Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
mehdihadeli committed Nov 29, 2023
1 parent 1abd05b commit dabb003
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 5 deletions.
6 changes: 6 additions & 0 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@
"commands": [
"nbgv"
]
},
"dotnet-depends": {
"version": "0.7.0",
"commands": [
"dotnet-depends"
]
}
}
}
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ dotnet tool install csharpier
dotnet tool install dotnet-format
```

5. Add `prepare` command for installing and activating `husky hooks` and `restoring` our installed [dotnet tools](.config/dotnet-tools.json) in the previous step to the [package.json](package.json) file:
5. Add `prepare` command for installing and activating `husky hooks` that we will add in the next steps and `restoring` our installed [dotnet tools](.config/dotnet-tools.json) in the previous step to the [package.json](package.json) file:

```bash
npm pkg set scripts.prepare="husky install && dotnet tool restore"
Expand All @@ -208,7 +208,7 @@ npm pkg set scripts.prepare="husky install && dotnet tool restore"
mkdir .husky
```

7. Link Husky and formatting tools:
7. Add formatting and Linting hooks to the husky:

```bash
npx husky add .husky/pre-commit "dotnet format && git add -A ."
Expand Down
1 change: 1 addition & 0 deletions tests/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<PackageVersion Include="Hypothesist.MassTransit" Version="2.0.30" />
<PackageVersion Include="MartinCostello.Logging.XUnit" Version="0.3.0" />
<PackageVersion Include="MassTransit" Version="8.0.8" />
<PackageVersion Include="Meziantou.Extensions.Logging.InMemory" Version="1.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0-preview.7.23375.9" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.0-preview.7.23375.4" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0-preview-23424-02" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ ITestOutputHelper outputHelper
[CategoryTrait(TestCategory.Integration)]
public async Task should_create_new_product_with_valid_input_in_sql_db()
{
InMemoryLogTrackerProvider.Logs.Errors.Should().BeEmpty();
InMemoryLogTrackerProvider.Logs.Informations.Should().NotBeEmpty();

// Arrange
var fakeCategoryId = Guid.NewGuid();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
using Meziantou.Extensions.Logging.InMemory;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Extensions.Logging;
using Vertical.Slice.Template.Api;

namespace Vertical.Slice.Template.TestsShared.Factory;

public class CustomWebApplicationFactory : WebApplicationFactory<CatalogsApiMetadata>, IAsyncLifetime
{
private ITestOutputHelper? _outputHelper;
private readonly Action<IWebHostBuilder>? _webHostBuilder;

public Action<IServiceCollection>? TestConfigureServices { get; set; }

public Action<WebHostBuilderContext, IConfigurationBuilder>? TestConfigureApp { get; set; }

/// <summary>
/// Use for tracking occured log events for testing purposes
/// </summary>
public InMemoryLoggerProvider InMemoryLogTrackerProvider { get; } = new();

public CustomWebApplicationFactory(Action<IWebHostBuilder>? webHostBuilder = null)
{
_webHostBuilder = webHostBuilder;
Expand All @@ -24,6 +36,28 @@ protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseEnvironment("test");

// UseSerilog on WebHostBuilder is absolute so we should use IHostBuilder
builder.UseSerilog(
(ctx, loggerConfiguration) =>
{
// https://www.meziantou.net/how-to-test-the-logs-from-ilogger-in-dotnet.htm
// We could also create a serilog sink for this in-memoryLoggerProvider for keep-tracking logs in the test and their states
var loggerProviderCollections = new LoggerProviderCollection();
loggerProviderCollections.AddProvider(InMemoryLogTrackerProvider);
loggerConfiguration.WriteTo.Providers(loggerProviderCollections);

//https://github.com/trbenning/serilog-sinks-xunit
if (_outputHelper is { })
{
loggerConfiguration.WriteTo.TestOutput(
_outputHelper,
LogEventLevel.Information,
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level} - {Message:lj}{NewLine}{Exception}"
);
}
}
);

// builder.ConfigureWebHost(wb =>
// {
// wb.ConfigureTestServices(services => { });
Expand All @@ -34,6 +68,8 @@ protected override IHost CreateHost(IHostBuilder builder)
return base.CreateHost(builder);
}

public void SetOutputHelper(ITestOutputHelper value) => _outputHelper = value;

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
_webHostBuilder?.Invoke(builder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ public SharedFixture(IMessageSink messageSink)
);
}

public void SetOutputHelper(ITestOutputHelper outputHelper)
{
// var loggerFactory = ServiceProvider.GetRequiredService<ILoggerFactory>();
// loggerFactory.AddXUnit(outputHelper);
Factory.SetOutputHelper(outputHelper);
}

/// <summary>
/// We should not dispose this GuestClient, because we reuse it in our tests
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Meziantou.Extensions.Logging.InMemory;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -7,7 +8,7 @@

namespace Vertical.Slice.Template.TestsShared.TestBase;

public abstract class IntegrationTest<TEntryPoint> : IAsyncLifetime
public abstract class IntegrationTest<TEntryPoint> :XunitContextBase, IAsyncLifetime
where TEntryPoint : class
{
private readonly ITestOutputHelper _outputHelper;
Expand All @@ -17,11 +18,18 @@ public abstract class IntegrationTest<TEntryPoint> : IAsyncLifetime
protected IServiceScope Scope { get; }
protected SharedFixture<TEntryPoint> SharedFixture { get; }

protected IntegrationTest(SharedFixture<TEntryPoint> sharedFixture, ITestOutputHelper outputHelper)
/// <summary>
/// Use for tracking occured log events for testing purposes
/// </summary>
protected InMemoryLoggerProvider InMemoryLogTrackerProvider { get; }

protected IntegrationTest(SharedFixture<TEntryPoint> sharedFixture, ITestOutputHelper outputHelper): base(outputHelper)
{
_outputHelper = outputHelper;
SharedFixture = sharedFixture;

SharedFixture.SetOutputHelper(outputHelper);

CancellationTokenSource = new(TimeSpan.FromSeconds(Timeout));
CancellationToken.ThrowIfCancellationRequested();

Expand All @@ -36,6 +44,7 @@ protected IntegrationTest(SharedFixture<TEntryPoint> sharedFixture, ITestOutputH

// Build Service Provider here
Scope = SharedFixture.ServiceProvider.CreateScope();
InMemoryLogTrackerProvider = sharedFixture.Factory.InMemoryLogTrackerProvider;
}

protected virtual void RegisterTestConfigureServices(IServiceCollection services) { }
Expand Down Expand Up @@ -82,7 +91,7 @@ public virtual async Task DisposeAsync()
// it is better messages delete first
await SharedFixture.ResetDatabasesAsync(CancellationToken);

CancellationTokenSource.Cancel();
await CancellationTokenSource.CancelAsync();

Scope.Dispose();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Meziantou.Extensions.Logging.InMemory" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="Mongo2Go" />
<PackageReference Include="Serilog.Sinks.XUnit" />
Expand Down

0 comments on commit dabb003

Please sign in to comment.