Skip to content

Commit

Permalink
(#23) logging: add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
SaintAngeLs committed Sep 21, 2024
1 parent df4aa41 commit 247e58e
Show file tree
Hide file tree
Showing 13 changed files with 355 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/Paralax.CQRS.Logging/src/Paralax.CQRS.Logging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
35 changes: 35 additions & 0 deletions src/Paralax.Logging/scripts/build-and-pack.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/bin/bash

echo "Executing post-success scripts for branch $GITHUB_REF_NAME"
echo "Starting build and NuGet package creation for Paralax.Security..."

cd src/Paralax.Security/src

echo "Restoring NuGet packages..."
dotnet restore

PACKAGE_VERSION="1.0.$GITHUB_RUN_NUMBER"
echo "Building and packing the Paralax.Security library..."
dotnet pack -c release /p:PackageVersion=$PACKAGE_VERSION --no-restore -o ./nupkg

PACKAGE_PATH="./nupkg/Paralax.Security.$PACKAGE_VERSION.nupkg"

if [ -f "$PACKAGE_PATH" ]; then
echo "Checking if the package is already signed..."
if dotnet nuget verify "$PACKAGE_PATH" | grep -q 'Package is signed'; then
echo "Package is already signed, skipping signing."
else
echo "Signing the NuGet package..."
dotnet nuget sign "$PACKAGE_PATH" \
--certificate-path "$CERTIFICATE_PATH" \
--timestamper http://timestamp.digicert.com
fi

echo "Uploading Paralax.Security package to NuGet..."
dotnet nuget push "$PACKAGE_PATH" -k "$NUGET_API_KEY" \
-s https://api.nuget.org/v3/index.json --skip-duplicate
echo "Package uploaded to NuGet."
else
echo "Error: Package $PACKAGE_PATH not found."
exit 1
fi
18 changes: 18 additions & 0 deletions src/Paralax.Logging/scripts/test-and-collect-coverage.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

echo "Running tests and collecting coverage for Paralax.Security..."

cd src/Paralax.Security/src

echo "Restoring NuGet packages..."
dotnet restore

echo "Running tests and generating code coverage report..."
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults

# Check if tests succeeded
if [ $? -ne 0 ]; then
echo "Tests failed. Exiting..."
exit 1
fi

6 changes: 6 additions & 0 deletions src/Paralax.Logging/src/Paralax.Logging.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,10 @@
<PackageReference Include="Serilog.Sinks.Seq" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>Paralax.Logging.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

</Project>
100 changes: 100 additions & 0 deletions src/Paralax.Logging/tests/CorrelationContextLoggingMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Paralax.Logging;
using Moq;
using Xunit;

namespace Paralax.Logging.Tests
{
public class CorrelationContextLoggingMiddlewareTests
{
private readonly Mock<ILogger<CorrelationContextLoggingMiddleware>> _loggerMock;
private readonly Mock<RequestDelegate> _nextMock;
private readonly CorrelationContextLoggingMiddleware _middleware;

public CorrelationContextLoggingMiddlewareTests()
{
// Set up the mocks
_loggerMock = new Mock<ILogger<CorrelationContextLoggingMiddleware>>();
_nextMock = new Mock<RequestDelegate>();

// Instantiate the middleware with the mock logger
_middleware = new CorrelationContextLoggingMiddleware(_loggerMock.Object);
}

[Fact]
public async Task InvokeAsync_Should_Log_Correlation_Headers_When_Activity_Exists()
{
// Arrange
var httpContext = new DefaultHttpContext();
var baggage = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("CorrelationId", "12345"),
new KeyValuePair<string, string>("UserId", "User123")
};

// Simulate an Activity with baggage
var activity = new Activity("TestActivity");
activity.AddBaggage("CorrelationId", "12345");
activity.AddBaggage("UserId", "User123");
activity.Start();

_nextMock.Setup(next => next(It.IsAny<HttpContext>())).Returns(Task.CompletedTask);

// Act
await _middleware.InvokeAsync(httpContext, _nextMock.Object);

// Assert
_loggerMock.Verify(logger =>
logger.BeginScope(It.Is<Dictionary<string, string>>(d =>
d.ContainsKey("CorrelationId") && d["CorrelationId"] == "12345" &&
d.ContainsKey("UserId") && d["UserId"] == "User123")), Times.Once);

// Cleanup
activity.Stop();
}

[Fact]
public async Task InvokeAsync_Should_Log_Empty_Headers_When_Activity_Is_Null()
{
// Arrange
var httpContext = new DefaultHttpContext();

// No active activity, meaning Activity.Current is null
Activity.Current = null;

_nextMock.Setup(next => next(It.IsAny<HttpContext>())).Returns(Task.CompletedTask);

// Act
await _middleware.InvokeAsync(httpContext, _nextMock.Object);

// Assert
_loggerMock.Verify(logger =>
logger.BeginScope(It.Is<Dictionary<string, string>>(d => d.Count == 0)), Times.Once);
}

[Fact]
public async Task InvokeAsync_Should_Call_Next_Middleware()
{
// Arrange
var httpContext = new DefaultHttpContext();

// Simulate an empty Activity
var activity = new Activity("TestActivity").Start();
_nextMock.Setup(next => next(It.IsAny<HttpContext>())).Returns(Task.CompletedTask);

// Act
await _middleware.InvokeAsync(httpContext, _nextMock.Object);

// Assert
_nextMock.Verify(next => next(It.IsAny<HttpContext>()), Times.Once);

// Cleanup
activity.Stop();
}
}
}
48 changes: 48 additions & 0 deletions src/Paralax.Logging/tests/ExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Xunit;

namespace Paralax.Logging.Tests
{
public class ExtensionsTests
{
[Fact]
public void UseLogging_Should_Register_LoggingService_On_HostBuilder()
{
// Arrange
var hostBuilder = new HostBuilder();

// Act
hostBuilder.UseLogging();
var host = hostBuilder.Build();
var loggingService = host.Services.GetService<ILoggingService>();

// Assert
Assert.NotNull(loggingService);
}

[Fact]
public void UseLogging_Should_Configure_Serilog_On_HostBuilder()
{
// Arrange
var hostBuilder = new HostBuilder();
var loggerConfigurationMock = new Mock<LoggerConfiguration>();

// Act
hostBuilder.UseLogging((context, loggerConfig) =>
{
loggerConfig.WriteTo.Console();
});

var host = hostBuilder.Build();

// Assert
var loggingService = host.Services.GetService<ILoggingService>();
Assert.NotNull(loggingService); // Check if logging service is registered
}
}
}
65 changes: 65 additions & 0 deletions src/Paralax.Logging/tests/ExtensionsWebHostTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Serilog;
using Xunit;

namespace Paralax.Logging.Tests
{
public class ExtensionsWebHostTests
{
// Mock Startup class to ensure that web host configuration is valid
public class TestStartup
{
public void ConfigureServices(IServiceCollection services)
{
// Add required services here (logging, etc.)
services.AddSingleton<ILoggingService, LoggingService>(); // Example service registration
}

// A Configure method is required by WebHostBuilder for setting up the request pipeline
public void Configure(IApplicationBuilder app)
{
// Minimal middleware setup, can be left empty or add minimal configurations
app.UseRouting();
}
}

[Fact]
public void UseLogging_Should_Register_LoggingService_On_WebHostBuilder()
{
// Arrange
var webHostBuilder = new WebHostBuilder()
.UseStartup<TestStartup>(); // Provide a minimal Startup class

// Act
webHostBuilder.UseLogging();
var webHost = webHostBuilder.Build();
var loggingService = webHost.Services.GetService<ILoggingService>();

// Assert
Assert.NotNull(loggingService); // Verify if the logging service is registered
}

[Fact]
public void UseLogging_Should_Configure_Serilog_On_WebHostBuilder()
{
// Arrange
var webHostBuilder = new WebHostBuilder()
.UseStartup<TestStartup>(); // Provide a minimal Startup class

// Act
webHostBuilder.UseLogging((context, loggerConfig) =>
{
loggerConfig.WriteTo.Console(); // Configure Serilog
});

var webHost = webHostBuilder.Build();

// Assert
var loggingService = webHost.Services.GetService<ILoggingService>();
Assert.NotNull(loggingService); // Check if logging service is registered
}
}
}
Empty file.
Empty file.
40 changes: 40 additions & 0 deletions src/Paralax.Logging/tests/Paralax.Logging.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0" />
<PackageReference Include="Paralax" Version="1.0.96" />

<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />

<PackageReference Include="Serilog" Version="4.0.2-dev-02226" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="6.0.0" />

<PackageReference Include="Moq" Version="4.18.3" />
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />

<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />


</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\src\Paralax.Logging.csproj" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions src/Paralax.Logging/tests/Paralax.Logging.Tests.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Paralax.Logging.Tests", "Paralax.Logging.Tests.csproj", "{6171C645-820E-41DA-BAA6-CF33C2069427}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6171C645-820E-41DA-BAA6-CF33C2069427}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6171C645-820E-41DA-BAA6-CF33C2069427}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6171C645-820E-41DA-BAA6-CF33C2069427}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6171C645-820E-41DA-BAA6-CF33C2069427}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DD4E79DA-E238-4315-A58B-9595AC1B57BB}
EndGlobalSection
EndGlobal
8 changes: 8 additions & 0 deletions src/Paralax/src/Core/DecoratorAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System;

namespace Paralax.Core;

// Marker
public class DecoratorAttribute : Attribute
{
}
2 changes: 1 addition & 1 deletion src/Paralax/src/Core/ServiceId.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using Paralax.Types;

namespace Paralax
namespace Paralax.Core
{
internal class ServiceId : IServiceId
{
Expand Down

0 comments on commit 247e58e

Please sign in to comment.