Skip to content

Commit

Permalink
Merge pull request #255 from meysamhadeli/fix/fix-problem-persist-mes…
Browse files Browse the repository at this point in the history
…sage-background-job

fix: Fix problem run persist-message background job service in test-base
  • Loading branch information
meysamhadeli authored May 8, 2023
2 parents 7bee658 + f24c3c9 commit d59c176
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 44 deletions.
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,11 @@ dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_chec
dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style
dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error

##########################################
# VSThread
##########################################
dotnet_diagnostic.VSTHRD111.severity = none


##########################################
# Other Naming Rules
Expand Down
1 change: 0 additions & 1 deletion src/BuildingBlocks/BuildingBlocks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@
<Folder Include="Core\Pagination" />
<Folder Include="EventStoreDB\BackgroundWorkers" />
<Folder Include="PersistMessageProcessor\Data\Configurations" />
<Folder Include="PersistMessageProcessor\Data\Migrations" />
</ItemGroup>

</Project>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 14 additions & 8 deletions src/BuildingBlocks/PersistMessageProcessor/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ namespace BuildingBlocks.PersistMessageProcessor;

public static class Extensions
{
public static IServiceCollection AddPersistMessageProcessor(this IServiceCollection services)
public static IServiceCollection AddPersistMessageProcessor(this IServiceCollection services,
IWebHostEnvironment env)
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

Expand All @@ -21,23 +22,28 @@ public static IServiceCollection AddPersistMessageProcessor(this IServiceCollect
var persistMessageOptions = sp.GetRequiredService<PersistMessageOptions>();

options.UseNpgsql(persistMessageOptions.ConnectionString,
dbOptions =>
{
dbOptions.MigrationsAssembly(typeof(PersistMessageDbContext).Assembly.GetName().Name);
})
dbOptions =>
{
dbOptions.MigrationsAssembly(typeof(PersistMessageDbContext).Assembly.GetName().Name);
})
// https://github.com/efcore/EFCore.NamingConventions
.UseSnakeCaseNamingConvention();;
.UseSnakeCaseNamingConvention();
});

services.AddScoped<IPersistMessageDbContext>(provider => provider.GetService<PersistMessageDbContext>());

services.AddScoped<IPersistMessageProcessor, PersistMessageProcessor>();
services.AddHostedService<PersistMessageBackgroundService>();

if (env.EnvironmentName != "test")
{
services.AddHostedService<PersistMessageBackgroundService>();
}

return services;
}

public static IApplicationBuilder UseMigrationPersistMessage<TContext>(this IApplicationBuilder app, IWebHostEnvironment env)
public static IApplicationBuilder UseMigrationPersistMessage<TContext>(this IApplicationBuilder app,
IWebHostEnvironment env)
where TContext : DbContext, IPersistMessageDbContext
{
using var scope = app.ApplicationServices.CreateScope();
Expand Down
67 changes: 41 additions & 26 deletions src/BuildingBlocks/TestBase/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using BuildingBlocks.Mongo;
using BuildingBlocks.PersistMessageProcessor;
using BuildingBlocks.Web;
using DotNet.Testcontainers.Containers;
using EasyNetQ.Management.Client;
using Grpc.Net.Client;
using MassTransit;
Expand Down Expand Up @@ -49,6 +48,10 @@ public class TestFixture<TEntryPoint> : IAsyncLifetime
public RabbitMqContainer RabbitMqTestContainer;
public MongoDbContainer MongoDbTestContainer;
public EventStoreDbContainer EventStoreDbTestContainer;
public CancellationTokenSource CancellationTokenSource;

public PersistMessageBackgroundService PersistMessageBackgroundService =>
ServiceProvider.GetRequiredService<PersistMessageBackgroundService>();

public HttpClient HttpClient
{
Expand Down Expand Up @@ -85,6 +88,12 @@ protected TestFixture()
TestRegistrationServices?.Invoke(services);
services.ReplaceSingleton(AddHttpContextAccessorMock);

services.AddSingleton<PersistMessageBackgroundService>();

// // remove persist-message processor background service
// var descriptor = services.Single(s => s.ImplementationType == typeof(PersistMessageBackgroundService));
// services.Remove(descriptor);

// add authentication using a fake jwt bearer - we can use SetAdminUser method to set authenticate user to existing HttContextAccessor
// https://github.com/webmotions/fake-authentication-jwtbearer
// https://github.com/webmotions/fake-authentication-jwtbearer/issues/14
Expand All @@ -99,13 +108,15 @@ protected TestFixture()

public async Task InitializeAsync()
{
CancellationTokenSource = new CancellationTokenSource();
await StartTestContainerAsync();
}

public async Task DisposeAsync()
{
await StopTestContainerAsync();
await _factory.DisposeAsync();
CancellationTokenSource.Cancel();
}

public virtual void RegisterServices(Action<IServiceCollection> services)
Expand Down Expand Up @@ -141,6 +152,7 @@ protected async Task<T> ExecuteScopeAsync<T>(Func<IServiceProvider, Task<T>> act
return result;
}


public Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
return ExecuteScopeAsync(sp =>
Expand Down Expand Up @@ -173,7 +185,6 @@ public async Task<bool> WaitForPublishing<TMessage>(CancellationToken cancellati
{
var published = await TestHarness.Published.Any<TMessage>(cancellationToken);
var faulty = await TestHarness.Published.Any<Fault<TMessage>>(cancellationToken);

return published && faulty == false;
});
return result;
Expand All @@ -193,30 +204,8 @@ public async Task<bool> WaitForConsuming<TMessage>(CancellationToken cancellatio
return result;
}

// Ref: https://tech.energyhelpline.com/in-memory-testing-with-masstransit/
private async Task<bool> WaitUntilConditionMet(Func<Task<bool>> conditionToMet, int? timeoutSecond = null)
{
var time = timeoutSecond ?? Timeout;

var startTime = DateTime.Now;
var timeoutExpired = false;
var meet = await conditionToMet.Invoke();
while (!meet)
{
if (timeoutExpired)
{
return false;
}

await Task.Delay(100);
meet = await conditionToMet.Invoke();
timeoutExpired = DateTime.Now - startTime > TimeSpan.FromSeconds(time);
}

return true;
}

public async Task<bool> ShouldProcessedPersistInternalCommand<TInternalCommand>()
public async Task<bool> ShouldProcessedPersistInternalCommand<TInternalCommand>(
CancellationToken cancellationToken = default)
where TInternalCommand : class, IInternalCommand
{
var result = await WaitUntilConditionMet(async () =>
Expand All @@ -239,6 +228,28 @@ public async Task<bool> ShouldProcessedPersistInternalCommand<TInternalCommand>(
return result;
}

// Ref: https://tech.energyhelpline.com/in-memory-testing-with-masstransit/
private async Task<bool> WaitUntilConditionMet(Func<Task<bool>> conditionToMet, int? timeoutSecond = null)
{
var time = timeoutSecond ?? Timeout;

var startTime = DateTime.Now;
var timeoutExpired = false;
var meet = await conditionToMet.Invoke();
while (!meet)
{
if (timeoutExpired)
{
return false;
}

await Task.Delay(100);
meet = await conditionToMet.Invoke();
timeoutExpired = DateTime.Now - startTime > TimeSpan.FromSeconds(time);
}

return true;
}

private async Task StartTestContainerAsync()
{
Expand Down Expand Up @@ -496,6 +507,8 @@ private async Task InitPostgresAsync()

if (!string.IsNullOrEmpty(persistOptions?.ConnectionString))
{
await Fixture.PersistMessageBackgroundService.StartAsync(Fixture.CancellationTokenSource.Token);

PersistDbConnection = new NpgsqlConnection(persistOptions.ConnectionString);
await PersistDbConnection.OpenAsync();

Expand All @@ -520,6 +533,8 @@ private async Task ResetPostgresAsync()
if (PersistDbConnection is not null)
{
await _reSpawnerPersistDb.ResetAsync(PersistDbConnection);

await Fixture.PersistMessageBackgroundService.StopAsync(Fixture.CancellationTokenSource.Token);
}

if (DefaultDbConnection is not null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static WebApplicationBuilder AddInfrastructure(this WebApplicationBuilder
}));
});

builder.Services.AddPersistMessageProcessor();
builder.Services.AddPersistMessageProcessor(env);
builder.Services.AddMongoDbContext<BookingReadDbContext>(configuration);

builder.AddCustomSerilog(env);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public static WebApplicationBuilder AddInfrastructure(this WebApplicationBuilder
builder.Services.AddCustomDbContext<FlightDbContext>();
builder.Services.AddScoped<IDataSeeder, FlightDataSeeder>();
builder.Services.AddMongoDbContext<FlightReadDbContext>(configuration);
builder.Services.AddPersistMessageProcessor();
builder.Services.AddPersistMessageProcessor(env);

builder.AddCustomSerilog(env);
builder.Services.AddJwt();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@

namespace Integration.Test.Aircraft.Features;

using global::Flight.Aircrafts.Features.CreatingAircraft.V1;

public class CreateAircraftTests : FlightIntegrationTestBase
{
public CreateAircraftTests(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@

namespace Integration.Test.Airport.Features;

using global::Flight.Airports.Features.CreatingAirport.V1;

public class CreateAirportTests : FlightIntegrationTestBase
{
public CreateAirportTests(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static WebApplicationBuilder AddInfrastructure(this WebApplicationBuilder
});

builder.Services.AddControllers();
builder.Services.AddPersistMessageProcessor();
builder.Services.AddPersistMessageProcessor(env);
builder.Services.AddCustomDbContext<IdentityContext>();
builder.Services.AddScoped<IDataSeeder, IdentityDataSeeder>();
builder.AddCustomSerilog(env);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static WebApplicationBuilder AddInfrastructure(this WebApplicationBuilder
}));
});

builder.Services.AddPersistMessageProcessor();
builder.Services.AddPersistMessageProcessor(env);
builder.Services.AddCustomDbContext<PassengerDbContext>();
builder.Services.AddMongoDbContext<PassengerReadDbContext>(configuration);

Expand Down

0 comments on commit d59c176

Please sign in to comment.