Centralizes and standardizes test fixtures.

This commit is contained in:
BinaryAlley committed 2026-08-15 02:58:17 -07:00
1 parent dfc513da4f
commit b648e2f054
294 files changed
+3807 -4437

No files matched your search

@@ -6,7 +6,7 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -28,6 +28,7 @@ public class ChangePasswordCommandHandlerTests
private readonly IPasswordHashService _mockHashService;
private readonly IUserRepository _mockUserRepository;
private readonly ChangePasswordCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandlerTests"/> class.
@@ -58,7 +59,7 @@ public class ChangePasswordCommandHandlerTests
string hashedNewPassword = "hashedNewPassword";
string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword");
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = escapedHashedCurrentPassword;
ChangePasswordCommand command = new(
@@ -115,7 +116,7 @@ public class ChangePasswordCommandHandlerTests
public async Task HandleAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnError()
{
// Arrange
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
string incorrectPassword = "wrongPassword";
ChangePasswordCommand command = new(
@@ -151,7 +152,7 @@ public class ChangePasswordCommandHandlerTests
string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword");
Error error = Error.Failure("Database.Error", "Failed to update user");
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = escapedHashedCurrentPassword;
ChangePasswordCommand command = new(
@@ -186,7 +187,7 @@ public class ChangePasswordCommandHandlerTests
// Arrange
string currentPassword = "currentPassword";
string newPassword = "newPassword";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
ChangePasswordCommand command = new(
user.Username,
currentPassword,
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
public class ChangePasswordCommandValidatorTests
{
private readonly ChangePasswordCommandValidator _validator;
private readonly ChangePasswordCommandFixture _changePasswordCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class ChangePasswordCommandValidatorTests
public ChangePasswordCommandValidatorTests()
{
_validator = new ChangePasswordCommandValidator();
_changePasswordCommandFixture = new ChangePasswordCommandFixture();
}
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = null! };
// Act
@@ -44,7 +46,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { Username = " " };
// Act
@@ -72,7 +74,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = null! };
// Act
@@ -86,7 +88,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = string.Empty };
// Act
@@ -100,7 +102,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = " " };
// Act
@@ -114,7 +116,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = null! };
// Act
@@ -128,7 +130,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = string.Empty };
// Act
@@ -142,7 +144,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = " " };
// Act
@@ -156,7 +158,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = null! };
// Act
@@ -170,7 +172,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = string.Empty };
// Act
@@ -184,7 +186,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = " " };
// Act
@@ -198,7 +200,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPasswordConfirm = "$321Bcda" };
// Act
@@ -218,7 +220,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenCurrentPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { CurrentPassword = password };
// Act
@@ -238,7 +240,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenNewPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with { NewPassword = password, NewPasswordConfirm = password };
// Act
@@ -256,7 +258,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenPasswordsMatchPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
command = command with
{
CurrentPassword = password,
@@ -276,7 +278,7 @@ public class ChangePasswordCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ChangePasswordCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordCommandFixture
{
/// <summary>
/// Creates a random valid command for changing a password.
/// </summary>
/// <returns>The created command.</returns>
public static ChangePasswordCommand CreateChangePasswordCommand()
{
string currentPassword = "Abcd123$";
string newPassword = "Wxyz789#";
return new Faker<ChangePasswordCommand>()
.CustomInstantiator(f => new ChangePasswordCommand(
default!,
default!,
default!,
default!
))
.RuleFor(x => x.Username, f => f.Person.UserName)
.RuleFor(x => x.CurrentPassword, currentPassword)
.RuleFor(x => x.NewPassword, newPassword)
.RuleFor(x => x.NewPasswordConfirm, newPassword);
}
}
@@ -1,56 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Authentication;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ChangePasswordRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordRequestFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordRequestFixture"/> class.
/// </summary>
public ChangePasswordRequestFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="ChangePasswordRequest"/>.
/// </summary>
/// <returns>The created <see cref="ChangePasswordRequest"/>.</returns>
public ChangePasswordRequest CreateChangePasswordRequest(
string? username = null,
string? currentPassword = null,
string? newPassword = null,
string? newPasswordConfirm = null)
{
return new ChangePasswordRequest(
username ?? _faker.Internet.UserName(),
currentPassword ?? _faker.Internet.Password(),
newPassword ?? _faker.Internet.Password(),
newPasswordConfirm ?? _faker.Internet.Password()
);
}
/// <summary>
/// Creates a list of <see cref="ChangePasswordRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ChangePasswordRequest> CreateMany(int count = 3)
{
return Enumerable.Range(0, count)
.Select(_ => CreateChangePasswordRequest())
.ToList();
}
}
@@ -1,29 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
/// <summary>
/// Fixture class for the <see cref="RecoverPasswordCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordCommandFixture
{
/// <summary>
/// Creates a random valid command for password recovery.
/// </summary>
/// <returns>The created command.</returns>
public static RecoverPasswordCommand CreateRecoverPasswordCommand()
{
return new Faker<RecoverPasswordCommand>()
.CustomInstantiator(f => new RecoverPasswordCommand(
default!,
default!
))
.RuleFor(x => x.Username, f => f.Person.UserName)
.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
}
}
@@ -1,52 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Authentication;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
/// <summary>
/// Fixture class for the <see cref="RecoverPasswordRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordRequestFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordRequestFixture"/> class.
/// </summary>
public RecoverPasswordRequestFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="RecoverPasswordRequest"/>.
/// </summary>
/// <returns>The created <see cref="RecoverPasswordRequest"/>.</returns>
public RecoverPasswordRequest CreateRecoverPasswordRequest(
string? username = null,
string? totpCode = null)
{
return new RecoverPasswordRequest(
username ?? _faker.Internet.UserName(),
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
);
}
/// <summary>
/// Creates a list of <see cref="RecoverPasswordRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<RecoverPasswordRequest> CreateMany(int count = 3)
{
return Enumerable.Range(0, count)
.Select(_ => CreateRecoverPasswordRequest())
.ToList();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -31,6 +31,7 @@ public class RecoverPasswordCommandHandlerTests
private readonly ICryptographyService _mockCryptographyService;
private readonly IUserRepository _mockUserRepository;
private readonly RecoverPasswordCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
@@ -65,7 +66,7 @@ public class RecoverPasswordCommandHandlerTests
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
string hashedTempPassword = "hashedTempPassword";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
user.TempPassword = null;
@@ -121,7 +122,7 @@ public class RecoverPasswordCommandHandlerTests
public async Task HandleAsync_WhenTempPasswordExists_ShouldReturnError()
{
// Arrange
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TempPassword = "existingTempPassword";
user.TempPasswordCreated = DateTime.UtcNow;
@@ -146,7 +147,7 @@ public class RecoverPasswordCommandHandlerTests
public async Task HandleAsync_WhenUserDoesNotUseTOTP_ShouldReturnError()
{
// Arrange
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = null;
RecoverPasswordCommand command = new(user.Username, "123456");
@@ -174,7 +175,7 @@ public class RecoverPasswordCommandHandlerTests
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = new(user.Username, totpCode);
@@ -208,7 +209,7 @@ public class RecoverPasswordCommandHandlerTests
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
Error error = Error.Failure("Database.Error", "Failed to update user");
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = new(user.Username, totpCode);
@@ -242,7 +243,7 @@ public class RecoverPasswordCommandHandlerTests
string totpCode = "123456";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = new(user.Username, totpCode);
@@ -269,7 +270,7 @@ public class RecoverPasswordCommandHandlerTests
// Arrange
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.TotpSecret = encryptedTotpSecret;
RecoverPasswordCommand command = new(user.Username, null);
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
public class RecoverPasswordCommandValidatorTests
{
private readonly RecoverPasswordCommandValidator _validator;
private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class RecoverPasswordCommandValidatorTests
public RecoverPasswordCommandValidatorTests()
{
_validator = new RecoverPasswordCommandValidator();
_recoverPasswordCommandFixture = new RecoverPasswordCommandFixture();
}
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = null! };
// Act
@@ -44,7 +46,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { Username = " " };
// Act
@@ -72,7 +74,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = null! };
// Act
@@ -86,7 +88,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = string.Empty };
// Act
@@ -100,7 +102,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = " " };
// Act
@@ -120,7 +122,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode)
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = totpCode };
// Act
@@ -137,7 +139,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
command = command with { TotpCode = totpCode };
// Act
@@ -151,7 +153,7 @@ public class RecoverPasswordCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
/// <summary>
/// Fixture class for the <see cref="RegisterUserCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterUserCommandFixture
{
/// <summary>
/// Creates a random valid command for a new account registration.
/// </summary>
/// <returns>The created command.</returns>
public static RegisterUserCommand CreateRegisterCommand()
{
string password = "Abcd123$";
return new Faker<RegisterUserCommand>()
.CustomInstantiator(f => new RegisterUserCommand(
default!,
default!,
default!,
true
))
.RuleFor(x => x.Username, f => f.Person.UserName)
.RuleFor(x => x.Password, password)
.RuleFor(x => x.PasswordConfirm, password);
}
}
@@ -1,58 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Authentication;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
/// <summary>
/// Fixture class for the <see cref="RegistrationRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegistrationRequestFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="RegistrationRequestFixture"/> class.
/// </summary>
public RegistrationRequestFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="RegistrationRequest"/>.
/// </summary>
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
public RegistrationRequest CreateRegistrationRequest(
string? username = null,
string? password = null,
string? passwordConfirm = null,
bool? use2fa = null)
{
password ??= _faker.Internet.Password();
return new RegistrationRequest(
username ?? _faker.Internet.UserName(),
password,
passwordConfirm ?? password,
use2fa ?? _faker.Random.Bool()
);
}
/// <summary>
/// Creates a list of <see cref="RegistrationRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<RegistrationRequest> CreateMany(int count = 3)
{
return Enumerable.Range(0, count)
.Select(_ => CreateRegistrationRequest())
.ToList();
}
}
@@ -8,8 +8,8 @@ using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -35,6 +35,8 @@ public class RegisterUserCommandHandlerTests
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly RegisterUserCommandHandler _sut;
private readonly RegisterUserCommandFixture _registerUserCommandFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandHandlerTests"/> class.
@@ -69,7 +71,7 @@ public class RegisterUserCommandHandlerTests
public async Task HandleAsync_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
byte[] totpSecret = [1, 2, 3];
string qrCodeUri = "data:image/png;base64,test";
string encryptedSecret = "encryptedSecret";
@@ -109,7 +111,7 @@ public class RegisterUserCommandHandlerTests
public async Task HandleAsync_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false };
RegisterUserCommand command = _registerUserCommandFixture.Create() with { Use2fa = false };
string hashedPassword = "hashedPassword";
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
@@ -140,8 +142,8 @@ public class RegisterUserCommandHandlerTests
public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
UserEntity existingUser = UserEntityFixture.CreateUserEntity();
RegisterUserCommand command = _registerUserCommandFixture.Create();
UserEntity existingUser = _userEntityFixture.Create();
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(existingUser));
@@ -162,7 +164,7 @@ public class RegisterUserCommandHandlerTests
public async Task HandleAsync_WhenInsertFails_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to insert user");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
@@ -186,7 +188,7 @@ public class RegisterUserCommandHandlerTests
public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to check username");
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
public class RegisterUserCommandValidatorTests
{
private readonly RegisterUserCommandValidator _validator;
private readonly RegisterUserCommandFixture _registerUserCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class RegisterUserCommandValidatorTests
public RegisterUserCommandValidatorTests()
{
_validator = new RegisterUserCommandValidator();
_registerUserCommandFixture = new RegisterUserCommandFixture();
}
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = null! };
// Act
@@ -44,7 +46,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = " " };
// Act
@@ -72,7 +74,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = null! };
// Act
@@ -86,7 +88,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = string.Empty };
// Act
@@ -100,7 +102,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = " " };
// Act
@@ -114,7 +116,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = null! };
// Act
@@ -128,7 +130,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = string.Empty };
// Act
@@ -142,7 +144,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = " " };
// Act
@@ -156,7 +158,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { PasswordConfirm = "$321Bcda" };
// Act
@@ -176,7 +178,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
@@ -194,7 +196,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
@@ -208,7 +210,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with
{
Username = "valid.user123",
@@ -232,7 +234,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenUsernameHasInvalidLength_ShouldHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
@@ -256,7 +258,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenUsernameHasInvalidFormat_ShouldHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
@@ -277,7 +279,7 @@ public class RegisterUserCommandValidatorTests
public void Validate_WhenUsernameHasValidFormat_ShouldNotHaveValidationError(string username)
{
// Arrange
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
RegisterUserCommand command = _registerUserCommandFixture.Create();
command = command with { Username = username };
// Act
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetUsersQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUsersQueryFixture
{
/// <summary>
/// Creates a random valid query to get users.
/// </summary>
/// <returns>The created query.</returns>
public GetUsersQuery CreateQuery()
{
return new GetUsersQuery();
}
}
@@ -6,8 +6,8 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.GetUsers;
using Lumina.Contracts.Responses.UsersManagement.Users;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -32,6 +32,7 @@ public class GetUsersQueryHandlerTests
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserRepository _mockUserRepository;
private readonly GetUsersQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly GetUsersQueryFixture _getUsersQueryFixture;
private readonly Guid _userId;
@@ -60,7 +61,7 @@ public class GetUsersQueryHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.CreateQuery();
GetUsersQuery query = _getUsersQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -77,7 +78,7 @@ public class GetUsersQueryHandlerTests
public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.CreateQuery();
GetUsersQuery query = _getUsersQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get users");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -97,8 +98,8 @@ public class GetUsersQueryHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnUsers()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.CreateQuery();
IEnumerable<UserEntity> users = UserEntityFixture.CreateMany(2);
GetUsersQuery query = _getUsersQueryFixture.Create();
IEnumerable<UserEntity> users = _userEntityFixture.CreateMany(2);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -1,54 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Authentication;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
/// <summary>
/// Fixture class for the <see cref="LoginRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginRequestFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="LoginRequestFixture"/> class.
/// </summary>
public LoginRequestFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="LoginRequest"/>.
/// </summary>
/// <returns>The created <see cref="LoginRequest"/>.</returns>
public LoginRequest CreateLoginRequest(
string? username = null,
string? password = null,
string? totpCode = null)
{
return new LoginRequest(
username ?? _faker.Internet.UserName(),
password ?? _faker.Internet.Password(),
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
);
}
/// <summary>
/// Creates a list of <see cref="LoginRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LoginRequest> CreateMany(int count = 3)
{
return Enumerable.Range(0, count)
.Select(_ => CreateLoginRequest())
.ToList();
}
}
@@ -1,36 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
/// <summary>
/// Fixture class for the <see cref="LoginUserQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginUserQueryFixture
{
/// <summary>
/// Creates a random valid query for user login.
/// </summary>
/// <param name="includeTotpCode">Whether to include a TOTP code in the query.</param>
/// <returns>The created query.</returns>
public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false)
{
string password = "Abcd123$";
Faker<LoginUserQuery> faker = new Faker<LoginUserQuery>()
.CustomInstantiator(f => new LoginUserQuery(
default!,
default!,
default
))
.RuleFor(x => x.Username, f => f.Person.UserName)
.RuleFor(x => x.Password, password);
if (includeTotpCode)
faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
return faker;
}
}
@@ -8,7 +8,7 @@ using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -34,6 +34,7 @@ public class LoginUserQueryHandlerTests
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly LoginUserQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandlerTests"/> class.
@@ -72,7 +73,7 @@ public class LoginUserQueryHandlerTests
string hashedPassword = "hashedPassword";
string jwtToken = "jwtToken";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = null;
@@ -107,7 +108,7 @@ public class LoginUserQueryHandlerTests
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
@@ -159,7 +160,7 @@ public class LoginUserQueryHandlerTests
string password = "wrongPassword";
string hashedPassword = "hashedPassword";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = null;
@@ -186,7 +187,7 @@ public class LoginUserQueryHandlerTests
string hashedPassword = "hashedPassword";
string hashedTempPassword = "hashedTempPassword";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old)
@@ -222,7 +223,7 @@ public class LoginUserQueryHandlerTests
string hashedTempPassword = "hashedTempPassword";
string jwtToken = "jwtToken";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
// Set temp password created time to 10 minutes ago (still valid)
@@ -259,7 +260,7 @@ public class LoginUserQueryHandlerTests
string hashedPassword = "hashedPassword";
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
@@ -288,7 +289,7 @@ public class LoginUserQueryHandlerTests
string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 });
string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 });
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TotpSecret = encryptedTotpSecret;
@@ -337,7 +338,7 @@ public class LoginUserQueryHandlerTests
string hashedPassword = "hashedPassword";
string hashedTempPassword = "hashedTempPassword";
UserEntity user = UserEntityFixture.CreateUserEntity();
UserEntity user = _userEntityFixture.Create();
user.Password = Uri.EscapeDataString(hashedPassword);
user.TempPassword = Uri.EscapeDataString(hashedTempPassword);
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queri
public class LoginUserQueryValidatorTests
{
private readonly LoginUserQueryValidator _validator;
private readonly LoginUserQueryFixture _loginUserQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class LoginUserQueryValidatorTests
public LoginUserQueryValidatorTests()
{
_validator = new LoginUserQueryValidator();
_loginUserQueryFixture = new LoginUserQueryFixture();
}
[Fact]
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = null! };
// Act
@@ -44,7 +46,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Username = " " };
// Act
@@ -72,7 +74,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = null! };
// Act
@@ -86,7 +88,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = string.Empty };
// Act
@@ -100,7 +102,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = " " };
// Act
@@ -120,7 +122,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = password };
// Act
@@ -138,7 +140,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { Password = password };
// Act
@@ -158,7 +160,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode)
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = totpCode };
// Act
@@ -175,7 +177,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode)
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = totpCode };
// Act
@@ -189,7 +191,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
LoginUserQuery query = _loginUserQueryFixture.Create();
query = query with { TotpCode = null };
// Act
@@ -203,7 +205,7 @@ public class LoginUserQueryValidatorTests
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true);
LoginUserQuery query = _loginUserQueryFixture.Create(includeTotpCode: true);
// Act
List<Error> result = _validator.TestValidate(query);
@@ -1,36 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UpdateUserRoleAndPermissionsCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserRoleAndPermissionsCommandFixture
{
/// <summary>
/// Creates a random valid command to update user role and permissions.
/// </summary>
/// <param name="roleId">Optional role ID to assign. If null, no role will be assigned.</param>
/// <param name="permissionCount">The number of permissions to generate.</param>
/// <returns>The created command.</returns>
public UpdateUserRoleAndPermissionsCommand CreateCommand(Guid? roleId = null, int permissionCount = 3)
{
return new Faker<UpdateUserRoleAndPermissionsCommand>()
.CustomInstantiator(f => new UpdateUserRoleAndPermissionsCommand(
Guid.NewGuid(),
roleId,
default!))
.RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount)
.Select(_ => Guid.NewGuid())
.ToList())
.Generate();
}
}
@@ -8,8 +8,8 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -39,6 +39,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
private readonly IRoleRepository _mockRoleRepository;
private readonly IPermissionRepository _mockPermissionRepository;
private readonly UpdateUserRoleAndPermissionsCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture;
private readonly Guid _userId;
@@ -75,7 +76,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand();
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -92,7 +93,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand();
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUserRepository.GetByIdAsync(command.UserId, Arg.Any<CancellationToken>())
@@ -110,8 +111,8 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UserEntity user = UserEntityFixture.CreateUserEntity();
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = _userEntityFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -132,7 +133,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenRemovingLastAdmin_ShouldReturnCannotRemoveLastAdminError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
RoleEntity adminRole = new() { RoleName = "Admin" };
Guid userId = Guid.NewGuid();
@@ -178,8 +179,8 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UserEntity user = UserEntityFixture.CreateUserEntity();
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = _userEntityFixture.Create();
RoleEntity role = new() { RoleName = "TestRole" };
IEnumerable<PermissionEntity> permissions = command.Permissions.Select(p =>
new PermissionEntity { Id = p, PermissionName = AuthorizationPermission.CanViewUsers });
@@ -209,7 +210,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = new()
{
Id = command.UserId,
@@ -261,7 +262,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenGetAllUsersFails_ShouldReturnError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = new()
{
Id = command.UserId,
@@ -302,7 +303,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
public async Task HandleAsync_WhenGetPermissionsFails_ShouldReturnError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid());
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = new()
{
Id = command.UserId,
@@ -1,54 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetAuthorizationQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationQueryFixture
{
/// <summary>
/// Creates a random valid query to get authorization details.
/// </summary>
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
/// <returns>The created query.</returns>
public static GetAuthorizationQuery CreateGetAuthorizationQuery(Guid? userId = null)
{
return new Faker<GetAuthorizationQuery>()
.CustomInstantiator(f => new GetAuthorizationQuery(
userId ?? f.Random.Guid()
))
.Generate();
}
/// <summary>
/// Creates a random valid authorization entity.
/// </summary>
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
/// <param name="isAdmin">Whether the user should have admin role.</param>
/// <returns>The created entity.</returns>
public static UserAuthorizationEntity CreateUserAuthorizationEntity(Guid? userId = null, bool isAdmin = false)
{
string role = isAdmin ? "Admin" : string.Empty;
return new UserAuthorizationEntity
{
UserId = userId ?? Guid.NewGuid(),
Role = role,
Permissions = new HashSet<AuthorizationPermission>
{
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanRegisterUsers
}
};
}
}
@@ -5,7 +5,8 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -26,6 +27,8 @@ public class GetAuthorizationQueryHandlerTests
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly GetAuthorizationQueryHandler _sut;
private readonly GetAuthorizationQueryFixture _getAuthorizationQueryFixture;
private readonly UserAuthorizationEntityFixture _userAuthorizationEntityFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandlerTests"/> class.
@@ -34,6 +37,8 @@ public class GetAuthorizationQueryHandlerTests
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_getAuthorizationQueryFixture = new GetAuthorizationQueryFixture();
_userAuthorizationEntityFixture = new UserAuthorizationEntityFixture();
IValidator<GetAuthorizationQuery> mockValidator = Substitute.For<IValidator<GetAuthorizationQuery>>();
mockValidator.Validate(Arg.Any<GetAuthorizationQuery>())
.Returns([]);
@@ -45,8 +50,8 @@ public class GetAuthorizationQueryHandlerTests
{
// Arrange
Guid userId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(userId);
UserAuthorizationEntity authEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(userId);
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(userId);
UserAuthorizationEntity authEntity = _userAuthorizationEntityFixture.Create(userId);
_mockCurrentUserService.UserId.Returns(userId);
_mockAuthorizationService.GetUserAuthorizationAsync(userId, Arg.Any<CancellationToken>())
@@ -68,9 +73,9 @@ public class GetAuthorizationQueryHandlerTests
// Arrange
Guid adminUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true);
UserAuthorizationEntity targetAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(targetUserId);
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId);
UserAuthorizationEntity adminAuthEntity = _userAuthorizationEntityFixture.Create(adminUserId, true);
UserAuthorizationEntity targetAuthEntity = _userAuthorizationEntityFixture.Create(targetUserId);
_mockCurrentUserService.UserId.Returns(adminUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any<CancellationToken>())
@@ -94,8 +99,8 @@ public class GetAuthorizationQueryHandlerTests
// Arrange
Guid currentUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity currentUserAuth = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(currentUserId, false);
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId);
UserAuthorizationEntity currentUserAuth = _userAuthorizationEntityFixture.Create(currentUserId, false);
_mockCurrentUserService.UserId.Returns(currentUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(currentUserId, Arg.Any<CancellationToken>())
@@ -115,7 +120,7 @@ public class GetAuthorizationQueryHandlerTests
// Arrange
Guid currentUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId);
Error error = Error.Failure("Database.Error", "Failed to get user authorization");
_mockCurrentUserService.UserId.Returns(currentUserId);
@@ -136,8 +141,8 @@ public class GetAuthorizationQueryHandlerTests
// Arrange
Guid adminUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true);
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId);
UserAuthorizationEntity adminAuthEntity = _userAuthorizationEntityFixture.Create(adminUserId, true);
Error error = Error.Failure("Database.Error", "Failed to get target user authorization");
_mockCurrentUserService.UserId.Returns(adminUserId);
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
@@ -18,6 +18,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie
public class GetAuthorizationQueryValidatorTests
{
private readonly GetAuthorizationQueryValidator _validator;
private readonly GetAuthorizationQueryFixture _getAuthorizationQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryValidatorTests"/> class.
@@ -25,13 +26,14 @@ public class GetAuthorizationQueryValidatorTests
public GetAuthorizationQueryValidatorTests()
{
_validator = new GetAuthorizationQueryValidator();
_getAuthorizationQueryFixture = new GetAuthorizationQueryFixture();
}
[Fact]
public void Validate_WhenUserIdIsNull_ShouldHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
query = query with { UserId = null };
// Act
@@ -45,7 +47,7 @@ public class GetAuthorizationQueryValidatorTests
public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
query = query with { UserId = Guid.Empty };
// Act
@@ -59,7 +61,7 @@ public class GetAuthorizationQueryValidatorTests
public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetUserPermissionsQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserPermissionsQueryFixture
{
/// <summary>
/// Creates a random valid query to get user permissions.
/// </summary>
/// <returns>The created query.</returns>
public GetUserPermissionsQuery CreateQuery()
{
return new Faker<GetUserPermissionsQuery>()
.CustomInstantiator(f => new GetUserPermissionsQuery(
Guid.NewGuid()))
.Generate();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures;
using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -65,7 +65,7 @@ public class GetUserPermissionsQueryHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery();
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -82,7 +82,7 @@ public class GetUserPermissionsQueryHandlerTests
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
{
// Arrange
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery();
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get user");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -102,7 +102,7 @@ public class GetUserPermissionsQueryHandlerTests
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError()
{
// Arrange
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery();
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -121,7 +121,7 @@ public class GetUserPermissionsQueryHandlerTests
public async Task HandleAsync_WhenUserHasPermissions_ShouldReturnPermissions()
{
// Arrange
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery();
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create();
UserEntity user = new()
{
Id = query.UserId!.Value,
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetUserRoleQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserRoleQueryFixture
{
/// <summary>
/// Creates a random valid query to get a user's role.
/// </summary>
/// <returns>The created query.</returns>
public GetUserRoleQuery CreateQuery()
{
return new Faker<GetUserRoleQuery>()
.CustomInstantiator(f => new GetUserRoleQuery(
Guid.NewGuid()))
.Generate();
}
}
@@ -7,8 +7,8 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserRole;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -31,6 +31,7 @@ public class GetUserRoleQueryHandlerTests
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserRepository _mockUserRepository;
private readonly GetUserRoleQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly GetUserRoleQueryFixture _getUserRoleQueryFixture;
private readonly Guid _userId;
@@ -63,7 +64,7 @@ public class GetUserRoleQueryHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery();
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -80,7 +81,7 @@ public class GetUserRoleQueryHandlerTests
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery();
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get user");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -100,7 +101,7 @@ public class GetUserRoleQueryHandlerTests
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery();
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -119,8 +120,8 @@ public class GetUserRoleQueryHandlerTests
public async Task HandleAsync_WhenUserHasNoRole_ShouldReturnNull()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery();
UserEntity user = UserEntityFixture.CreateUserEntity();
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
UserEntity user = _userEntityFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -139,7 +140,7 @@ public class GetUserRoleQueryHandlerTests
public async Task HandleAsync_WhenUserHasRole_ShouldReturnRole()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery();
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
UserEntity user = new()
{
Id = query.UserId!.Value,