Skip to content

Commit

Permalink
added unit tests for HttpGlobalExceptionFilter, excluded from code co…
Browse files Browse the repository at this point in the history
…verage some infrastructure code
  • Loading branch information
lkurzyniec committed Jan 3, 2025
1 parent 1d00089 commit df351a8
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 11 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dotnetcore.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ on:
env:
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
EXCLUDE_PATHS: '\"**/Program.cs,**/Startup.cs,**/Configurations/*.cs,**/Registrations/*.cs,**/Filters/*Swagger*Filter.cs,**/*Context.cs\"'
EXCLUDE_PATHS: '\"**/Program.cs,**/Startup.cs,**/*Context.cs\"'

jobs:
build-and-test:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System.Diagnostics.CodeAnalysis;

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Configurations;

[ExcludeFromCodeCoverage]
public static class BannerConfigurator
{
private const string _cyan = "\x1b[96m";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System.Diagnostics.CodeAnalysis;
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Core;

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Configurations
{
[ExcludeFromCodeCoverage]
public static class SerilogConfigurator
{
public static Logger CreateLogger()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HappyCode.NetCoreBoilerplate.Core;
using Microsoft.FeatureManagement;
Expand All @@ -7,6 +8,7 @@

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters
{
[ExcludeFromCodeCoverage]
public class FeatureFlagSwaggerDocumentFilter : IDocumentFilter
{
private readonly IFeatureManager _featureManager;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
using System.Linq;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Authorization;
using System.Diagnostics.CodeAnalysis;

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters
{
[ExcludeFromCodeCoverage]
public class SecurityRequirementSwaggerOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Middlewares
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Middlewares;

[ExcludeFromCodeCoverage]
public class ConnectionInfoMiddleware(RequestDelegate next, ILogger<ConnectionInfoMiddleware> logger)
{
public class ConnectionInfoMiddleware(RequestDelegate next, ILogger<ConnectionInfoMiddleware> logger)
{
private readonly RequestDelegate _next = next;
private readonly ILogger<ConnectionInfoMiddleware> _logger = logger;
private readonly RequestDelegate _next = next;
private readonly ILogger<ConnectionInfoMiddleware> _logger = logger;

public async Task InvokeAsync(HttpContext httpContext)
{
_logger.LogDebug("===> Connection: {Connection}", new { ConnectionId = httpContext.Connection.Id, LocalIP = httpContext.Connection.LocalIpAddress, RemoteIP = httpContext.Connection.RemoteIpAddress });
public async Task InvokeAsync(HttpContext httpContext)
{
_logger.LogDebug("===> Connection: {Connection}", new { ConnectionId = httpContext.Connection.Id, LocalIP = httpContext.Connection.LocalIpAddress, RemoteIP = httpContext.Connection.RemoteIpAddress });

await _next.Invoke(httpContext);
}
await _next.Invoke(httpContext);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.IO;
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters;
using Microsoft.Extensions.Configuration;
Expand All @@ -6,6 +7,7 @@

namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Registrations
{
[ExcludeFromCodeCoverage]
public static class SwaggerRegistration
{
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using FluentAssertions;
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

namespace HappyCode.NetCoreBoilerplate.Api.UnitTests.Infrastructure.Filters
{
public class HttpGlobalExceptionFilterTests
{
private const string _exMessage = "Some exception test message";

private readonly HttpGlobalExceptionFilter _sut;

private readonly Mock<IWebHostEnvironment> _envMock;

public HttpGlobalExceptionFilterTests()
{
_envMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);

_sut = new HttpGlobalExceptionFilter(_envMock.Object, new Mock<ILogger<HttpGlobalExceptionFilter>>().Object);
}

[Fact]
public void When_Development_Then_exception_details_returned()
{
//given
_envMock.SetupGet(x => x.EnvironmentName).Returns("Development");

//when
var context = GetMockedContext();
_sut.OnException(context);

//then
context.Result.Should().NotBeNull();
context.Result.Should().BeOfType<ObjectResult>()
.Subject.StatusCode.Should().Be(StatusCodes.Status500InternalServerError);
context.Result.Should().BeOfType<ObjectResult>()
.Subject.Value.Should().BeOfType<ErrorResponse>()
.Subject.Exception.Should().NotBeNullOrEmpty()
.And.Contain(_exMessage);
}

[Fact]
public void When_not_Development_Then_exception_details_empty()
{
//given
_envMock.SetupGet(x => x.EnvironmentName).Returns("Other");

//when
var context = GetMockedContext();
_sut.OnException(context);

//then
context.Result.Should().NotBeNull();
context.Result.Should().BeOfType<ObjectResult>()
.Subject.Value.Should().BeOfType<ErrorResponse>()
.Subject.Exception.Should().BeNullOrEmpty();
}

private ExceptionContext GetMockedContext()
{
var actionContext = new ActionContext(
Mock.Of<HttpContext>(),
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
Mock.Of<ModelStateDictionary>()
);

return new ExceptionContext(actionContext, [])
{
Exception = new Exception(_exMessage),
};
}
}
}

0 comments on commit df351a8

Please sign in to comment.