From a06d4d94288f8debeb29ec1c4bec7c8af7c75c43 Mon Sep 17 00:00:00 2001 From: Mobin Barfi Date: Sun, 8 Sep 2024 19:10:41 +0330 Subject: [PATCH] feat: add error code to result --- src/Application/DTOs/ErrorCode.cs | 9 + src/Application/DTOs/Result.cs | 12 +- .../Services/DomainService/AccountService.cs | 18 +- .../Services/DomainService/ProfileService.cs | 20 +- .../DomainService/TransactionService.cs | 16 +- .../Services/DomainService/UserService.cs | 26 +- src/Web/Controllers/AccountsController.cs | 10 +- src/Web/Controllers/ProfileController.cs | 6 +- src/Web/Controllers/TransactionsController.cs | 10 +- src/Web/Controllers/UsersController.cs | 9 +- src/Web/Program.cs | 3 - .../Controllers/UsersControllerTests.cs | 248 ------------------ 12 files changed, 73 insertions(+), 314 deletions(-) create mode 100644 src/Application/DTOs/ErrorCode.cs delete mode 100644 test/Web.UnitTests/Controllers/UsersControllerTests.cs diff --git a/src/Application/DTOs/ErrorCode.cs b/src/Application/DTOs/ErrorCode.cs new file mode 100644 index 0000000..0bff7ee --- /dev/null +++ b/src/Application/DTOs/ErrorCode.cs @@ -0,0 +1,9 @@ +namespace Application.DTOs; + +public enum ErrorCode +{ + BadRequest = 400, + UnAuthorized = 401, + NotFound = 404, + InternalServerError = 500, +} \ No newline at end of file diff --git a/src/Application/DTOs/Result.cs b/src/Application/DTOs/Result.cs index da726f8..8132d19 100644 --- a/src/Application/DTOs/Result.cs +++ b/src/Application/DTOs/Result.cs @@ -4,7 +4,7 @@ public class Result { public string Message { get; protected set; } = string.Empty; public bool Succeed { get; protected set; } - + public ErrorCode ErrCode { get; protected set; } public static Result Ok(string message = "succeed") { return new Result @@ -14,12 +14,13 @@ public static Result Ok(string message = "succeed") }; } - public static Result Fail(string message = "failed") + public static Result Fail(ErrorCode errorCode, string message = "failed") { return new Result { Succeed = false, - Message = message + Message = message, + ErrCode = errorCode }; } } @@ -37,12 +38,13 @@ public static Result Ok(T value) }; } - public static Result Fail(string message = "failed") + public static Result Fail(ErrorCode errorCode, string message = "failed") { return new Result { Succeed = false, - Message = message + Message = message, + ErrCode = errorCode }; } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/AccountService.cs b/src/Application/Services/DomainService/AccountService.cs index fd8bbfc..58347f2 100644 --- a/src/Application/Services/DomainService/AccountService.cs +++ b/src/Application/Services/DomainService/AccountService.cs @@ -38,7 +38,7 @@ public async Task AddAccountsFromCsvAsync(string filePath, long fileId) var fileAlreadyExists = await _fileIdRepository.IdExistsAsync(fileId); if (fileAlreadyExists) { - return Result.Fail("File-Id already exists"); + return Result.Fail(ErrorCode.BadRequest, "File-Id already exists"); } await _fileIdRepository.AddAsync(new FileId { Id = fileId }); await _accountRepository.CreateBulkAsync(newAccounts); @@ -46,7 +46,7 @@ public async Task AddAccountsFromCsvAsync(string filePath, long fileId) } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -57,14 +57,14 @@ public async Task> GetAccountByIdAsync(long accountId) var account = await _accountRepository.GetByIdAsync(accountId); if (account == null) { - return Result.Fail("Account not found"); + return Result.Fail(ErrorCode.NotFound, "Account not found"); } return Result.Ok(account); } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -77,7 +77,7 @@ public async Task>> GetAllAccountsAsync() } catch (Exception ex) { - return Result>.Fail($"An unexpected error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -87,14 +87,14 @@ public async Task>> GetAccountsByFileIdAsync(long fileId) { if (!await _fileIdRepository.IdExistsAsync(fileId)) { - return Result>.Fail("File-Id not found"); + return Result>.Fail(ErrorCode.BadRequest, "File-Id not found"); } var accounts = await _accountRepository.GetByFileIdAsync(fileId); return Result>.Ok(accounts); } catch (Exception ex) { - return Result>.Fail($"An unexpected error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -104,7 +104,7 @@ public async Task DeleteAccountsByFileIdAsync(long fileId) { if (!await _fileIdRepository.IdExistsAsync(fileId)) { - return Result>.Fail("File-Id not found"); + return Result>.Fail(ErrorCode.BadRequest, "File-Id not found"); } await _accountRepository.DeleteByFileIdAsync(fileId); await _fileIdRepository.DeleteByIdAsync(fileId); @@ -112,7 +112,7 @@ public async Task DeleteAccountsByFileIdAsync(long fileId) } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/ProfileService.cs b/src/Application/Services/DomainService/ProfileService.cs index 69b6bf6..44abf07 100644 --- a/src/Application/Services/DomainService/ProfileService.cs +++ b/src/Application/Services/DomainService/ProfileService.cs @@ -24,13 +24,13 @@ public async Task> EditProfileInfo(EditProfileIn { var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId); if (user == null) - return Result.Fail("User not found!"); + return Result.Fail(ErrorCode.BadRequest, "User not found!"); if (user.UserName != infoRequest.UserName) { var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName); if (existingUser != null) - return Result.Fail("Username is already reserved by another user!"); + return Result.Fail(ErrorCode.BadRequest, "Username is already reserved by another user!"); } user.UserName = infoRequest.UserName; @@ -39,13 +39,13 @@ public async Task> EditProfileInfo(EditProfileIn var updateResult = await _userManagerRepository.UpdateAsync(user); if (!updateResult.Succeeded) - return Result.Fail(updateResult.Errors.FirstMessage()); + return Result.Fail(ErrorCode.BadRequest, updateResult.Errors.FirstMessage()); return Result.Ok(user.ToEditProfileInfoResponse()); } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -56,7 +56,7 @@ public async Task> GetProfileInfo(GetProfileInfoR var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId); if (user == null) - return Result.Fail("User not found!"); + return Result.Fail(ErrorCode.NotFound, "User not found!"); var role = await _userManagerRepository.GetRoleAsync(user); @@ -64,7 +64,7 @@ public async Task> GetProfileInfo(GetProfileInfoR } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -74,21 +74,21 @@ public async Task ChangePassword(ChangePasswordRequest request) { var user = await _userManagerRepository.FindByIdAsync(request.UserId); if (user == null) - return Result.Fail("User not found!"); + return Result.Fail(ErrorCode.BadRequest, "User not found!"); var isPasswordCorrect = await _userManagerRepository.CheckPasswordAsync(user, request.CurrentPassword); if (!isPasswordCorrect) - return Result.Fail("Incorrect current password!"); + return Result.Fail(ErrorCode.BadRequest, "Incorrect current password!"); var passwordChangeResult = await _userManagerRepository.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword); if (!passwordChangeResult.Succeeded) - return Result.Fail(passwordChangeResult.Errors.FirstMessage()); + return Result.Fail(ErrorCode.BadRequest, passwordChangeResult.Errors.FirstMessage()); return Result.Ok(); } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/TransactionService.cs b/src/Application/Services/DomainService/TransactionService.cs index 25f11db..80258f0 100644 --- a/src/Application/Services/DomainService/TransactionService.cs +++ b/src/Application/Services/DomainService/TransactionService.cs @@ -62,7 +62,7 @@ public async Task AddTransactionsFromCsvAsync(string filePath, long file var fileAlreadyExists = await _fileIdRepository.IdExistsAsync(fileId); if (!fileAlreadyExists) { - return Result.Fail("File-Id do not exist"); + return Result.Fail(ErrorCode.BadRequest, "File-Id do not exist"); } await _transactionRepository.CreateBulkAsync(newTransactions); return Result.Ok(invalidTransactionCsvModels.Count == 0 @@ -71,7 +71,7 @@ public async Task AddTransactionsFromCsvAsync(string filePath, long file } catch (Exception ex) { - return Result.Fail($"An error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}"); } } @@ -84,7 +84,7 @@ public async Task>> GetAllTransactionsAsync() } catch (Exception ex) { - return Result>.Fail($"An error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}"); } } @@ -129,7 +129,7 @@ public async Task>> GetTransacti } catch (Exception ex) { - return Result>.Fail($"An error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}"); } } @@ -139,14 +139,14 @@ public async Task>> GetTransactionsByFileIdAsync(long f { if (!await _fileIdRepository.IdExistsAsync(fileId)) { - return Result>.Fail("File-Id not found"); + return Result>.Fail(ErrorCode.BadRequest, "File-Id not found"); } var transactions = await _transactionRepository.GetByFileIdAsync(fileId); return Result>.Ok(transactions); } catch (Exception ex) { - return Result>.Fail($"An error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}"); } } @@ -156,14 +156,14 @@ public async Task DeleteTransactionsByFileIdAsync(long fileId) { if (!await _fileIdRepository.IdExistsAsync(fileId)) { - return Result.Fail("File-Id not found"); + return Result.Fail(ErrorCode.BadRequest, "File-Id not found"); } await _transactionRepository.DeleteByFileIdAsync(fileId); return Result.Ok(); } catch (Exception ex) { - return Result.Fail($"An error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/UserService.cs b/src/Application/Services/DomainService/UserService.cs index 6e0268f..df37774 100644 --- a/src/Application/Services/DomainService/UserService.cs +++ b/src/Application/Services/DomainService/UserService.cs @@ -31,7 +31,7 @@ public async Task> SignUp(CreateUserRequest createUse { if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role)) { - return Result.Fail("Role does not exist."); + return Result.Fail(ErrorCode.BadRequest, "Role does not exist."); } var appUser = createUserRequest.ToAppUser(); @@ -39,20 +39,20 @@ public async Task> SignUp(CreateUserRequest createUse var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password); if (!appUserResult.Succeeded) { - return Result.Fail(appUserResult.Errors.FirstMessage()); + return Result.Fail(ErrorCode.BadRequest, appUserResult.Errors.FirstMessage()); } var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role); if (!roleResult.Succeeded) { - return Result.Fail(roleResult.Errors.FirstMessage()); + return Result.Fail(ErrorCode.BadRequest, roleResult.Errors.FirstMessage()); } return Result.Ok(appUser.ToCreateUserResponse(createUserRequest.Role)); } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -72,14 +72,14 @@ public async Task> Login(LoginUserRequest loginUserReq } else { - return Result.Fail("You should enter email or username!"); + return Result.Fail(ErrorCode.UnAuthorized, "You should enter email or username!"); } - if (appUser is null) return Result.Fail("Invalid username/email!"); + if (appUser is null) return Result.Fail(ErrorCode.UnAuthorized, "Invalid username/email!"); var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password); - if (!succeed) return Result.Fail("Username/Email not found and/or password incorrect"); + if (!succeed) return Result.Fail(ErrorCode.UnAuthorized, "Username/Email not found and/or password incorrect"); var role = await _userManagerRepository.GetRoleAsync(appUser); var token = _tokenService.GenerateToken(appUser, role); @@ -88,7 +88,7 @@ public async Task> Login(LoginUserRequest loginUserReq } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -98,19 +98,19 @@ public async Task ChangeRole(ChangeRoleRequest request) { if (!await _roleManagerRepository.RoleExistsAsync(request.Role)) { - return Result.Fail("role does not exist"); + return Result.Fail(ErrorCode.BadRequest, "role does not exist"); } AppUser? appUser = await _userManagerRepository.FindByNameAsync(request.UserName); - if (appUser is null) return Result.Fail("Invalid username"); + if (appUser is null) return Result.Fail(ErrorCode.BadRequest, "Invalid username"); var result = await _userManagerRepository.ChangeRoleAsync(appUser, request.Role); - return result.Succeeded ? Result.Ok() : Result.Fail(result.Errors.FirstMessage()); + return result.Succeeded ? Result.Ok() : Result.Fail(ErrorCode.BadRequest, result.Errors.FirstMessage()); } catch (Exception ex) { - return Result.Fail($"An unexpected error occurred: {ex.Message}"); + return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } @@ -132,7 +132,7 @@ public async Task>> GetAllUsersAsync() } catch (Exception ex) { - return Result>.Fail($"An unexpected error occurred: {ex.Message}"); + return Result>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/src/Web/Controllers/AccountsController.cs b/src/Web/Controllers/AccountsController.cs index 87714b2..5fb58a7 100644 --- a/src/Web/Controllers/AccountsController.cs +++ b/src/Web/Controllers/AccountsController.cs @@ -41,7 +41,7 @@ public async Task UploadAccounts([FromForm] IFormFile file, [From if (!result.Succeed) { var errorResponse = Errors.New(nameof(UploadAccounts), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok("Accounts uploaded successfully!"); @@ -58,7 +58,7 @@ public async Task GetAccountById(long accountId) if (!account.Succeed) { var errorResponse = Errors.New(nameof(GetAccountById), account.Message); - return NotFound(errorResponse); + return StatusCode((int)account.ErrCode, errorResponse); } var response = account.Value!; @@ -77,7 +77,7 @@ public async Task GetAllAccounts() if (!allAccounts.Succeed) { var errorResponse = Errors.New(nameof(GetAllAccounts), allAccounts.Message); - return BadRequest(errorResponse); + return StatusCode((int)allAccounts.ErrCode, errorResponse); } var response = allAccounts.Value!; @@ -95,7 +95,7 @@ public async Task GetAccountsByFileId(long fileId) if (!accounts.Succeed) { var errorResponse = Errors.New(nameof(GetAccountsByFileId), accounts.Message); - return BadRequest(errorResponse); + return StatusCode((int)accounts.ErrCode, errorResponse); } var response = accounts.Value!; @@ -113,7 +113,7 @@ public async Task DeleteAccountsByFileId(long fileId) if (!result.Succeed) { var errorResponse = Errors.New(nameof(DeleteAccountsByFileId), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok("Accounts deleted successfully!"); diff --git a/src/Web/Controllers/ProfileController.cs b/src/Web/Controllers/ProfileController.cs index cd6d470..d18fd7b 100644 --- a/src/Web/Controllers/ProfileController.cs +++ b/src/Web/Controllers/ProfileController.cs @@ -36,7 +36,7 @@ public async Task EditProfileInfo([FromBody] EditProfileInfoDto e if (!result.Succeed) { var errorResponse = Errors.New(nameof(EditProfileInfo), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok("Profile info updated successfully!"); @@ -57,7 +57,7 @@ public async Task GetProfileInfo() if (!result.Succeed) { var errorResponse = Errors.New(nameof(GetProfileInfo), result.Message); - return NotFound(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } var user = result.Value!; @@ -80,7 +80,7 @@ public async Task ChangePassword([FromBody] ChangePasswordDto cha if (!result.Succeed) { var errorResponse = Errors.New(nameof(ChangePassword), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok("Password changed successfully!"); diff --git a/src/Web/Controllers/TransactionsController.cs b/src/Web/Controllers/TransactionsController.cs index be6a44c..e6a5483 100644 --- a/src/Web/Controllers/TransactionsController.cs +++ b/src/Web/Controllers/TransactionsController.cs @@ -43,7 +43,7 @@ public async Task UploadTransactions([FromForm] IFormFile file, [ if (!result.Succeed) { var errorResponse = Errors.New(nameof(UploadTransactions), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok(result.Message); @@ -62,7 +62,7 @@ public async Task GetAllTransactions() if (!allTransactions.Succeed) { var errorResponse = Errors.New(nameof(GetAllTransactions), allTransactions.Message); - return BadRequest(errorResponse); + return StatusCode((int)allTransactions.ErrCode, errorResponse); } var response = allTransactions.Value!; @@ -82,7 +82,7 @@ public async Task GetTransactionsByAccountId(long accountId) if (!transactions.Succeed) { var errorResponse = Errors.New(nameof(GetAllTransactions), transactions.Message); - return BadRequest(errorResponse); + return StatusCode((int)transactions.ErrCode, errorResponse); } var response = transactions.Value!; @@ -103,7 +103,7 @@ public async Task GetTransactionsByFileId(long fileId) if (!transactions.Succeed) { var errorResponse = Errors.New(nameof(GetAllTransactions), transactions.Message); - return BadRequest(errorResponse); + return StatusCode((int)transactions.ErrCode, errorResponse); } var response = transactions.Value!.ToGotAllTransactionsDto(); @@ -124,7 +124,7 @@ public async Task DeleteTransactionsByFileId(long fileId) if (!result.Succeed) { var errorResponse = Errors.New(nameof(DeleteTransactionsByFileId), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok(result.Message); diff --git a/src/Web/Controllers/UsersController.cs b/src/Web/Controllers/UsersController.cs index 51f4921..1ef6d41 100644 --- a/src/Web/Controllers/UsersController.cs +++ b/src/Web/Controllers/UsersController.cs @@ -35,8 +35,7 @@ public async Task Signup([FromBody] SignupDto signupDto) if (!result.Succeed) { var errorResponse = Errors.New(nameof(Signup), result.Message); - return BadRequest(errorResponse); - // return StatusCode(500, Errors.New("Server Error", $"An unexpected error occurred: {ex.Message}")); + return StatusCode((int)result.ErrCode, errorResponse); } var response = result.Value!; @@ -54,7 +53,7 @@ public async Task Login([FromBody] LoginDto loginDto) if (!result.Succeed) { var errorResponse = Errors.New(nameof(Login), result.Message); - return Unauthorized(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } var response = result.Value!; @@ -76,7 +75,7 @@ public async Task ChangeRole([FromBody] ChangeRoleDto changeRoleD if (!result.Succeed) { var errorResponse = Errors.New(nameof(ChangeRole), result.Message); - return BadRequest(errorResponse); + return StatusCode((int)result.ErrCode, errorResponse); } return Ok("Role changed successfully!"); @@ -95,7 +94,7 @@ public async Task GetAllUsers() if (!usersWithRolesResult.Succeed) { var errorResponse = Errors.New(nameof(ChangeRole), usersWithRolesResult.Message); - return BadRequest(errorResponse); + return StatusCode((int)usersWithRolesResult.ErrCode, errorResponse); } var response = usersWithRolesResult.Value!; diff --git a/src/Web/Program.cs b/src/Web/Program.cs index 4ef7ddb..bec8ded 100644 --- a/src/Web/Program.cs +++ b/src/Web/Program.cs @@ -5,7 +5,6 @@ Env.Load(); var config = builder.Configuration; - builder.Services.AddSwaggerGen(); builder.Services.AddControllers().AddNewtonsoftJson(options => { @@ -17,11 +16,9 @@ builder.Services.AddSwaggerDocumentation(); builder.Services.AddCorsPolicy(config); - var app = builder.Build(); app.UseMiddlewareServices(); - using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; diff --git a/test/Web.UnitTests/Controllers/UsersControllerTests.cs b/test/Web.UnitTests/Controllers/UsersControllerTests.cs deleted file mode 100644 index e7b6aec..0000000 --- a/test/Web.UnitTests/Controllers/UsersControllerTests.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System.Security.Claims; -using Application.DTOs; -using Application.DTOs.Identity; -using Application.DTOs.Identity.CreateUser; -using Application.DTOs.Identity.LoginUser; -using Application.DTOs.User; -using Application.Interfaces.Services; -using Domain.Constants; -using Domain.Entities; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using NSubstitute; -using Web.Controllers; -using Web.DTOs.User; -using Web.DTOs.User.Login; -using Web.DTOs.User.Signup; -using Web.Mappers; -using Web.Models; -using Xunit.Abstractions; - -namespace test.Web.UnitTests.Controllers; - -public class UsersControllerTests -{ - private readonly IUserService _userServiceMock; - private readonly UsersController _controller; - - public UsersControllerTests() - { - _userServiceMock = Substitute.For(); - _controller = new UsersController(_userServiceMock); - } - - // Signup Tests - - // [Fact] - public async Task Signup_WhenUserIsNotAdmin_ReturnsForbidden() - { - // Arrange - var signupDto = new SignupDto - { - FirstName = "Mobin", - LastName = "Barfi", - Email = "mobinbr99@gmail.com", - UserName = "MobinBarfi", - Password = "Abc@1234", - Role = "DataAnalyst" - }; - - _userServiceMock.SignUp(Arg.Any()).Returns(Result.Ok(new CreateUserResponse())); - - _controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] - { - new(ClaimTypes.Role, "DataAnalyst") - })) - } - }; - - // Act - var result = await _controller.Signup(signupDto); - - // Assert - Assert.IsType(result); - } - - [Fact] - public async Task Signup_WhenRoleDoesNotExist_ReturnsBadRequest() - { - // Arrange - var signupDto = new SignupDto - { - FirstName = "Mobin", - LastName = "Barfi", - Email = "mobinbr99@gmail.com", - UserName = "MobinBarfi", - Password = "Abc@1234", - Role = "NonExistentRole" - }; - - _userServiceMock - .SignUp(Arg.Any()) - .Returns(Result.Fail("role does not exist")); - - _controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] - { - new(ClaimTypes.Role, "NonExistentRole") - })) - } - }; - - // Act - var result = await _controller.Signup(signupDto); - - // Assert - var badRequestResult = Assert.IsType(result); - Assert.Equal(400, badRequestResult.StatusCode); - - var errorResponse = Assert.IsType(badRequestResult.Value); - - Assert.Equal("Signup", errorResponse.Title); - Assert.NotNull(errorResponse.Message); - Assert.Contains("role does not exist", errorResponse.Message); - } - - [Fact] - public async Task Signup_WhenSignUpSucceeds_ReturnsOkResult() - { - // Arrange - var signupDto = new SignupDto - { - FirstName = "Mobin", - LastName = "Barfi", - Email = "mobinbr99@gmail.com", - UserName = "MobinBarfi", - Password = "Abc@1234", - Role = "Admin" - }; - - var createUserResponse = new CreateUserResponse - { - FirstName = "Mobin", - LastName = "Barfi", - Email = "mobinbr99@gmail.com", - UserName = "MobinBarfi", - Role = "Admin" - }; - - _userServiceMock - .SignUp(Arg.Any()) - .Returns(Result.Ok(createUserResponse)); - - _controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] - { - new(ClaimTypes.Role, AppRoles.Admin) - })) - } - }; - - // Act - var result = await _controller.Signup(signupDto); - - // Assert - var okResult = Assert.IsType(result); - Assert.Equal(200, okResult.StatusCode); - - var responseValue = Assert.IsType(okResult.Value); - Assert.Equal("Mobin", responseValue.FirstName); - Assert.Equal("Barfi", responseValue.LastName); - Assert.Equal("mobinbr99@gmail.com", responseValue.Email); - Assert.Equal("MobinBarfi", responseValue.UserName); - Assert.Equal("Admin", responseValue.Role); - } - - // Login Tests - [Fact] - public async Task Login_WhenLoginSucceeds_ReturnsOkResult() - { - // Arrange - var loginDto = new LoginDto - { - UserName = "MobinBarfi", - Password = "Abc@1234" - }; - - var mockResponse = new LoginUserResponse - { - UserName = "MobinBarfi", - Token = "FakeToken" - }; - - _userServiceMock - .Login(Arg.Any()) - .Returns(Result.Ok(mockResponse)); - - // Act - var result = await _controller.Login(loginDto); - - // Assert - var okResult = Assert.IsType(result); - var response = Assert.IsType(okResult.Value); - Assert.Equal("MobinBarfi", response.UserName); - Assert.Equal("FakeToken", response.Token); - } - - // ChangeRole Tests - [Fact] - public async Task ChangeRole_WhenRoleDoesNotExist_ReturnsBadRequest() - { - // Arrange - var changeRoleDto = new ChangeRoleDto - { - UserName = "MobinBarfi", - Role = "NonExistentRole" - }; - - _userServiceMock - .ChangeRole(Arg.Any()) - .Returns(Result.Fail("role does not exist")); - - // Act - var result = await _controller.ChangeRole(changeRoleDto); - - // Assert - var badRequestResult = Assert.IsType(result); - var errorResponse = Assert.IsType(badRequestResult.Value); - - Assert.Equal(400, badRequestResult.StatusCode); - Assert.Equal("ChangeRole", errorResponse.Title); - Assert.NotNull(errorResponse.Message); - Assert.Contains("role does not exist", errorResponse.Message); - } - - [Fact] - public async Task ChangeRole_WhenOperationSucceeds_ReturnsOk() - { - // Arrange - var changeRoleDto = new ChangeRoleDto - { - UserName = "MobinBarfi", - Role = "Admin" - }; - - _userServiceMock - .ChangeRole(Arg.Any()) - .Returns(Result.Ok()); - - // Act - var result = await _controller.ChangeRole(changeRoleDto); - - // Assert - var okResult = Assert.IsType(result); - - Assert.Equal(200, okResult.StatusCode); - Assert.Equal("Role changed successfully!", okResult.Value); - } -} \ No newline at end of file