Skip to content

Commit

Permalink
Added example on how to use test containers with Marten
Browse files Browse the repository at this point in the history
  • Loading branch information
oskardudycz committed Aug 4, 2023
1 parent 6e495d6 commit 3ec0e0e
Show file tree
Hide file tree
Showing 14 changed files with 151 additions and 103 deletions.
65 changes: 35 additions & 30 deletions Marten.Integration.Tests/Commands/MartenAsyncCommandBusTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,33 @@ namespace Marten.Integration.Tests.Commands;

public class MartenAsyncCommandBusTests: MartenTest
{
private readonly MartenAsyncCommandBus martenAsyncCommandBus;
private readonly List<Guid> userIds = new();
private readonly EventListener eventListener = new();
private readonly AsyncProjectionHostedService asyncDaemon;
private readonly CancellationToken ct = new CancellationTokenSource().Token;
[Fact]
public async Task CommandIsStoredInMartenAndForwardedToCommandHandler()
{
// Given
var userId = Guid.NewGuid();
var command = new AddUser(userId);

// When
await asyncDaemon.StartAsync(ct);

await martenAsyncCommandBus.Schedule(command, ct);

// Then
await eventListener.WaitForProcessing(command, ct);

var commands = await Session.Events.FetchStreamAsync(MartenAsyncCommandBus.CommandsStreamId, token: ct);
commands.Should().HaveCountGreaterThanOrEqualTo(1);
commands.Select(e => e.Data).OfType<AddUser>()
.Count(e => e.UserId == userId)
.Should().Be(1);

userIds.Should().Contain(userId);
}

public MartenAsyncCommandBusTests(): base(false)
public override async Task InitializeAsync()
{
await base.InitializeAsync();
var services = new ServiceCollection();

services
Expand All @@ -42,7 +61,7 @@ public MartenAsyncCommandBusTests(): base(false)
.AddCoreServices()
.AddMarten(new MartenConfig
{
ConnectionString = Settings.ConnectionString,
ConnectionString = ConnectionString,
WriteModelSchema = SchemaName,
ReadModelSchema = SchemaName
})
Expand All @@ -58,35 +77,21 @@ public MartenAsyncCommandBusTests(): base(false)
.AddCommandForwarder();

var serviceProvider = services.BuildServiceProvider();
Session = serviceProvider.GetRequiredService<IDocumentSession>();
var session = serviceProvider.GetRequiredService<IDocumentSession>();

asyncDaemon = (AsyncProjectionHostedService)serviceProvider.GetRequiredService<IHostedService>();

martenAsyncCommandBus = new MartenAsyncCommandBus(Session);
martenAsyncCommandBus = new MartenAsyncCommandBus(session);
}

[Fact]
public async Task CommandIsStoredInMartenAndForwardedToCommandHandler()
{
// Given
var userId = Guid.NewGuid();
var command = new AddUser(userId);

// When
await asyncDaemon.StartAsync(ct);

await martenAsyncCommandBus.Schedule(command, ct);

// Then
await eventListener.WaitForProcessing(command, ct);

var commands = await Session.Events.FetchStreamAsync(MartenAsyncCommandBus.CommandsStreamId, token: ct);
commands.Should().HaveCountGreaterThanOrEqualTo(1);
commands.Select(e => e.Data).OfType<AddUser>()
.Count(e => e.UserId == userId)
.Should().Be(1);
private MartenAsyncCommandBus martenAsyncCommandBus = default!;
private readonly List<Guid> userIds = new();
private readonly EventListener eventListener = new();
private AsyncProjectionHostedService asyncDaemon = default!;
private readonly CancellationToken ct = new CancellationTokenSource().Token;

userIds.Should().Contain(userId);
public MartenAsyncCommandBusTests(): base(true)
{
}
}

Expand Down
2 changes: 1 addition & 1 deletion Marten.Integration.Tests/CompositeIds/CompositeIdsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ protected override IDocumentSession CreateSession(Action<StoreOptions>? setStore
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.DatabaseSchemaName = SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ protected override IDocumentSession CreateSession(Action<StoreOptions>? setStore
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.DatabaseSchemaName = SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ protected override IDocumentSession CreateSession(Action<StoreOptions>? setStore
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.DatabaseSchemaName = SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public Task AfterCommitAsync(IDocumentSession session, IChangeSet commit, Cancel
}
}

public class DocumentChangesForwarding: MartenTest, IAsyncDisposable
public class DocumentChangesForwarding: MartenTest
{
[Fact]
public async Task GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberOfTransformedItems()
Expand All @@ -135,16 +135,18 @@ public async Task GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameN
cts.Token);
}

public DocumentChangesForwarding()
public override async Task InitializeAsync()
{
await base.InitializeAsync();

var services = new ServiceCollection();

services.AddLogging();

services.AddMarten(options =>
{
options.DatabaseSchemaName = SchemaName;
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.Projections.Add<ProjectInfoProjection>(ProjectionLifecycle.Async);
options.Projections.AsyncListeners.Add(
new AsyncListenerWrapper(
Expand All @@ -158,21 +160,28 @@ public DocumentChangesForwarding()
}).AddAsyncDaemon(DaemonMode.Solo)
.UseLightweightSessions();

using var sp = services.BuildServiceProvider();
await using var sp = services.BuildServiceProvider();
serviceScope = sp.CreateScope();
daemon = serviceScope.ServiceProvider.GetRequiredService<IHostedService>();
documentSession = serviceScope.ServiceProvider.GetRequiredService<IDocumentSession>();
}

private readonly IHostedService daemon;
private readonly IServiceScope serviceScope;
private readonly IDocumentSession documentSession;
private readonly EventListener eventListener = new();
private readonly MessagingSystemStub messagingSystemStub = new();
private IHostedService daemon = default!;
private IServiceScope serviceScope = default!;
private IDocumentSession documentSession = default!;
private EventListener eventListener = new();
private MessagingSystemStub messagingSystemStub = new();

public async ValueTask DisposeAsync()
public override async Task DisposeAsync()
{
await daemon.StopAsync(default);
serviceScope.Dispose();

await base.DisposeAsync();
}

public DocumentChangesForwarding(): base(false, false)
{

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public Task AfterCommitAsync(IDocumentSession session, IChangeSet commit, Cancel
}
}

public class EventTransformationsWithForwarding: MartenTest, IAsyncDisposable
public class EventTransformationsWithForwarding: MartenTest
{
[Fact(Skip = "That Doesn't work yet :(")]
public async Task GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberOfTransformedItems()
Expand Down Expand Up @@ -159,7 +159,7 @@ public EventTransformationsWithForwarding()
services.AddMarten(options =>
{
options.DatabaseSchemaName = SchemaName;
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.Projections.Add<ProjectInfoProjection>(ProjectionLifecycle.Async);
options.Projections.AsyncListeners.Add(
new AsyncListenerWrapper(
Expand All @@ -186,7 +186,7 @@ public EventTransformationsWithForwarding()
private readonly EventListener eventListener = new();
private readonly MessagingSystemStub messagingSystemStub = new();

public async ValueTask DisposeAsync()
public override async Task DisposeAsync()
{
await daemon.StopAsync(default);
serviceScope.Dispose();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected override IDocumentSession CreateSession(Action<StoreOptions>? setStore
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.UseDefaultSerialization(nonPublicMembersStorage: NonPublicMembersStorage.All);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.DatabaseSchemaName = SchemaName;
Expand Down
22 changes: 14 additions & 8 deletions Marten.Integration.Tests/General/StoreInitializationTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using FluentAssertions;
using Marten.Integration.Tests.TestsInfrastructure;
using Npgsql;
using Weasel.Core;
using Xunit;

namespace Marten.Integration.Tests.General;

public class StoreInitializationTests
public class StoreInitializationTests: MartenTest
{
[Fact]
public void GivenWrongConnectionString_WhenDocumentSessionIsInitialized_ThenConnectionIsCreated()
Expand All @@ -25,7 +26,7 @@ public void GivenProperConnectionString_WhenDocumentSessionIsInitialized_ThenCon
{
var ex = Record.Exception(() =>
{
var store = DocumentStore.For(Settings.ConnectionString);
var store = DocumentStore.For(ConnectionString);
ConnectionShouldBeEstablished(store);
});
Expand All @@ -40,9 +41,9 @@ public void GivenProperConnectionString_WhenDocumentSessionIsInitializedWithDiff
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.Events.DatabaseSchemaName = Settings.SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
});
ConnectionShouldBeEstablished(store);
Expand All @@ -58,9 +59,9 @@ public void GivenSettingWithNpgsqlConnection_WhenDocumentSessionIsInitializedWit
{
var store = DocumentStore.For(options =>
{
options.Connection(() => new NpgsqlConnection(Settings.ConnectionString));
options.Connection(() => new NpgsqlConnection(ConnectionString));
options.AutoCreateSchemaObjects = AutoCreate.All;
options.Events.DatabaseSchemaName = Settings.SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
});
ConnectionShouldBeEstablished(store);
Expand All @@ -76,9 +77,9 @@ public void GivenProperConnectionString_WhenDocumentSessionIsCreatedAndTransacti
{
var store = DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.Events.DatabaseSchemaName = Settings.SchemaName;
options.Events.DatabaseSchemaName = SchemaName;
});
using var session = store.LightweightSession();
Expand All @@ -98,4 +99,9 @@ private static void ConnectionShouldBeEstablished(IDocumentStore store)

result.Should().NotBeNull();
}

public StoreInitializationTests(): base(false, false)
{

}
}
1 change: 1 addition & 0 deletions Marten.Integration.Tests/Marten.Integration.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" />
<PackageReference Include="Testcontainers.PostgreSql" Version="3.3.0" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
Expand Down
13 changes: 0 additions & 13 deletions Marten.Integration.Tests/Settings.cs

This file was deleted.

12 changes: 9 additions & 3 deletions Marten.Integration.Tests/Tenancy/TenancyPerSchema.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using System.Data;
using Marten.Integration.Tests.TestsInfrastructure;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

Expand Down Expand Up @@ -72,11 +73,16 @@ public record TestDocumentForTenancy(
string Name
);

public class TenancyPerSchema
public class TenancyPerSchema: MartenTest
{
private const string FirstTenant = "Tenant1";
private const string SecondTenant = "Tenant2";

public TenancyPerSchema(): base(false)
{

}

[Fact]
public void GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberOfTransformedItems()
{
Expand Down Expand Up @@ -110,7 +116,7 @@ public void GivenEvents_WhenInlineTransformationIsApplied_ThenReturnsSameNumberO
}
}

private static void AddMarten(IServiceCollection services)
private void AddMarten(IServiceCollection services)
{
// simulate http context
services.AddScoped<DummyTenancyContext>();
Expand All @@ -121,7 +127,7 @@ private static void AddMarten(IServiceCollection services)
services.AddSingleton<Action<string, StoreOptions>>((tenantId, options) =>
{
options.DatabaseSchemaName = tenantId;
options.Connection(Settings.ConnectionString);
options.Connection(ConnectionString);
});

services.AddScoped<ISessionFactory, TenancyPerSchemaSessionFactory>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ namespace Marten.Integration.Tests.TestsInfrastructure;

public static class DocumentSessionProvider
{
public static IDocumentSession Get(string? schemaName = null, Action<StoreOptions>? setOptions = null)
public static IDocumentSession Get(string connectionString, string? schemaName = null, Action<StoreOptions>? setOptions = null)
{
var store = DocumentStoreProvider.Get(schemaName, setOptions);
var store = DocumentStoreProvider.Get(connectionString, schemaName, setOptions);

return store.LightweightSession();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ namespace Marten.Integration.Tests.TestsInfrastructure;

public static class DocumentStoreProvider
{
public static IDocumentStore Get(string? schemaName = null, Action<StoreOptions>? setOptions = null)
private const string SchemaName = "EventStore";

public static IDocumentStore Get(string connectionString, string? schemaName = null, Action<StoreOptions>? setOptions = null)
{
return DocumentStore.For(options =>
{
options.Connection(Settings.ConnectionString);
options.Connection(connectionString);
options.AutoCreateSchemaObjects = AutoCreate.All;
options.DatabaseSchemaName = schemaName ?? Settings.SchemaName;
options.Events.DatabaseSchemaName = schemaName ?? Settings.SchemaName;
options.DatabaseSchemaName = schemaName ?? SchemaName;
options.Events.DatabaseSchemaName = schemaName ?? SchemaName;
setOptions?.Invoke(options);
});
Expand Down
Loading

0 comments on commit 3ec0e0e

Please sign in to comment.