From 997535f3ff4ea2b53193c3292e9a6ec39aa2ef7f Mon Sep 17 00:00:00 2001 From: Eduardo Kroetz Date: Thu, 27 Jun 2024 12:34:49 -0300 Subject: [PATCH] refatorando endpoints e ajustando testes --- Hotel.Domain/Controllers/AdminController.cs | 6 +- .../Controllers/CustomerController.cs | 6 +- .../Controllers/EmployeeController.cs | 6 +- .../Controllers/FeedbackController.cs | 8 +- Hotel.Domain/Controllers/ReportController.cs | 6 +- .../Controllers/ReservationControllers.cs | 16 +- Hotel.Domain/Controllers/RoomController.cs | 28 ++-- Hotel.Domain/DTOs/Base/User/UpdateFields.cs | 3 +- .../DTOs/FeedbackDTOs/UpdateComment.cs | 9 -- .../DTOs/FeedbackDTOs/UpdateFeedback.cs | 14 -- .../DTOs/FeedbackDTOs/UpdateFields.cs | 7 + Hotel.Domain/DTOs/ReportDTOs/NewPriority.cs | 3 + .../DTOs/ReservationDTOs/UpdateCheckIn.cs | 9 -- .../DTOs/ReservationDTOs/UpdateCheckOut.cs | 9 -- .../DTOs/ReservationDTOs/UpdateFields.cs | 4 + Hotel.Domain/DTOs/RoomDTOs/UpdateFields.cs | 11 ++ Hotel.Domain/DTOs/RoomDTOs/UpdatePriceDTO.cs | 11 -- .../Controllers/AdminControllerTests.cs | 50 +++--- .../Controllers/CustomerControllerTests.cs | 2 +- .../Controllers/EmployeeControllerTests.cs | 23 +-- .../Controllers/FeedbackControllerTests.cs | 23 +-- .../Controllers/ReportControllerTests.cs | 9 +- .../Controllers/ReservationControllerTests.cs | 46 +++--- .../Controllers/RoomControllerTests.cs | 143 ++++++------------ .../IntegrationTests/Utilities/TestService.cs | 1 + 25 files changed, 183 insertions(+), 270 deletions(-) delete mode 100644 Hotel.Domain/DTOs/FeedbackDTOs/UpdateComment.cs delete mode 100644 Hotel.Domain/DTOs/FeedbackDTOs/UpdateFeedback.cs create mode 100644 Hotel.Domain/DTOs/FeedbackDTOs/UpdateFields.cs create mode 100644 Hotel.Domain/DTOs/ReportDTOs/NewPriority.cs delete mode 100644 Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckIn.cs delete mode 100644 Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckOut.cs create mode 100644 Hotel.Domain/DTOs/ReservationDTOs/UpdateFields.cs create mode 100644 Hotel.Domain/DTOs/RoomDTOs/UpdateFields.cs delete mode 100644 Hotel.Domain/DTOs/RoomDTOs/UpdatePriceDTO.cs diff --git a/Hotel.Domain/Controllers/AdminController.cs b/Hotel.Domain/Controllers/AdminController.cs index 8349bdd..1222dca 100644 --- a/Hotel.Domain/Controllers/AdminController.cs +++ b/Hotel.Domain/Controllers/AdminController.cs @@ -154,11 +154,11 @@ public async Task UpdateAddressAsync([FromBody] Address address) //Editar gênero do administrador. //Administradores autenticados podem acessar. - [HttpPatch("gender/{gender:int}")] - public async Task UpdateGenderAsync([FromRoute] int gender) + [HttpPatch("gender")] + public async Task UpdateGenderAsync([FromBody] UpdateGender updateGender) { var adminId = _userService.GetUserIdentifier(User); - return Ok(await _handler.HandleUpdateGenderAsync(adminId, (EGender)gender)); + return Ok(await _handler.HandleUpdateGenderAsync(adminId, (EGender)updateGender.Gender)); } //Editar data de nascimento do administrador. diff --git a/Hotel.Domain/Controllers/CustomerController.cs b/Hotel.Domain/Controllers/CustomerController.cs index aa17d29..6bcffd6 100644 --- a/Hotel.Domain/Controllers/CustomerController.cs +++ b/Hotel.Domain/Controllers/CustomerController.cs @@ -113,11 +113,11 @@ public async Task UpdateAddressAsync([FromBody] Address address) } // Endpoint para editar o gênero do cliente (usando ID do token) - [HttpPatch("gender/{gender:int}")] - public async Task UpdateGenderAsync([FromRoute] int gender) + [HttpPatch("gender")] + public async Task UpdateGenderAsync([FromBody] UpdateGender updateGender) { var customerId = _userService.GetUserIdentifier(User); - return Ok(await _handler.HandleUpdateGenderAsync(customerId, (EGender)gender)); + return Ok(await _handler.HandleUpdateGenderAsync(customerId, (EGender)updateGender.Gender)); } // Endpoint para editar a data de nascimento do cliente (usando ID do token) diff --git a/Hotel.Domain/Controllers/EmployeeController.cs b/Hotel.Domain/Controllers/EmployeeController.cs index 6ce53f2..39980e1 100644 --- a/Hotel.Domain/Controllers/EmployeeController.cs +++ b/Hotel.Domain/Controllers/EmployeeController.cs @@ -139,11 +139,11 @@ public async Task UpdateAddressAsync([FromBody] Address address) return Ok(await _handler.HandleUpdateAddressAsync(userId, address)); } - [HttpPatch("gender/{gender:int}")] - public async Task UpdateGenderAsync([FromRoute] int gender) + [HttpPatch("gender")] + public async Task UpdateGenderAsync([FromBody] UpdateGender updateGender) { var userId = _userService.GetUserIdentifier(User); - return Ok(await _handler.HandleUpdateGenderAsync(userId, (EGender)gender)); + return Ok(await _handler.HandleUpdateGenderAsync(userId, (EGender)updateGender.Gender)); } [HttpPatch("date-of-birth")] diff --git a/Hotel.Domain/Controllers/FeedbackController.cs b/Hotel.Domain/Controllers/FeedbackController.cs index 650359e..4f63f61 100644 --- a/Hotel.Domain/Controllers/FeedbackController.cs +++ b/Hotel.Domain/Controllers/FeedbackController.cs @@ -82,15 +82,15 @@ public async Task DeleteAsync([FromRoute] Guid id) } // Endpoint para atualizar a avaliação (rate) de um feedback - [HttpPatch("{Id:guid}/rate/{rate:int}")] - public async Task UpdateRateAsync([FromRoute] Guid id, [FromRoute] int rate) + [HttpPatch("rate/{Id:guid}")] + public async Task UpdateRateAsync([FromRoute] Guid id, [FromBody] UpdateRate update) { var customerId = _userService.GetUserIdentifier(User); - return Ok(await _handler.HandleUpdateRateAsync(id, rate, customerId)); + return Ok(await _handler.HandleUpdateRateAsync(id, update.Rate, customerId)); } // Endpoint para atualizar o comentário de um feedback - [HttpPatch("{Id:guid}/comment")] + [HttpPatch("comment/{Id:guid}")] public async Task UpdateCommentAsync([FromRoute] Guid id, [FromBody] UpdateComment updateComment) { var customerId = _userService.GetUserIdentifier(User); diff --git a/Hotel.Domain/Controllers/ReportController.cs b/Hotel.Domain/Controllers/ReportController.cs index 08985b5..89a6efa 100644 --- a/Hotel.Domain/Controllers/ReportController.cs +++ b/Hotel.Domain/Controllers/ReportController.cs @@ -87,7 +87,7 @@ public async Task CancelAsync([FromRoute] Guid id) } // Endpoint para atualizar prioridade - [HttpPatch("{id:guid}/priority/{priority:int}")] - public async Task CancelAsync([FromRoute] Guid id, [FromRoute] int priority) - => Ok(await _handler.HandleUpdatePriorityAsync((EPriority)priority, id)); + [HttpPatch("priority/{id:guid}")] + public async Task CancelAsync([FromRoute] Guid id, [FromBody] UpdatePriority priority) + => Ok(await _handler.HandleUpdatePriorityAsync((EPriority)priority.Priority, id)); } diff --git a/Hotel.Domain/Controllers/ReservationControllers.cs b/Hotel.Domain/Controllers/ReservationControllers.cs index 9ba76a5..49ae866 100644 --- a/Hotel.Domain/Controllers/ReservationControllers.cs +++ b/Hotel.Domain/Controllers/ReservationControllers.cs @@ -98,18 +98,18 @@ public async Task DeleteAsync([FromRoute] Guid id) //Atualizar check out. //Somente administradores ou funcionários com permissão podem atualizar check out de reservas que não são suas. //Administradores e funcionários tem acesso por padrão. - [HttpPatch("{Id:guid}/check-out")] + [HttpPatch("expected-check-out/{Id:guid}")] [AuthorizePermissions([EPermissions.UpdateReservationCheckout, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission], [ERoles.Customer])] - public async Task UpdateCheckoutAsync([FromRoute] Guid id, [FromBody] UpdateCheckOut updateCheckOut) - => Ok(await _handler.HandleUpdateExpectedCheckOutAsync(id, updateCheckOut.CheckOut)); + public async Task UpdateCheckoutAsync([FromRoute] Guid id, [FromBody] UpdateExpectedCheckOut update) + => Ok(await _handler.HandleUpdateExpectedCheckOutAsync(id, update.ExpectedCheckOut)); //Atualizar check in. //Somente administradores ou funcionários com permissão podem atualizar check in de reservas que não são suas. //Administradores e funcionários tem acesso por padrão. - [HttpPatch("{Id:guid}/check-in")] + [HttpPatch("expected-check-in/{Id:guid}")] [AuthorizePermissions([EPermissions.UpdateReservationCheckIn, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission], [ERoles.Customer])] - public async Task UpdateCheckInAsync([FromRoute] Guid id, [FromBody] UpdateCheckIn updateCheckIn) - => Ok(await _handler.HandleUpdateExpectedCheckInAsync(id, updateCheckIn.CheckIn)); + public async Task UpdateCheckInAsync([FromRoute] Guid id, [FromBody] UpdateExpectedCheckIn update) + => Ok(await _handler.HandleUpdateExpectedCheckInAsync(id, update.ExpectedCheckIn)); //Adicionar um serviço a uma reserva, ou seja, o cliente //requisitou o serviço e o serviço é adicionado através desse endpoint. @@ -135,14 +135,14 @@ public async Task ReservationCheckInAsync([FromRoute] Guid Id, [F return Ok(await _handler.HandleReservationCheckInAsync(Id, cardOptions.TokenId)); } - [HttpPatch("finish/{Id:guid}")] + [HttpPost("finish/{Id:guid}")] public async Task FinishReservationAsync([FromRoute] Guid Id) { var customerId = _userService.GetUserIdentifier(User); return Ok(await _handler.HandleFinishReservationAsync(Id, customerId)); } - [HttpPatch("cancel/{Id:guid}")] + [HttpPost("cancel/{Id:guid}")] public async Task CancelReservationAsync([FromRoute] Guid Id) { var customerId = _userService.GetUserIdentifier(User); diff --git a/Hotel.Domain/Controllers/RoomController.cs b/Hotel.Domain/Controllers/RoomController.cs index c18e7fc..69a8fe4 100644 --- a/Hotel.Domain/Controllers/RoomController.cs +++ b/Hotel.Domain/Controllers/RoomController.cs @@ -81,33 +81,33 @@ public async Task RemoveServiceAsync([FromRoute] Guid id, [FromRo => Ok(await _handler.HandleRemoveServiceAsync(id, serviceId)); // Endpoint para atualizar o número de um quarto (com permissão) - [HttpPatch("{id:guid}/number/{number:int}")] + [HttpPatch("number/{id:guid}")] [AuthorizePermissions([EPermissions.UpdateRoomNumber, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission])] - public async Task UpdateNumberAsync([FromRoute] Guid id, [FromRoute] int number) - => Ok(await _handler.HandleUpdateNumberAsync(id, number)); + public async Task UpdateNumberAsync([FromRoute] Guid id, [FromBody] UpdateRoomNumber update) + => Ok(await _handler.HandleUpdateNumberAsync(id, update.Number)); // Endpoint para atualizar o nome de um quarto (com permissão) - [HttpPatch("{id:guid}")] + [HttpPatch("name/{id:guid}")] [AuthorizePermissions([EPermissions.UpdateRoomName, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission])] - public async Task UpdateNameAsync([FromRoute] Guid id, [FromQuery] string name) - => Ok(await _handler.HandleUpdateNameAsync(id, name)); + public async Task UpdateNameAsync([FromRoute] Guid id, [FromBody] UpdateRoomName update) + => Ok(await _handler.HandleUpdateNameAsync(id, update.Name)); // Endpoint para atualizar a capacidade de um quarto (com permissão) - [HttpPatch("{id:guid}/capacity/{capacity:int}")] + [HttpPatch("capacity/{id:guid}")] [AuthorizePermissions([EPermissions.UpdateRoomCapacity, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission])] - public async Task UpdateCapacityAsync([FromRoute] Guid id, [FromRoute] int capacity) - => Ok(await _handler.HandleUpdateCapacityAsync(id, capacity)); + public async Task UpdateCapacityAsync([FromRoute] Guid id, [FromBody] UpdateRoomCapacity update) + => Ok(await _handler.HandleUpdateCapacityAsync(id, update.Capacity)); // Endpoint para atualizar a categoria de um quarto (com permissão) - [HttpPatch("{id:guid}/category/{categoryId:guid}")] + [HttpPatch("category/{id:guid}")] [AuthorizePermissions([EPermissions.UpdateRoomCategory, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission])] - public async Task UpdateCategoryAsync([FromRoute] Guid id, [FromRoute] Guid categoryId) - => Ok(await _handler.HandleUpdateCategoryAsync(id, categoryId)); + public async Task UpdateCategoryAsync([FromRoute] Guid id, [FromBody] UpdateRoomCategory update) + => Ok(await _handler.HandleUpdateCategoryAsync(id, update.CategoryId)); // Endpoint para atualizar o preço de um quarto (com permissão) - [HttpPatch("{id:guid}/price")] + [HttpPatch("price/{id:guid}")] [AuthorizePermissions([EPermissions.UpdateRoomPrice, EPermissions.DefaultAdminPermission, EPermissions.DefaultEmployeePermission])] - public async Task UpdatePriceAsync([FromRoute] Guid id, [FromBody] UpdatePriceDTO update) + public async Task UpdatePriceAsync([FromRoute] Guid id, [FromBody] UpdateRoomPrice update) => Ok(await _handler.HandleUpdatePriceAsync(id, update.Price)); // Endpoint para ativar um quarto diff --git a/Hotel.Domain/DTOs/Base/User/UpdateFields.cs b/Hotel.Domain/DTOs/Base/User/UpdateFields.cs index 0446aad..b8b2da4 100644 --- a/Hotel.Domain/DTOs/Base/User/UpdateFields.cs +++ b/Hotel.Domain/DTOs/Base/User/UpdateFields.cs @@ -2,4 +2,5 @@ public record UpdateDateOfBirth(DateTime? DateOfBirth) : IDataTransferObject; -public record UpdatePassword(string Password) : IDataTransferObject; \ No newline at end of file +public record UpdatePassword(string Password) : IDataTransferObject; +public record UpdateGender(int Gender); \ No newline at end of file diff --git a/Hotel.Domain/DTOs/FeedbackDTOs/UpdateComment.cs b/Hotel.Domain/DTOs/FeedbackDTOs/UpdateComment.cs deleted file mode 100644 index b17ddf6..0000000 --- a/Hotel.Domain/DTOs/FeedbackDTOs/UpdateComment.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Hotel.Domain.DTOs.FeedbackDTOs; - -public class UpdateComment -{ - public UpdateComment(string comment) - => Comment = comment; - - public string Comment { get; private set; } -} diff --git a/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFeedback.cs b/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFeedback.cs deleted file mode 100644 index e597d0e..0000000 --- a/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFeedback.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Hotel.Domain.DTOs.FeedbackDTOs; - -public class UpdateFeedback : IDataTransferObject -{ - public UpdateFeedback(string comment, int rate) - { - Comment = comment; - Rate = rate; - } - - public string Comment { get; private set; } - public int Rate { get; private set; } -} - diff --git a/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFields.cs b/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFields.cs new file mode 100644 index 0000000..f7e36f3 --- /dev/null +++ b/Hotel.Domain/DTOs/FeedbackDTOs/UpdateFields.cs @@ -0,0 +1,7 @@ +namespace Hotel.Domain.DTOs.FeedbackDTOs; + +public record UpdateFeedback(string Comment, int Rate); + +public record UpdateComment(string Comment); + +public record UpdateRate(int Rate); \ No newline at end of file diff --git a/Hotel.Domain/DTOs/ReportDTOs/NewPriority.cs b/Hotel.Domain/DTOs/ReportDTOs/NewPriority.cs new file mode 100644 index 0000000..59e6911 --- /dev/null +++ b/Hotel.Domain/DTOs/ReportDTOs/NewPriority.cs @@ -0,0 +1,3 @@ +namespace Hotel.Domain.DTOs.ReportDTOs; + +public record UpdatePriority(int Priority); \ No newline at end of file diff --git a/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckIn.cs b/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckIn.cs deleted file mode 100644 index 389def5..0000000 --- a/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckIn.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Hotel.Domain.DTOs.ReservationDTOs; - -public class UpdateCheckIn -{ - public UpdateCheckIn(DateTime checkIn) - => CheckIn = checkIn; - - public DateTime CheckIn { get; private set; } -} diff --git a/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckOut.cs b/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckOut.cs deleted file mode 100644 index 2262a5c..0000000 --- a/Hotel.Domain/DTOs/ReservationDTOs/UpdateCheckOut.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Hotel.Domain.DTOs.ReservationDTOs; - -public class UpdateCheckOut -{ - public UpdateCheckOut(DateTime checkOut) - => CheckOut = checkOut; - - public DateTime CheckOut { get; private set; } -} diff --git a/Hotel.Domain/DTOs/ReservationDTOs/UpdateFields.cs b/Hotel.Domain/DTOs/ReservationDTOs/UpdateFields.cs new file mode 100644 index 0000000..5824f95 --- /dev/null +++ b/Hotel.Domain/DTOs/ReservationDTOs/UpdateFields.cs @@ -0,0 +1,4 @@ +namespace Hotel.Domain.DTOs.ReservationDTOs; + +public record UpdateExpectedCheckIn(DateTime ExpectedCheckIn); +public record UpdateExpectedCheckOut(DateTime ExpectedCheckOut); diff --git a/Hotel.Domain/DTOs/RoomDTOs/UpdateFields.cs b/Hotel.Domain/DTOs/RoomDTOs/UpdateFields.cs new file mode 100644 index 0000000..e897be7 --- /dev/null +++ b/Hotel.Domain/DTOs/RoomDTOs/UpdateFields.cs @@ -0,0 +1,11 @@ +namespace Hotel.Domain.DTOs.RoomDTOs; + +public record UpdateRoomPrice(decimal Price); + +public record UpdateRoomNumber(int Number); + +public record UpdateRoomName(string Name); + +public record UpdateRoomDescription(string Description); +public record UpdateRoomCapacity(int Capacity); +public record UpdateRoomCategory(Guid CategoryId); \ No newline at end of file diff --git a/Hotel.Domain/DTOs/RoomDTOs/UpdatePriceDTO.cs b/Hotel.Domain/DTOs/RoomDTOs/UpdatePriceDTO.cs deleted file mode 100644 index b2f6223..0000000 --- a/Hotel.Domain/DTOs/RoomDTOs/UpdatePriceDTO.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Hotel.Domain.DTOs.RoomDTOs; - -public class UpdatePriceDTO : IDataTransferObject -{ - public UpdatePriceDTO(decimal price) - { - Price = price; - } - - public decimal Price { get; private set; } -} diff --git a/Hotel.Tests/IntegrationTests/Controllers/AdminControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/AdminControllerTests.cs index b2e5513..6b39b9f 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/AdminControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/AdminControllerTests.cs @@ -153,8 +153,7 @@ public async Task DeleteLoggedAdmin_ShouldReturn_OK() new Address("United Kingdom", "London", "UK-123", 456) ); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var dbContext = _factory.Services.GetRequiredService(); await dbContext.Admins.AddAsync(admin); @@ -329,8 +328,7 @@ public async Task UpdateLoggedAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new UpdateUser("Jão", "Pedro", "+55 (41) 93651-3210", EGender.Feminine, DateTime.Now.AddYears(-20), "Brazil", "Curitiba", "PR-404", 404); @@ -372,8 +370,7 @@ public async Task UpdateAdminName_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new Name("John", "Wick"); @@ -407,8 +404,7 @@ public async Task UpdateEmailAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new Email("feeRriber@gmail.com"); @@ -441,8 +437,7 @@ public async Task UpdatePhoneAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new Phone("+55 (62) 99156-3449"); @@ -475,8 +470,7 @@ public async Task UpdateAddressAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new Address("Brazil", "Florianópolis", "SC-909", 909); @@ -512,11 +506,10 @@ public async Task UpdateGenderAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender/2", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender", new UpdateGender(2)); //Assert var updatedAdmin = await _dbContext.Admins.FirstOrDefaultAsync(x => x.Id == admin.Id); @@ -544,8 +537,7 @@ public async Task UpdateDateOfBirthAdmin_ShouldReturn_OK() await _dbContext.Admins.AddAsync(admin); await _dbContext.SaveChangesAsync(); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client, admin); var body = new UpdateDateOfBirth(DateTime.Now.AddYears(-35)); @@ -590,14 +582,15 @@ public async Task UpdateDateOfBirthAdmin_ShouldReturn_OK() [DataRow("CreateResponsibility", "v1/responsibilities", "POST")] [DataRow("EditResponsibility", "v1/responsibilities/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PUT")] [DataRow("DeleteResponsibility", "v1/responsibilities/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("DeleteInvoice", "v1/room-invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("GetInvoices", "v1/room-invoices", "GET")] - [DataRow("GetInvoice", "v1/room-invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "GET")] + [DataRow("DeleteInvoice", "v1/invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] + [DataRow("GetInvoices", "v1/invoices", "GET")] + [DataRow("GetInvoice", "v1/invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "GET")] [DataRow("DeleteReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("UpdateReservationCheckout", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/check-out", "PATCH")] - [DataRow("UpdateReservationCheckIn", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/check-in", "PATCH")] + [DataRow("UpdateReservationCheckout", "v1/reservations/expected-check-out/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateReservationCheckIn", "v1/reservations/expected-check-in/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("AddServiceToReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/e3347565-8ec7-4a3b-be3a-951317bb53dc", "POST")] [DataRow("RemoveServiceFromReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] + [DataRow("ReservationCheckIn", "v1/reservations/check-in/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "POST")] [DataRow("CreateCategory", "v1/categories", "POST")] [DataRow("EditCategory", "v1/categories/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PUT")] [DataRow("DeleteCategory", "v1/categories/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] @@ -611,11 +604,11 @@ public async Task UpdateDateOfBirthAdmin_ShouldReturn_OK() [DataRow("DeleteRoom", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] [DataRow("AddRoomService", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/e3347565-8ec7-4a3b-be3a-951317bb53dc", "POST")] [DataRow("RemoveRoomService", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("UpdateRoomName", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414?name=ola", "PATCH")] - [DataRow("UpdateRoomNumber", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/number/1", "PATCH")] - [DataRow("UpdateRoomCapacity", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/capacity/2", "PATCH")] - [DataRow("UpdateRoomCategory", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/category/62eb01d1-a7ba-4c09-ae5b-5ec6b5071577", "PATCH")] - [DataRow("UpdateRoomPrice", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/price", "PATCH")] + [DataRow("UpdateRoomName", "v1/rooms/name/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomNumber", "v1/rooms/number/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomCapacity", "v1/rooms/capacity/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomCategory", "v1/rooms/category/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomPrice", "v1/rooms/price/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("EnableRoom", "v1/rooms/enable/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("DisableRoom", "v1/rooms/disable/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("GetServices", "v1/services", "GET")] @@ -651,8 +644,7 @@ public void AccessEndpointsWithOutPermission_ShouldReturn_FORBIDDEN(string permi var permission = _dbContext.Permissions.FirstOrDefault(x => x.Name.Equals(permissionName)); admin.RemovePermission(permission!); - var token = _tokenService.GenerateToken(admin); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + _factory.Login(_client,admin); //Act var response = method switch diff --git a/Hotel.Tests/IntegrationTests/Controllers/CustomerControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/CustomerControllerTests.cs index 2ddc3ab..5c787f5 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/CustomerControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/CustomerControllerTests.cs @@ -582,7 +582,7 @@ public async Task UpdateGenderCustomer_ShouldReturn_OK() _factory.Login(_client, customer); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender/2", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender", new UpdateGender(2)); //Assert var updatedCustomer = await _dbContext.Customers.FirstOrDefaultAsync(x => x.Id == customer.Id); diff --git a/Hotel.Tests/IntegrationTests/Controllers/EmployeeControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/EmployeeControllerTests.cs index 82f96e9..2766568 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/EmployeeControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/EmployeeControllerTests.cs @@ -490,7 +490,7 @@ public async Task UpdateEmployeeGender_ShouldReturn_OK() _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender/2", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/gender", new UpdateGender(2)); //Assert var updatedEmployee = await _dbContext.Employees.FirstOrDefaultAsync(x => x.Id == employee.Id); @@ -639,14 +639,15 @@ public async Task RemoveEmployeeResponsability_ShouldReturn_OK() [DataRow("CreateResponsibility", "v1/responsibilities", "POST")] [DataRow("EditResponsibility", "v1/responsibilities/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PUT")] [DataRow("DeleteResponsibility", "v1/responsibilities/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("DeleteInvoice", "v1/room-invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("GetInvoices", "v1/room-invoices", "GET")] - [DataRow("GetInvoice", "v1/room-invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "GET")] + [DataRow("DeleteInvoice", "v1/invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] + [DataRow("GetInvoices", "v1/invoices", "GET")] + [DataRow("GetInvoice", "v1/invoices/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "GET")] [DataRow("DeleteReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("UpdateReservationCheckout", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/check-out", "PATCH")] - [DataRow("UpdateReservationCheckIn", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/check-in", "PATCH")] + [DataRow("UpdateReservationCheckout", "v1/reservations/expected-check-out/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateReservationCheckIn", "v1/reservations/expected-check-in/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("AddServiceToReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/e3347565-8ec7-4a3b-be3a-951317bb53dc", "POST")] [DataRow("RemoveServiceFromReservation", "v1/reservations/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] + [DataRow("ReservationCheckIn", "v1/reservations/check-in/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "POST")] [DataRow("CreateCategory", "v1/categories", "POST")] [DataRow("EditCategory", "v1/categories/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PUT")] [DataRow("DeleteCategory", "v1/categories/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] @@ -660,11 +661,11 @@ public async Task RemoveEmployeeResponsability_ShouldReturn_OK() [DataRow("DeleteRoom", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] [DataRow("AddRoomService", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/e3347565-8ec7-4a3b-be3a-951317bb53dc", "POST")] [DataRow("RemoveRoomService", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/services/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "DELETE")] - [DataRow("UpdateRoomName", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414?name=ola", "PATCH")] - [DataRow("UpdateRoomNumber", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/number/1", "PATCH")] - [DataRow("UpdateRoomCapacity", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/capacity/2", "PATCH")] - [DataRow("UpdateRoomCategory", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/category/62eb01d1-a7ba-4c09-ae5b-5ec6b5071577", "PATCH")] - [DataRow("UpdateRoomPrice", "v1/rooms/f6c5e02b-a0ae-429e-beb3-d433d51ad414/price", "PATCH")] + [DataRow("UpdateRoomName", "v1/rooms/name/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomNumber", "v1/rooms/number/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomCapacity", "v1/rooms/capacity/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomCategory", "v1/rooms/category/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] + [DataRow("UpdateRoomPrice", "v1/rooms/price/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("EnableRoom", "v1/rooms/enable/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("DisableRoom", "v1/rooms/disable/f6c5e02b-a0ae-429e-beb3-d433d51ad414", "PATCH")] [DataRow("GetServices", "v1/services", "GET")] diff --git a/Hotel.Tests/IntegrationTests/Controllers/FeedbackControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/FeedbackControllerTests.cs index b514ad4..019e8b5 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/FeedbackControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/FeedbackControllerTests.cs @@ -109,7 +109,7 @@ public async Task CreateFeedback_ShouldReturn_OK() await _dbContext.Reservations.AddAsync(reservation); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); var body = new CreateFeedback("Estadia perfeita, serviço impecável!", 10, reservation.Id); @@ -175,7 +175,7 @@ public async Task DeleteFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); //Act var response = await _client.DeleteAsync($"{_baseUrl}/{feedback.Id}"); @@ -216,7 +216,7 @@ public async Task UpdateFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); var body = new UpdateFeedback("A suite é de outro mundo, uma das melhores que já fui, recomendo!", 10); @@ -260,12 +260,12 @@ public async Task UpdateFeedbackComment_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); var body = new UpdateComment("Serviço é bom e o apartamento é confotável. Entrega o que promete."); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{feedback.Id}/comment", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/comment/{feedback.Id}", body); //Assert var updatedFeedback = await _dbContext.Feedbacks.FirstOrDefaultAsync(x => x.Id == feedback.Id); @@ -279,14 +279,15 @@ public async Task UpdateFeedbackComment_ShouldReturn_OK() public async Task UpdateFeedbackRate_ShouldReturn_OK() { //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{_feedbacks[0].Id}/rate/8", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/rate/{_feedbacks[0].Id}", new UpdateRate(8)); //Assert var updatedFeedback = await _dbContext.Feedbacks.FirstOrDefaultAsync(x => x.Id == _feedbacks[0].Id); Assert.IsNotNull(response); response.EnsureSuccessStatusCode(); - Assert.AreEqual(updatedFeedback!.Rate, 8); + + Assert.AreEqual(8,updatedFeedback!.Rate); } [TestMethod] @@ -315,7 +316,7 @@ public async Task AddLikeToFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); //Act var response = await _client.PatchAsJsonAsync($"{_baseUrl}/add-like/{feedback.Id}", new { }); @@ -357,7 +358,7 @@ public async Task RemoveLikeFromFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); //Act var response = await _client.PatchAsJsonAsync($"{_baseUrl}/remove-like/{feedback.Id}", new { }); @@ -436,7 +437,7 @@ public async Task AddDislikeToFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); // Atua var response = await _client.PatchAsJsonAsync($"{_baseUrl}/add-dislike/{feedback.Id}", new { }); @@ -478,7 +479,7 @@ public async Task RemoveDislikeFromFeedback_ShouldReturn_OK() await _dbContext.Feedbacks.AddAsync(feedback); await _dbContext.SaveChangesAsync(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.GenerateToken(customer)); + _factory.Login(_client, customer); // Atua var response = await _client.PatchAsJsonAsync($"{_baseUrl}/remove-dislike/{feedback.Id}", new { }); diff --git a/Hotel.Tests/IntegrationTests/Controllers/ReportControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/ReportControllerTests.cs index b96bc94..c43423a 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/ReportControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/ReportControllerTests.cs @@ -538,10 +538,9 @@ public async Task UpdateReportPriority_ShouldReturn_OK() await _dbContext.Reports.AddAsync(report); await _dbContext.SaveChangesAsync(); - var priority = EPriority.Critical; - + var priority = new UpdatePriority(5); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{report.Id}/priority/{(int)priority}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/priority/{report.Id}", priority); //Assert @@ -558,7 +557,7 @@ public async Task UpdateReportPriority_ShouldReturn_OK() Assert.AreEqual(report.Id, content.Data.Id); Assert.AreEqual(report.Summary, updatedReport.Summary); Assert.AreEqual(report.Description, updatedReport.Description); - Assert.AreEqual(priority, updatedReport.Priority); + Assert.AreEqual(priority.Priority, (int)updatedReport.Priority); Assert.AreEqual(report.Resolution, updatedReport.Resolution); Assert.AreEqual(report.EmployeeId, updatedReport.EmployeeId); Assert.AreEqual(EStatus.Pending, updatedReport.Status); @@ -568,7 +567,7 @@ public async Task UpdateReportPriority_ShouldReturn_OK() public async Task UpdateNonexistReportPriority_ShouldReturn_NOT_FOUND() { //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{Guid.NewGuid()}/priority/3", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/priority/{Guid.NewGuid()}", new UpdatePriority(3)); //Assert var content = await _testService.DeserializeResponse(response); diff --git a/Hotel.Tests/IntegrationTests/Controllers/ReservationControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/ReservationControllerTests.cs index 7c5101f..77db2cb 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/ReservationControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/ReservationControllerTests.cs @@ -448,7 +448,7 @@ public async Task UpdateExpectedCheckOut_ShouldReturn_OK() var newExpectedCheckOut = DateTime.Now.AddDays(3); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-out", new UpdateCheckOut(newExpectedCheckOut)); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-out/{reservation.Id}", new UpdateExpectedCheckOut(newExpectedCheckOut)); // Assert response.EnsureSuccessStatusCode(); @@ -469,10 +469,10 @@ public async Task UpdateExpectedCheckOut_ShouldReturn_OK() [TestMethod] public async Task UpdateExpectedCheckOut_WithNonexistReservation_ShouldReturn_NOT_FOUND() { - var body = new UpdateCheckOut(DateTime.Now.AddDays(3)); + var body = new UpdateExpectedCheckOut(DateTime.Now.AddDays(3)); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{Guid.NewGuid()}/check-out", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-out/{Guid.NewGuid()}", body); //Assert Assert.IsNotNull(response); @@ -501,7 +501,7 @@ public async Task UpdateExpectedCheckOut_WithCheckedOutStatus_ShouldReturn_BAD_R // Act var newExpectedCheckOut = DateTime.Now.AddDays(7); - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-out", new UpdateCheckOut(newExpectedCheckOut)); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-out/{reservation.Id}", new UpdateExpectedCheckOut(newExpectedCheckOut)); // Assert Assert.IsNotNull(response); @@ -529,10 +529,10 @@ public async Task UpdateExpectedCheckOut_WithCancelledStatus_ShouldReturn_BAD_RE await _dbContext.SaveChangesAsync(); var newExpectedCheckOut = DateTime.Now.AddDays(7); - var body = new UpdateCheckOut(newExpectedCheckOut); + var body = new UpdateExpectedCheckOut(newExpectedCheckOut); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-out", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-out/{reservation.Id}", body); // Assert Assert.IsNotNull(response); @@ -557,10 +557,10 @@ public async Task UpdateExpectedCheckIn_ShouldReturn_OK() var reservation = await _testService.CreateReservationAsync(customer, new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(9), room.Id, 3)); var newExpectedCheckIn = DateTime.Now.AddDays(7); - var body = new UpdateCheckIn(newExpectedCheckIn); + var body = new UpdateExpectedCheckIn(newExpectedCheckIn); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-in", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-in/{reservation.Id}", body); // Assert Assert.IsNotNull(response); @@ -583,10 +583,10 @@ public async Task UpdateExpectedCheckIn_WithNonexistReservation_ShouldReturn_NOT { //Arange var reservationId = Guid.NewGuid(); - var body = new UpdateCheckIn(DateTime.Now.AddDays(5)); + var body = new UpdateExpectedCheckIn(DateTime.Now.AddDays(5)); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservationId}/check-in", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-in/{reservationId}", body); //Assert Assert.IsNotNull(response); @@ -611,10 +611,10 @@ public async Task UpdateExpectedCheckIn_WithCheckedOutStatus_ShouldReturn_BAD_RE reservation.Finish(); await _dbContext.SaveChangesAsync(); - var body = new UpdateCheckIn(DateTime.Now.AddDays(7)); + var body = new UpdateExpectedCheckIn(DateTime.Now.AddDays(7)); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-in", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-in/{reservation.Id}", body); // Assert Assert.IsNotNull(response); @@ -635,10 +635,10 @@ public async Task UpdateExpectedCheckIn_WithCancelledStatus_ShouldReturn_BAD_REQ var reservation = await _testService.CreateReservationAsync(customer, new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(6), room.Id, 4)); reservation.ToCancelled(); - var body = new UpdateCheckIn(DateTime.Now.AddDays(7)); + var body = new UpdateExpectedCheckIn(DateTime.Now.AddDays(7)); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-in", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-in/{reservation.Id}", body); // Assert Assert.IsNotNull(response); @@ -660,8 +660,8 @@ public async Task UpdateExpectedCheckIn_WithCheckedInStatus_ShouldReturn_BAD_REQ await _testService.ReservationCheckIn(reservation); // Act - var body = new UpdateCheckIn(DateTime.Now.AddDays(7)); - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{reservation.Id}/check-in", body); + var body = new UpdateExpectedCheckIn(DateTime.Now.AddDays(7)); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/expected-check-in/{reservation.Id}", body); // Assert Assert.IsNotNull(response); @@ -1071,7 +1071,7 @@ public async Task FinishReservation_ShouldReturn_OK() _factory.Login(_client, customer); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/finish/{reservation.Id}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/finish/{reservation.Id}", new { }); // Assert response.EnsureSuccessStatusCode(); @@ -1088,7 +1088,7 @@ public async Task FinishReservation_ShouldReturn_OK() public async Task FinishReservation_WithNonexistReservation_ShouldReturn_NOT_FOUND() { //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/finish/{Guid.NewGuid()}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/finish/{Guid.NewGuid()}", new { }); //Assert Assert.IsNotNull(response); @@ -1123,7 +1123,7 @@ public async Task FinishReservation_WithDifferentCustomer_ShouldReturn_UNAUTHORI // Act _factory.Login(_client, _customerToken); //Login com outro cliente que não criou a reserva - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/finish/{reservation.Id}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/finish/{reservation.Id}", new { }); // Assert Assert.IsNotNull(response); @@ -1154,7 +1154,7 @@ public async Task CancelReservation_ShouldReturn_OK() DateTime.Now.AddDays(1), DateTime.Now.AddDays(6), room.Id, 3)); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); // Assert Assert.IsNotNull(response); @@ -1178,7 +1178,7 @@ public async Task CancelReservation_ShouldReturn_OK() public async Task CancelReservation_WithNonexistReservation_ShouldReturn_NOT_FOUND() { //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/cancel/{Guid.NewGuid()}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/cancel/{Guid.NewGuid()}", new { }); //Assert Assert.IsNotNull(response); @@ -1201,7 +1201,7 @@ public async Task CancelReservation_WithDifferentCustomer_ShouldReturn_UNAUTHORI _factory.Login(_client, _customerToken); // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); // Assert Assert.IsNotNull(response); @@ -1234,7 +1234,7 @@ public async Task CancelReservation_WithStripeError_ShouldReturn_BAD_REQUEST_AND try { // Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); + var response = await _client.PostAsJsonAsync($"{_baseUrl}/cancel/{reservation.Id}", new { }); // Assert Assert.IsNotNull(response); diff --git a/Hotel.Tests/IntegrationTests/Controllers/RoomControllerTests.cs b/Hotel.Tests/IntegrationTests/Controllers/RoomControllerTests.cs index de47ea4..8870fe0 100644 --- a/Hotel.Tests/IntegrationTests/Controllers/RoomControllerTests.cs +++ b/Hotel.Tests/IntegrationTests/Controllers/RoomControllerTests.cs @@ -17,6 +17,8 @@ using Stripe; using Hotel.Domain.DTOs.Base.User; using Hotel.Domain.Entities.VerificationCodeEntity; +using System.Security.Cryptography; +using Hotel.Domain.DTOs.CategoryDTOs; namespace Hotel.Tests.IntegrationTests.Controllers; @@ -601,7 +603,7 @@ public async Task UpdateRoomName_ShouldReturn_OK() var newName = "Quarto padrão 55"; //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}?name={newName}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/name/{room.Id}", new UpdateRoomName(newName)); //Assert response.EnsureSuccessStatusCode(); @@ -651,22 +653,17 @@ public async Task UpdateRoomName_WithNameAlreadyExists_ShouldReturn_BAD_REQUEST( await _dbContext.Rooms.AddAsync(room40); await _dbContext.SaveChangesAsync(); - var newRoom = new EditorRoom("Quarto 40", 40, 45, 2, "Quarto padrão 40", _standardCategory.Id); - - var createRoomResponse = await _client.PostAsJsonAsync(_baseUrl, newRoom); - createRoomResponse.EnsureSuccessStatusCode(); - var roomId = JsonConvert.DeserializeObject>(await createRoomResponse.Content.ReadAsStringAsync())!.Data.Id; - var room = await _dbContext.Rooms.FirstAsync(x => x.Id == roomId); + var room = await _testService.CreateRoomAsync(new EditorRoom("Quarto 40", 40, 45, 2, "Quarto padrão 40", _standardCategory.Id)); var newName = "Quarto 50"; //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{roomId}?name={newName}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/name/{room.Id}", new UpdateRoomName(newName)); //Assert Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); var content = await _testService.DeserializeResponse(response); - var updatedRoom = await _dbContext.Rooms.FirstAsync(x => x.Id == roomId); + var updatedRoom = await _dbContext.Rooms.FirstAsync(x => x.Id == room.Id); Assert.AreEqual("Esse nome já está cadastrado.",content.Errors[0]); @@ -697,7 +694,7 @@ public async Task UpdateRoomName_WithNameAlreadyExists_ShouldReturn_BAD_REQUEST( var activePrices = _stripePriceService.ListAsync(priceListOptions).Result.Data; foreach (var activePrice in activePrices) - Assert.AreEqual(newRoom.Price * 100, activePrice.UnitAmountDecimal); + Assert.AreEqual(room.Price * 100, activePrice.UnitAmountDecimal); } [TestMethod] @@ -710,14 +707,13 @@ public async Task UpdateRoomNumber_ShouldReturn_OK() var newNumber = 16; //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}/number/{newNumber}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/number/{room.Id}/", new UpdateRoomNumber(newNumber)); //Assert response.EnsureSuccessStatusCode(); var content = await _testService.DeserializeResponse(response); var updatedRoom = await _dbContext.Rooms.FirstAsync(x => x.Id == room.Id); - Assert.AreEqual("Número atualizado com sucesso!", content.Message); Assert.AreEqual(0, content.Errors.Count); @@ -740,28 +736,20 @@ public async Task UpdateRoomNumber_WithNumberAlreadyExists_ShouldReturn_BAD_REQU var factory = new HotelWebApplicationFactory(); var client = factory.CreateClient(); var dbContext = factory.Services.GetRequiredService(); - _factory.Login(client, _rootAdminToken); + var testService = new TestService(dbContext ,factory, client, _rootAdminToken); - var category = new Category("Basic", "Hospedagems básicos", 40); - var room = new Room("Quarto 2",2, 35, 2, "Quarto básico 2", category); - - await dbContext.Categories.AddAsync(category); - await dbContext.Rooms.AddRangeAsync( - [ - new Room("Quarto 5",5, 43, 2, "Quarto básico 4",category), - room - ]); - await dbContext.SaveChangesAsync(); + var category = await testService.CreateCategoryAsync(new EditorCategory("Basic", "Hospedagems básicos", 40)); + var room = await testService.CreateRoomAsync(new EditorRoom("Quarto 2", 2, 35, 2, "Quarto básico 2", category.Id)); + await testService.CreateRoomAsync(new EditorRoom("Quarto 5", 5, 43, 2, "Quarto básico 4", category.Id)); //Act - var response = await client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}/number/5", new { }); + var response = await client.PatchAsJsonAsync($"{_baseUrl}/number/{room.Id}/", new UpdateRoomNumber(5)); //Assert Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); - var content = await _testService.DeserializeResponse(response); + var content = await testService.DeserializeResponse(response); - Assert.AreEqual("Esse número já está cadastrado.", content.Errors[0]); } @@ -773,9 +761,9 @@ public async Task UpdateRoomCategory_ShouldReturn_OK() await _dbContext.Rooms.AddAsync(room); await _dbContext.SaveChangesAsync(); - var newCategoryId = _deluxeCategory.Id; + var newCategory = new UpdateRoomCategory(_basicCategory.Id); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}/category/{newCategoryId}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/category/{room.Id}", newCategory); //Assert response.EnsureSuccessStatusCode(); @@ -792,7 +780,7 @@ public async Task UpdateRoomCategory_ShouldReturn_OK() Assert.AreEqual(room.Price, updatedRoom.Price); Assert.AreEqual(room.Capacity, updatedRoom.Capacity); Assert.AreEqual(room.Description, updatedRoom.Description); - Assert.AreEqual(newCategoryId, updatedRoom.CategoryId); + Assert.AreEqual(newCategory.CategoryId, updatedRoom.CategoryId); Assert.AreEqual(room.Images.Count, updatedRoom.Images.Count); Assert.AreEqual(room.Status, updatedRoom.Status); Assert.AreEqual(room.CreatedAt, updatedRoom.CreatedAt); @@ -807,7 +795,7 @@ public async Task UpdateRoomCategory_WithNonexistCategory_ShouldReturn_NOT_FOUND await _dbContext.SaveChangesAsync(); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}/category/{Guid.NewGuid()}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/category/{room.Id}", new UpdateRoomCategory(Guid.NewGuid())); //Assert Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); @@ -827,9 +815,9 @@ public async Task UpdateRoomPrice_ShouldReturn_OK() var createRoomResponse = await _client.PostAsJsonAsync(_baseUrl, room); var roomId = JsonConvert.DeserializeObject>(await createRoomResponse.Content.ReadAsStringAsync())!.Data.Id; - var newPrice = new UpdatePriceDTO(146.00m); + var newPrice = new UpdateRoomPrice(146.00m); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{roomId}/price", newPrice); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/price/{roomId}", newPrice); //Assert response.EnsureSuccessStatusCode(); @@ -848,7 +836,7 @@ public async Task UpdateRoomPrice_ShouldReturn_OK() } [TestMethod] - public async Task UpdateRoomPrice_WithPendingReservationAssociated_ShouldReturn_BAD_REQUEST() + public async Task UpdateRoomPrice_WithAssociatedPendingReservation_ShouldReturn_BAD_REQUEST() { //Arange var newCustomer = new CreateUser @@ -862,36 +850,21 @@ public async Task UpdateRoomPrice_WithPendingReservationAssociated_ShouldReturn_ "Brazil", "Porto Velho", "RO-3030", 3030 ); - var verificationCode = new VerificationCode(new Email(newCustomer.Email)); - await _dbContext.VerificationCodes.AddAsync(verificationCode); - await _dbContext.SaveChangesAsync(); - - var createCustomerResponse = await _client.PostAsJsonAsync($"v1/register/customers?code={verificationCode.Code}", newCustomer); - var createCustomerContent = JsonConvert.DeserializeObject>(await createCustomerResponse.Content.ReadAsStringAsync())!; - var customer = await _dbContext.Customers.FirstAsync(x => x.Id == createCustomerContent.Data.Id); - - - var newRoom = new EditorRoom("Quarto 20",20, 43, 13, "Quarto deluxe", _deluxeCategory.Id); - var createRoomResponse = await _client.PostAsJsonAsync(_baseUrl, newRoom); - var roomId = JsonConvert.DeserializeObject>(await createRoomResponse.Content.ReadAsStringAsync())!.Data.Id; - - _factory.Login(_client, customer); - - var newReservation = new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(2), roomId, 1); - _client.PostAsJsonAsync("v1/reservations", newReservation).Result.EnsureSuccessStatusCode(); + var customer = await _testService.CreateCustomerAsync(newCustomer); + var room = await _testService.CreateRoomAsync(new EditorRoom("Quarto 20", 20, 43, 13, "Quarto deluxe", _deluxeCategory.Id)); + var reservation = await _testService.CreateReservationAsync(customer ,new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(2), room.Id, 1)); _factory.Login(_client, _rootAdminToken); - var newPrice = new UpdatePriceDTO(196.00m); + var newPrice = new UpdateRoomPrice(196.00m); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{roomId}/price", newPrice); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/price/{room.Id}", newPrice); //Assert Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); var content = await _testService.DeserializeResponse(response); - Assert.AreEqual("Não foi possível atualizar o preço pois possuem reservas pendentes relacionadas a hospedagem.", content.Errors[0]); } @@ -911,52 +884,32 @@ public async Task UpdateRoomPrice_WithAssociatedNonPendingReservation_ShouldRetu "Brazil", "Sobral", "CE-2929", 2929 ); - var verificationCode = new VerificationCode(new Email(newCustomer.Email)); - await _dbContext.VerificationCodes.AddAsync(verificationCode); - await _dbContext.SaveChangesAsync(); - - var createCustomerResponse = await _client.PostAsJsonAsync($"v1/register/customers?code={verificationCode.Code}", newCustomer); - var createCustomerContent = JsonConvert.DeserializeObject>(await createCustomerResponse.Content.ReadAsStringAsync())!; - var customer = await _dbContext.Customers.FirstAsync(x => x.Id == createCustomerContent.Data.Id); - - - var newRoom = new EditorRoom("Quarto 21",21, 43, 13, "Quarto deluxe", _deluxeCategory.Id); - var createRoomResponse = await _client.PostAsJsonAsync(_baseUrl, newRoom); - var roomId = JsonConvert.DeserializeObject>(await createRoomResponse.Content.ReadAsStringAsync())!.Data.Id; - - _factory.Login(_client, customer); - - var newReservation = new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(2), roomId, 1); - var createReservationResponse = await _client.PostAsJsonAsync("v1/reservations", newReservation); - var reservationId = JsonConvert.DeserializeObject>(await createReservationResponse.Content.ReadAsStringAsync())!.Data.Id; - - var reservation = await _dbContext.Reservations.FirstAsync(x => x.Id == reservationId); + var customer = await _testService.CreateCustomerAsync(newCustomer); + var room = await _testService.CreateRoomAsync(new EditorRoom("Quarto 21", 21, 43, 13, "Quarto deluxe", _deluxeCategory.Id)); + var reservation = await _testService.CreateReservationAsync(customer,new CreateReservation(DateTime.Now.AddDays(1), DateTime.Now.AddDays(2), room.Id, 1)); reservation.ToCheckIn(); - await _dbContext.SaveChangesAsync(); - _factory.Login(_client, _rootAdminToken); - - var newPrice = new UpdatePriceDTO(196.00m); + var newPrice = new UpdateRoomPrice(196.00m); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{roomId}/price", newPrice); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/price/{room.Id}", newPrice); //Assert response.EnsureSuccessStatusCode(); var content = await _testService.DeserializeResponse(response); - var updatedRoom = await _dbContext.Rooms.FirstAsync(x => x.Id == roomId); + var updatedRoom = await _dbContext.Rooms.FirstAsync(x => x.Id == room.Id); Assert.AreEqual("Preço atualizado com sucesso!", content.Message); Assert.AreEqual(0, content.Errors.Count); - Assert.AreEqual(roomId, updatedRoom.Id); - Assert.AreEqual(newRoom.Number, updatedRoom.Number); + Assert.AreEqual(room.Id, updatedRoom.Id); + Assert.AreEqual(room.Number, updatedRoom.Number); Assert.AreEqual(newPrice.Price, updatedRoom.Price); - Assert.AreEqual(newRoom.Capacity, updatedRoom.Capacity); - Assert.AreEqual(newRoom.Description, updatedRoom.Description); - Assert.AreEqual(newRoom.CategoryId, updatedRoom.CategoryId); + Assert.AreEqual(room.Capacity, updatedRoom.Capacity); + Assert.AreEqual(room.Description, updatedRoom.Description); + Assert.AreEqual(room.CategoryId, updatedRoom.CategoryId); } [TestMethod] @@ -967,10 +920,10 @@ public async Task UpdateRoomCapacity_ShouldReturn_OK() await _dbContext.Rooms.AddAsync(room); await _dbContext.SaveChangesAsync(); - var newCapacity = 5; + var newCapacity = new UpdateRoomCapacity(5); //Act - var response = await _client.PatchAsJsonAsync($"{_baseUrl}/{room.Id}/capacity/{newCapacity}", new { }); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/capacity/{room.Id}", newCapacity); //Assert response.EnsureSuccessStatusCode(); @@ -985,7 +938,7 @@ public async Task UpdateRoomCapacity_ShouldReturn_OK() Assert.AreEqual(room.Id, updatedRoom.Id); Assert.AreEqual(room.Number, updatedRoom.Number); Assert.AreEqual(room.Price, updatedRoom.Price); - Assert.AreEqual(newCapacity, updatedRoom.Capacity); + Assert.AreEqual(newCapacity.Capacity, updatedRoom.Capacity); Assert.AreEqual(room.Description, updatedRoom.Description); Assert.AreEqual(room.CategoryId, updatedRoom.CategoryId); Assert.AreEqual(room.Images.Count, updatedRoom.Images.Count); @@ -1145,10 +1098,6 @@ public async Task NonexistsReservation_ShouldReturn_NOT_FOUND(string method, str }; Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - - var content = await _testService.DeserializeResponse(response); - - } [TestMethod] @@ -1157,23 +1106,19 @@ public async Task UpdateRoom_WithNonexistsReservation_ShouldReturn_NOT_FOUND() //Arange var body = new EditorRoom("Quarto 1",1, 1, 1, "abcd", _standardCategory.Id); //Act - var response = await _client.PutAsJsonAsync($"v1/rooms/{Guid.NewGuid()}", body); + var response = await _client.PutAsJsonAsync($"{_baseUrl}/{Guid.NewGuid()}", body); //Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - - var content = await _testService.DeserializeResponse(response); - - + Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } [TestMethod] public async Task UpdatePrice_WithNonexistsReservation_ShouldReturn_NOT_FOUND() { //Arange - var body = new UpdatePriceDTO(30); + var body = new UpdateRoomPrice(30); //Act - var response = await _client.PatchAsJsonAsync($"v1/rooms/{Guid.NewGuid()}/price", body); + var response = await _client.PatchAsJsonAsync($"{_baseUrl}/price/{Guid.NewGuid()}", body); //Assert Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); diff --git a/Hotel.Tests/IntegrationTests/Utilities/TestService.cs b/Hotel.Tests/IntegrationTests/Utilities/TestService.cs index 3ca84c2..46cf261 100644 --- a/Hotel.Tests/IntegrationTests/Utilities/TestService.cs +++ b/Hotel.Tests/IntegrationTests/Utilities/TestService.cs @@ -158,6 +158,7 @@ public async Task CreateCategoryAsync(EditorCategory newCategory) _factory.Login(_client, _rootAdminToken); var response = await _client.PostAsJsonAsync("v1/categories", newCategory); + response.EnsureSuccessStatusCode(); var content = await DeserializeResponse(response); var category = await _dbContext.Categories.FirstAsync(x => x.Id == content.Data.Id);