Skip to content

Functional tests of Command execution and projections #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<ItemGroup Label="Code Analyzers">
<PackageReference Include="SecurityCodeScan.VS2019" Version="5.6.7" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.321" PrivateAssets="All" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.0.0.68202" PrivateAssets="all" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.7.0.110445" PrivateAssets="all" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ public ProjectionFilter(string filter)
? CreateEvaluateAll()
: CreateEvaluation(p))
.ToArray();
endsOnAcceptAll = filter
.Split(
new[] { EventStreamId.PartSeperator },
StringSplitOptions.RemoveEmptyEntries)
.Last() == "**";
endsOnAcceptAll = filter.EndsWith("**");
}

public bool Evaluate(StreamId streamId)
Expand Down
5 changes: 3 additions & 2 deletions src/Atc.Cosmos.EventStore/InMemory/InMemoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ public Task WriteAsync(
.GetOrAdd(streamId, new ConcurrentDictionary<string, CheckpointDocument>())
.AddOrUpdate(
name,
key => new CheckpointDocument(name, streamId, streamVersion, dateTimeProvider.GetDateTime(), state),
(key, doc) => new CheckpointDocument(name, streamId, streamVersion, dateTimeProvider.GetDateTime(), state));
static (key, arg) => new CheckpointDocument(key, arg.streamId, arg.streamVersion, arg.currentTime, arg.state),
static (key, doc, arg) => new CheckpointDocument(key, arg.streamId, arg.streamVersion, arg.currentTime, arg),
(streamId, streamVersion, state, currentTime: dateTimeProvider.GetDateTime()));

return Task.CompletedTask;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<IsPackable>false</IsPackable>

</PropertyGroup>

<ItemGroup>
<PackageReference Include="Atc.Test" Version="1.1.4" />
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
Expand All @@ -18,6 +20,9 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

<!-- Get the shared Microsoft.AspNetCore.App framework instead of referencing a bunch of MS.Ext.Hosting etc packages -->
<FrameworkReference Include="Microsoft.AspNetCore.App"/>
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace Atc.Cosmos.EventStore.Cqrs.Tests.Functional;

#nullable enable

[Trait("Category", "Functional")]
public class CommandHandlerTests : IAsyncLifetime
{
private CqrsTestHost host = null!;

[Fact]
public async Task Result_from_CommandHandler_must_be_returned()
{
var tick = DateTime.UtcNow.Ticks;
var commandResult = await host.Services.GetRequiredService<ICommandProcessorFactory>()
.Create<MakeTimeTickCommand>()
.ExecuteAsync(new MakeTimeTickCommand(tick), CancellationToken.None);

Assert.NotNull(commandResult);
Assert.NotNull(commandResult.Response);
Assert.Equal(tick, commandResult.Response);
}

[Fact]
public async Task CommandHandler_can_consume_existing_events()
{
// Produce some events by making time tick
await MakeTimeTick(host);
await MakeTimeTick(host);
await MakeTimeTick(host);

// Query events
var result = await host.Services.GetRequiredService<ICommandProcessorFactory>()
.Create<QueryTimeTickCommand>()
.ExecuteAsync(new QueryTimeTickCommand(), CancellationToken.None);

var events = Assert.IsType<List<(TimeTickedEvent Evt, EventMetadata Metadata)>>(result.Response);
Assert.Equal(3, events.Count);

static async Task MakeTimeTick(CqrsTestHost host)
{
var tick = DateTime.UtcNow.Ticks;
var commandProcessorFactory = host.Services.GetRequiredService<ICommandProcessorFactory>();
_ = await commandProcessorFactory
.Create<MakeTimeTickCommand>()
.ExecuteAsync(new MakeTimeTickCommand(tick), CancellationToken.None);
}
}

[Fact]
public async Task CommandHandler_that_consumes_events_works_when_no_existing_events_are_present()
{
// Query events - none exists
var result = await host.Services.GetRequiredService<ICommandProcessorFactory>()
.Create<QueryTimeTickCommand>()
.ExecuteAsync(new QueryTimeTickCommand(), CancellationToken.None);

var events = Assert.IsType<List<(TimeTickedEvent Evt, EventMetadata Metadata)>>(result.Response);
Assert.Empty(events);
}

[Fact]
public async Task Command_that_uses_RequiredVersion_Exists_must_result_in_NotFound_when_no_existing_events_are_present()
{
// Query events - must fail as non exists
var result = await host.Services.GetRequiredService<ICommandProcessorFactory>()
.Create<QueryExistingTimeTickCommand>()
.ExecuteAsync(new QueryExistingTimeTickCommand(), CancellationToken.None);

Assert.Equal(ResultType.NotFound, result.Result);
}

public async Task InitializeAsync()
{
host = new CqrsTestHost();
await host.StartAsync();
}

public async Task DisposeAsync()
{
await host.DisposeAsync();
}
}
73 changes: 73 additions & 0 deletions test/Atc.Cosmos.EventStore.Cqrs.Tests/Functional/CqrsTestHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Atc.Cosmos.EventStore.Streams;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Atc.Cosmos.EventStore.Cqrs.Tests.Functional;

#nullable enable

public class CqrsTestHost : IAsyncDisposable
{
private readonly WebApplication host;

public CqrsTestHost()
{
host = CreateHostBuilder().Build();
}

public IServiceProvider Services => host.Services;

public async Task StartAsync()
{
await host.StartAsync();
}

public async Task StopAsync()
{
await host.StopAsync();
}

public async ValueTask DisposeAsync()
{
await host.StopAsync();
await host.DisposeAsync();
}

private static WebApplicationBuilder CreateHostBuilder()
{
// Build a host with Atc EventStore
var webApplicationBuilder = WebApplication.CreateEmptyBuilder(new WebApplicationOptions()
{
ApplicationName = "Atc.Cosmos.EventStore.Cqrs.Tests",
});

webApplicationBuilder.WebHost.UseTestServer();

// Configure EventStore
webApplicationBuilder.Services.AddEventStore(eventStoreBuilder =>
{
eventStoreBuilder.UseEvents(c => c.FromAssembly<CqrsTestHost>());
eventStoreBuilder.UseCQRS(c =>
{
c.AddCommandsFromAssembly<CqrsTestHost>();
c.AddProjectionJob<TimeProjection>("TimeProjection");
});
});

// Use InMemoryEventStoreClient which actually works
webApplicationBuilder.Services.Replace(
ServiceDescriptor.Singleton<IEventStoreClient, InMemoryEventStoreClient>());

// Remove unused registrations
webApplicationBuilder.Services.RemoveAll<IStreamInfoReader>();
webApplicationBuilder.Services.RemoveAll<IStreamMetadataReader>();
webApplicationBuilder.Services.RemoveAll<IStreamReader>();
webApplicationBuilder.Services.RemoveAll<IStreamWriter>();

webApplicationBuilder.Services.AddSingleton<FakeDatabase>();

return webApplicationBuilder;
}
}
18 changes: 18 additions & 0 deletions test/Atc.Cosmos.EventStore.Cqrs.Tests/Functional/FakeDatabase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#nullable enable
namespace Atc.Cosmos.EventStore.Cqrs.Tests.Functional;

internal class FakeDatabase
{
private readonly Dictionary<string, object> storage = new();

public void Save(string key, object value)
{
storage[key] = value;
}

public object? Load(string key)
{
storage.TryGetValue(key, out var value);
return value;
}
}
Loading
Loading