Skip to content

Commit

Permalink
refactor: rewrite validators to use fluent validation
Browse files Browse the repository at this point in the history
  • Loading branch information
raczu committed Jun 5, 2024
1 parent c6ad6fe commit fe7e7be
Show file tree
Hide file tree
Showing 29 changed files with 1,176 additions and 1,357 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ public class ServiceExceptionHandlerTests
{
private Mock<IProblemDetailsService> _mockProblemDetailsService = null!;
private ServiceExceptionHandler _handler = null!;

[TestInitialize]
public void Setup()
{
_mockProblemDetailsService = new Mock<IProblemDetailsService>();
_handler = new ServiceExceptionHandler(_mockProblemDetailsService.Object);
}

[TestMethod]
public async Task HandleException_WhenBadRequestException_ShouldReturnProblemDetails()
{
Expand All @@ -30,9 +30,9 @@ public async Task HandleException_WhenBadRequestException_ShouldReturnProblemDet
x.TryWriteAsync(It.IsAny<ProblemDetailsContext>()))
.Callback<ProblemDetailsContext>(context => problemDetailsContext = context)
.ReturnsAsync(true);

await _handler.TryHandleAsync(httpContext, exception, CancellationToken.None);

Assert.AreEqual((int)HttpStatusCode.BadRequest, httpContext.Response.StatusCode);
Assert.IsNotNull(problemDetailsContext);
Assert.AreEqual("https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
Expand All @@ -42,21 +42,21 @@ public async Task HandleException_WhenBadRequestException_ShouldReturnProblemDet
Assert.AreEqual(exception, problemDetailsContext.Exception);
Assert.AreEqual(exception.Message, problemDetailsContext.ProblemDetails.Detail);
}

[TestMethod]
public async Task HandleException_WhenNotFoundException_ShouldReturnProblemDetails()
{
var httpContext = new DefaultHttpContext();
var exception = new NotFoundException("Resource not found");

ProblemDetailsContext? problemDetailsContext = null;
_mockProblemDetailsService.Setup(x =>
_mockProblemDetailsService.Setup(x =>
x.TryWriteAsync(It.IsAny<ProblemDetailsContext>()))
.Callback<ProblemDetailsContext>(context => problemDetailsContext = context)
.ReturnsAsync(true);

await _handler.TryHandleAsync(httpContext, exception, CancellationToken.None);

Assert.AreEqual((int)HttpStatusCode.NotFound, httpContext.Response.StatusCode);
Assert.IsNotNull(problemDetailsContext);
Assert.AreEqual("https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4",
Expand All @@ -66,21 +66,21 @@ public async Task HandleException_WhenNotFoundException_ShouldReturnProblemDetai
Assert.AreEqual(exception, problemDetailsContext.Exception);
Assert.AreEqual(exception.Message, problemDetailsContext.ProblemDetails.Detail);
}

[TestMethod]
public async Task HandleException_WhenVerificationException_ShouldReturnProblemDetails()
{
var httpContext = new DefaultHttpContext();
var exception = new VerificationException("Verification error");

ProblemDetailsContext? problemDetailsContext = null;
_mockProblemDetailsService.Setup(x =>
_mockProblemDetailsService.Setup(x =>
x.TryWriteAsync(It.IsAny<ProblemDetailsContext>()))
.Callback<ProblemDetailsContext>(context => problemDetailsContext = context)
.ReturnsAsync(true);

await _handler.TryHandleAsync(httpContext, exception, CancellationToken.None);

Assert.AreEqual((int)HttpStatusCode.BadRequest, httpContext.Response.StatusCode);
Assert.IsNotNull(problemDetailsContext);
Assert.AreEqual("https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ public class ValidationExceptionHandlerTests
{
private Mock<IProblemDetailsService> _mockProblemDetailsService = null!;
private ValidationExceptionHandler _handler = null!;

[TestInitialize]
public void Setup()
{
_mockProblemDetailsService = new Mock<IProblemDetailsService>();
_handler = new ValidationExceptionHandler(_mockProblemDetailsService.Object);
}

[TestMethod]
public async Task HandleException_WhenValidationException_ShouldReturnProblemDetails()
{
Expand All @@ -35,9 +35,9 @@ public async Task HandleException_WhenValidationException_ShouldReturnProblemDet
x.TryWriteAsync(It.IsAny<ProblemDetailsContext>()))
.Callback<ProblemDetailsContext>(context => problemDetailsContext = context)
.ReturnsAsync(true);

await _handler.TryHandleAsync(httpContext, exception, CancellationToken.None);

Assert.AreEqual((int)HttpStatusCode.BadRequest, httpContext.Response.StatusCode);
Assert.IsNotNull(problemDetailsContext);
Assert.AreEqual("https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
Expand All @@ -47,7 +47,7 @@ public async Task HandleException_WhenValidationException_ShouldReturnProblemDet
Assert.AreEqual(exception, problemDetailsContext.Exception);
Assert.AreEqual("One or more validation errors occurred",
problemDetailsContext.ProblemDetails.Detail);

Assert.IsNotNull(problemDetailsContext.ProblemDetails.Extensions);
Assert.IsTrue(problemDetailsContext.ProblemDetails.Extensions.ContainsKey("errors"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,21 @@ public class AuthServiceTests
private Mock<ReasnContext> _mockContext = null!;
private PasswordHasher<User> _hasher = null!;
private AuthService _service = null!;

[TestInitialize]
public void Setup()
{
_mockContext = new Mock<ReasnContext>();
_hasher = new PasswordHasher<User>();
_service = new AuthService(_mockContext.Object);

var user = new User
{
Email = "[email protected]",
Username = "jsnow",
Password = _hasher.HashPassword(null!, "password")
};

_mockContext.Setup(c => c.Users)
.ReturnsDbSet(new List<User> { user });
}
Expand All @@ -43,9 +43,9 @@ public void Login_WhenUserExistsAndPasswordIsCorrect_ShouldReturnUser()
Email = "[email protected]",
Password = "password"
};

var result = _service.Login(request);

Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(User));
}
Expand Down Expand Up @@ -80,10 +80,10 @@ public void Register_WhenUserWithEmailAlreadyExists_ShouldThrowBadRequestExcepti
{
Email = "[email protected]"
};

Assert.ThrowsException<BadRequestException>(() => _service.Register(request));
}

[TestMethod]
public void Register_WhenUserWithUsernameAlreadyExists_ShouldThrowBadRequestException()
{
Expand All @@ -92,7 +92,7 @@ public void Register_WhenUserWithUsernameAlreadyExists_ShouldThrowBadRequestExce
Email = "[email protected]",
Username = "jsnow"
};

Assert.ThrowsException<BadRequestException>(() => _service.Register(request));
}

Expand All @@ -116,9 +116,9 @@ public void Register_WhenUserDoesNotExist_ShouldReturnRegisteredUser()
},
Role = "User"
};

var result = _service.Register(request);

Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(User));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,37 @@ public class TokenServiceTests
private TokenService _service = null!;
private Mock<IConfiguration> _mockConfiguration = null!;
private User _validUser = null!;

[TestInitialize]
public void Setup()
{
_mockConfiguration = new Mock<IConfiguration>();

var bytes = new byte[32];
RandomNumberGenerator.Fill(bytes);
_mockConfiguration.Setup(x =>
_mockConfiguration.Setup(x =>
x["JwtSettings:Key"]).Returns(Convert.ToBase64String(bytes));
_mockConfiguration.Setup(x =>

_mockConfiguration.Setup(x =>
x["JwtSettings:Issuer"]).Returns(IssAudValue);

var mockSection = new Mock<IConfigurationSection>();
var mockAudienceValue = new Mock<IConfigurationSection>();
mockAudienceValue.Setup(x => x.Value).Returns(IssAudValue);
mockSection.Setup(x =>
x.GetChildren()).Returns(new List<IConfigurationSection> { mockAudienceValue.Object });
_mockConfiguration.Setup(x =>
x.GetSection("JwtSettings:Audiences")).Returns(mockSection.Object);

var mockDurationValue = new Mock<IConfigurationSection>();
mockDurationValue.SetupGet(x => x.Value).Returns(DurationInHours.ToString());
_mockConfiguration.Setup(x =>
x.GetSection("JwtSettings:DurationInHours")).Returns(mockDurationValue.Object);

_service = new TokenService(_mockConfiguration.Object);

_validUser = new User {

_validUser = new User
{
Id = 1,
Name = "Jon",
Surname = "Snow",
Expand All @@ -58,7 +59,7 @@ public void Setup()
public void GenerateToken_WhenValidUser_ShouldReturnTokenPayload()
{
var result = _service.GenerateToken(_validUser);

Assert.IsNotNull(result);
Assert.AreEqual("Bearer", result.TokenType);
Assert.IsNotNull(result.AccessToken);
Expand All @@ -69,10 +70,10 @@ public void GenerateToken_WhenValidUser_ShouldReturnTokenPayload()
public void GenerateToken_WhenValidUser_ShouldReturnValidToken()
{
var result = _service.GenerateToken(_validUser);

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.ReadToken(result.AccessToken) as JwtSecurityToken;

Assert.IsNotNull(token);
Assert.AreEqual(IssAudValue, token.Issuer);
Assert.AreEqual(IssAudValue, token.Audiences.First());
Expand Down
Loading

0 comments on commit fe7e7be

Please sign in to comment.