Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Authentication UnitTest #5

Merged
merged 2 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using FluentAssertions;
using Moq;
using SearchBugs.Application.Authentications.Login;
using SearchBugs.Domain.Services;
using SearchBugs.Domain.Users;
using Shared.Results;

namespace SearchBugs.Application.UnitTests.AuthenicationsTest;

public class LoginCommandHandlerTest
{
private readonly Mock<IUserRepository> _userRepository;
private readonly Mock<IJwtProvider> _jwtProvider;
private readonly Mock<IPasswordHashingService> _hasher;
private readonly LoginCommandHandler _sut;

public LoginCommandHandlerTest()
{
_userRepository = new();
_jwtProvider = new();
_hasher = new();
_sut = new LoginCommandHandler(_userRepository.Object, _jwtProvider.Object, _hasher.Object);
}

[Fact]
public async Task Handle_WhenUserNotFound_ShouldReturnFailure_WithNotFoundByEmailError()
{
// Arrange
var email = "[email protected]";
var password = "password";
var command = new LoginCommand(email, password);
_userRepository.Setup(x => x.GetUserByEmailAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Failure<User>(UserErrors.NotFoundByEmail(email)));

// Act
var result = await _sut.Handle(command, CancellationToken.None);

// Assert
result.IsSuccess.Should().BeFalse();
result.Error.Should().Be(UserErrors.NotFoundByEmail(email));
}

[Fact]
public async Task Handle_WhenPasswordIsInvalid_ShouldReturnFailure_WithInvalidPasswordError()
{
// Arrange
var email = "[email protected]";
var password = "password";
var command = new LoginCommand(email, password);
_userRepository.Setup(x => x.GetUserByEmailAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Success(User.Create(Name.Create("First", "Last"), Email.Create(email), "hashedPassword").Value));

_hasher.Setup(x => x.VerifyPassword(It.IsAny<string>(), It.IsAny<string>()))
.Returns(false);

// Act
var result = await _sut.Handle(command, CancellationToken.None);
result.IsSuccess.Should().BeFalse();
result.Error.Should().Be(UserErrors.InvalidPassword);
}

[Fact]
public async Task Handle_WhenUserFound_ShouldReturnSuccess_WithJwtToken()
{
// Arrange
var email = "[email protected]";
var password = "password";
var command = new LoginCommand(email, password);
var user = User.Create(Name.Create("First", "Last"), Email.Create(email), "hashedPassword").Value;
_userRepository.Setup(x => x.GetUserByEmailAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Success(user));

_hasher.Setup(x => x.VerifyPassword(It.IsAny<string>(), It.IsAny<string>()))
.Returns(true);

_jwtProvider.Setup(x => x.GenerateJwtToken(It.IsAny<User>()))
.Returns("jwtToken");

// Act
var result = await _sut.Handle(command, CancellationToken.None);
result.IsSuccess.Should().BeTrue();
result.Value.Token.Should().Be("jwtToken");

}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using FluentAssertions;
using Moq;
using SearchBugs.Application.Authentications;
using SearchBugs.Application.Authentications.Register;
using SearchBugs.Domain;
using SearchBugs.Domain.Roles;
using SearchBugs.Domain.Services;
using SearchBugs.Domain.Users;
using Shared.Results;

namespace SearchBugs.Application.UnitTests.AuthenicationsTest;

public class RegisterCommandHandlerTest
{
private readonly Mock<IUserRepository> _userRepository;
private readonly Mock<IPasswordHashingService> _hasher;
private readonly Mock<IUnitOfWork> _unitOfWork;
private readonly RegisterCommandHandler _sut;

public RegisterCommandHandlerTest()
{
_userRepository = new();
_hasher = new();
_unitOfWork = new();
_sut = new RegisterCommandHandler(_userRepository.Object, _hasher.Object, _unitOfWork.Object);
}

[Fact]
public async Task Handle_WhenEmailIsNotUnique_ShouldReturnFailure_WithDuplicateEmailError()
{
// Arrange
var email = "[email protected]";
var password = "password";

var command = new RegisterCommand(email, password, "First", "Last");

_userRepository.Setup(x => x.IsEmailUniqueAsync(Email.Create(email), It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Failure<User>(AuthValidationErrors.EmailAlreadyExists));

// Act
var result = await _sut.Handle(command, CancellationToken.None);

// Assert
result.IsSuccess.Should().BeFalse();
result.Error.Should().Be(AuthValidationErrors.EmailAlreadyExists);
}

[Fact]
public async Task Handle_WhenEmailIsUnique_ShouldReturnSuccess()
{
// Arrange
var email = "[email protected]";
var password = "password";

var command = new RegisterCommand(email, password, "First", "Last");

_userRepository.Setup(x => x.IsEmailUniqueAsync(Email.Create(email), It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Success<User>(User.Create(Name.Create("First", "Last"), Email.Create(email), "hashedPassword").Value));


_userRepository.Setup(x => x.GetRoleByIdAsync(Role.Guest.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(Result.Success<Role>(Role.Guest));

// Act
var result = await _sut.Handle(command, CancellationToken.None);

// Assert
result.IsSuccess.Should().BeTrue();
_userRepository.Verify(x => x.Add(It.IsAny<User>()), Times.Once);
_unitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
_userRepository.Verify(x => x.GetRoleByIdAsync(Role.Guest.Id, It.IsAny<CancellationToken>()), Times.Once);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,18 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand All @@ -24,4 +32,10 @@
<Folder Include="Data\Users\" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SearchBugs.Application\SearchBugs.Application.csproj" />
<ProjectReference Include="..\SearchBugs.Domain\SearchBugs.Domain.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ internal static class AuthValidationErrors

internal static Error UserNotFound => new("User.UserNotFound", "The user was not found.");

internal static Error FirstNameIsRequired => new("User.FirstNameIsRequired", "The user's first name is required.");
internal static Error LastNameIsRequired => new("User.LastNameIsRequired", "The user's last name is required.");

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public async Task<Result> Handle(RegisterCommand request, CancellationToken canc
Name.Create(request.FirstName, request.LastName),
Email.Create(request.Email),
passwordHashingService.HashPassword(request.Password));
var emailIsUnique = await CheckIfEmailIsUniqueAsync(user.Value.Email, cancellationToken);
if (!emailIsUnique.IsSuccess)
{
return Result.Failure(AuthValidationErrors.EmailAlreadyExists);
}

var role = await _userRepository.GetRoleByIdAsync(Role.Guest.Id, cancellationToken);
user.Value.AddRole(role.Value);
Expand All @@ -36,6 +41,6 @@ public async Task<Result> Handle(RegisterCommand request, CancellationToken canc

}

private async Task<Result<User>> CheckIfEmailIsUniqueAsync(User user, CancellationToken cancellationToken) =>
await _userRepository.IsEmailUniqueAsync(user.Email, cancellationToken);
private async Task<Result<User>> CheckIfEmailIsUniqueAsync(Email email, CancellationToken cancellationToken) =>
await _userRepository.IsEmailUniqueAsync(email, cancellationToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ internal sealed class RegisterCommandValidator : AbstractValidator<RegisterComma
{
public RegisterCommandValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress();
RuleFor(x => x.Email).NotEmpty().EmailAddress().WithError(AuthValidationErrors.InvalidEmail);
RuleFor(x => x.Password).NotEmpty()
.MinimumLength(6)
.ChildRules(x => x.RuleFor(y => y).Matches("[A-Z]").WithError(AuthValidationErrors.PasswordNotMatchRequirements("Password must contain at least one uppercase letter")))
.ChildRules(x => x.RuleFor(y => y).Matches("[a-z]").WithError(AuthValidationErrors.PasswordNotMatchRequirements("Password must contain at least one lowercase letter")))
.ChildRules(x => x.RuleFor(y => y).Matches("[0-9]").WithError(AuthValidationErrors.PasswordNotMatchRequirements("Password must contain at least one number")));

RuleFor(x => x.FirstName).NotEmpty();
RuleFor(x => x.LastName).NotEmpty();
RuleFor(x => x.FirstName).NotEmpty().WithError(AuthValidationErrors.FirstNameIsRequired);
RuleFor(x => x.LastName).NotEmpty().WithError(AuthValidationErrors.LastNameIsRequired);
}
}
4 changes: 1 addition & 3 deletions SearchBugs.Application/DependencyInjection.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Shared.Behaviors;
namespace SearchBugs.Application;
Expand All @@ -11,10 +10,9 @@ public static IServiceCollection AddApplication(this IServiceCollection services
services.AddMediatR(config =>
{
config.RegisterServicesFromAssemblyContaining<ApplicationAssemblyReference>();

config.AddOpenBehavior(typeof(ValidationPipelineBehavior<,>));
});
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationPipelineBehavior<,>));


services.AddValidatorsFromAssembly(ApplicationAssemblyReference.Assembly);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using FluentValidation;
using Shared.Extensions;

namespace SearchBugs.Application.Git.CreateGitRepo;

internal sealed class CreateGitRepoCommandValidator : AbstractValidator<CreateGitRepoCommand>
{
public CreateGitRepoCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.WithError(GitValidationErrors.NameIsRequired);

RuleFor(x => x.Description)
.NotEmpty()
.WithError(GitValidationErrors.DescriptionIsRequired);

RuleFor(x => x.Url)
.NotEmpty()
.WithError(GitValidationErrors.UrlIsRequired);
}
}
11 changes: 11 additions & 0 deletions SearchBugs.Application/Git/GitValidationErrors.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Shared.Errors;

namespace SearchBugs.Application.Git;

internal static class GitValidationErrors
{
internal static Error NameIsRequired => new("Git.NameIsRequired", "The git's name is required.");
internal static Error DescriptionIsRequired => new("Git.DescriptionIsRequired", "The git's description is required.");
internal static Error UrlIsRequired => new("Git.UrlIsRequired", "The git's url is required.");

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using FluentValidation;

namespace SearchBugs.Application.Projects.CreateProject;

public sealed class CreateProjectCommandValidator : AbstractValidator<CreateProjectCommand>
{
public CreateProjectCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(2);
}
}
36 changes: 36 additions & 0 deletions SearchBugs.Domain.UnitTests/Bugs/BugsUnitTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using FluentAssertions;
using SearchBugs.Domain.Bugs;
using SearchBugs.Domain.UnitTests.Data.Bugs;

namespace SearchBugs.Domain.UnitTests.Bugs;

public class BugsUnitTest
{

[Theory]
[ClassData(typeof(CreateBug))]
public void CreateBug(Bug bug)
{
var bugTest = Bug.Create(
bug.Title,
bug.Description,
bug.StatusId,
bug.PriorityId,
bug.Severity,
bug.ProjectId,
bug.AssigneeId,
bug.ReporterId

);

bug.Title.Should().Be(bugTest.Value.Title);
bug.Description.Should().Be(bugTest.Value.Description);
bug.StatusId.Should().Be(bugTest.Value.StatusId);
bug.PriorityId.Should().Be(bugTest.Value.PriorityId);
bug.Severity.Should().Be(bugTest.Value.Severity);
bug.ProjectId.Should().Be(bugTest.Value.ProjectId);
bug.ReporterId.Should().Be(bugTest.Value.ReporterId);
bug.AssigneeId.Should().Be(bugTest.Value.AssigneeId);

}
}
4 changes: 2 additions & 2 deletions SearchBugs.Domain.UnitTests/Data/Bugs/CreateBug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public CreateBug()
Result<Bug> bug = Bug.Create(
faker.Lorem.Sentence(),
faker.Lorem.Paragraph(),
item,
item2,
item.Id,
item2.Id,
faker.Lorem.Sentence(),
new ProjectId(faker.Random.Guid()),
new UserId(faker.Random.Guid()),
Expand Down
4 changes: 2 additions & 2 deletions SearchBugs.Domain.UnitTests/Data/Users/UserCreate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ public UserCreate()
{
var faker = new Faker();

User userRegistration = User.Create(
var userRegistration = User.Create(
Name.Create(faker.Name.FirstName(), faker.Name.LastName()),
Email.Create(faker.Internet.Email()),
faker.Internet.Password());

Add(userRegistration);
Add(userRegistration.Value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Bogus" Version="35.6.0" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
Expand All @@ -21,10 +22,6 @@
<Using Include="Xunit" />
</ItemGroup>

<ItemGroup>
<Folder Include="Bugs\" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SearchBugs.Domain\SearchBugs.Domain.csproj" />
</ItemGroup>
Expand Down
Loading
Loading