Cratis Chronicle append collection for integration tests
Cratis Chronicle’s IEventAppendCollection captures event-log append outcomes from the client under test, so you can assert on both the events your operation produces and their results. Use it with the .NET integration fixtures when a test needs a running kernel. It does not observe appends made by another client or process, even against the same event store.
How It Works
Section titled “How It Works”Call StartCollectingAppends() on the fixture before the operation you want to test. The collector subscribes to the event log’s AppendOperations notifications and keeps each event and its append result together as an AppendedEventWithResult. Direct calls to EventStore.EventLog.Append and EventStore.EventLog.AppendMany use this path. So do reactors that call ICommandPipeline.Execute(), because the command pipeline commits its unit of work through AppendMany on the same client.
The collection includes rejected appends as well as successful ones. An idempotent retry that returns an already-appended result does not emit a new append notification, so it does not add another entry.
For a direct Append, the entry is available when the awaited call returns. A reactor’s follow-up append can arrive later: use WaitForCount() before asserting on that event. Waiting for a count confirms that append outcomes arrived; it does not by itself confirm other observer work.
One-Time Test Project Setup
Section titled “One-Time Test Project Setup”Add the Cratis.Chronicle.XUnit.Integration package for IEventAppendCollection and ChronicleInProcessFixture. The in-process fixture runs the kernel in the test process and MongoDB through Testcontainers, so this setup needs a container runtime.
Define an xUnit collection to share the fixture among test classes marked with that collection. The project-local Specification base below binds Specification<TChronicleFixture> to ChronicleInProcessFixture, so each context can use the same base. Its AutoDiscoverArtifacts = false setting means the examples nominate their event types and reactors explicitly:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ // One-time test project setup: a collection definition sharing one ChronicleInProcessFixture // across test classes, and a project-local Specification convenience base. [CollectionDefinition(Name)] public class ChronicleCollection : ICollectionFixture<ChronicleInProcessFixture> { public const string Name = "Chronicle"; }
public class Specification(ChronicleInProcessFixture fixture) : Specification<ChronicleInProcessFixture>(fixture) { public override bool AutoDiscoverArtifacts => false; }
[EventType] public record ItemRegistered(string Name);
namespace given { public class an_event_append_collection_scope(ChronicleInProcessFixture fixture) : Specification(fixture) { public EventSourceId EventSourceId = null!; public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(ItemRegistered)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because() { AppendedEventsCollector = StartCollectingAppends(); await EventStore.EventLog.Append(EventSourceId, new ItemRegistered("Widget")); }
void Destroy() => AppendedEventsCollector?.Dispose(); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionScopeItemRegistered do use Cratis.Chronicle.Events.EventType, id: "testing-collection-scope-item-registered"
defstruct [:name]end
defmodule MyApp.TestingCollectionScopeTest do # `Cratis.Chronicle.Testing.Case` is the one-time per-test-module setup: every test # gets its own in-memory kernel and client (so there is no shared fixture to # bring up once), put in the context as `:chronicle`, and torn down # automatically. There is no separate collector to start or dispose — # `Cratis.Chronicle.Testing.appended_events/2` reads straight from the client's own # in-memory event log, scoped to that client alone. use Cratis.Chronicle.Testing.Case, event_types: [MyApp.Events.TestingCollectionScopeItemRegistered]
alias MyApp.Events.TestingCollectionScopeItemRegistered
test "appending is captured for this client only", %{chronicle: client} do event_source_id = "item-#{System.unique_integer([:positive])}"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( event_source_id, %TestingCollectionScopeItemRegistered{name: "Widget"}, client: client )
assert [%TestingCollectionScopeItemRegistered{name: "Widget"}] = client |> Cratis.Chronicle.Testing.appended_events(event_source_id) |> Enum.map(& &1.event) endendTypeScript does not support this workflow yet.The ChronicleCollection.Name used by the later test classes refers to this collection definition. Keep the definition and convenience base in your test project; the remaining examples build on them.
Scope Lifetime
Section titled “Scope Lifetime”Start collecting in Because(), immediately before the operation under test. That keeps setup events out of the assertions. Store the collector on the given context so the facts can inspect it, then dispose it in Destroy():
namespace Cratis.Chronicle.Docs.EventAppendCollection{ // One-time test project setup: a collection definition sharing one ChronicleInProcessFixture // across test classes, and a project-local Specification convenience base. [CollectionDefinition(Name)] public class ChronicleCollection : ICollectionFixture<ChronicleInProcessFixture> { public const string Name = "Chronicle"; }
public class Specification(ChronicleInProcessFixture fixture) : Specification<ChronicleInProcessFixture>(fixture) { public override bool AutoDiscoverArtifacts => false; }
[EventType] public record ItemRegistered(string Name);
namespace given { public class an_event_append_collection_scope(ChronicleInProcessFixture fixture) : Specification(fixture) { public EventSourceId EventSourceId = null!; public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(ItemRegistered)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because() { AppendedEventsCollector = StartCollectingAppends(); await EventStore.EventLog.Append(EventSourceId, new ItemRegistered("Widget")); }
void Destroy() => AppendedEventsCollector?.Dispose(); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionScopeItemRegistered do use Cratis.Chronicle.Events.EventType, id: "testing-collection-scope-item-registered"
defstruct [:name]end
defmodule MyApp.TestingCollectionScopeTest do # `Cratis.Chronicle.Testing.Case` is the one-time per-test-module setup: every test # gets its own in-memory kernel and client (so there is no shared fixture to # bring up once), put in the context as `:chronicle`, and torn down # automatically. There is no separate collector to start or dispose — # `Cratis.Chronicle.Testing.appended_events/2` reads straight from the client's own # in-memory event log, scoped to that client alone. use Cratis.Chronicle.Testing.Case, event_types: [MyApp.Events.TestingCollectionScopeItemRegistered]
alias MyApp.Events.TestingCollectionScopeItemRegistered
test "appending is captured for this client only", %{chronicle: client} do event_source_id = "item-#{System.unique_integer([:positive])}"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( event_source_id, %TestingCollectionScopeItemRegistered{name: "Widget"}, client: client )
assert [%TestingCollectionScopeItemRegistered{name: "Widget"}] = client |> Cratis.Chronicle.Testing.appended_events(event_source_id) |> Enum.map(& &1.event) endendTypeScript does not support this workflow yet.Disposal unsubscribes the collector, so later appends no longer accumulate in it. While a scope is active, it captures notifications from the subscribed event log, not only events for one event source. Filter by event type or context when other activity on that client could be present.
AppendedEventWithResult Members
Section titled “AppendedEventWithResult Members”Each entry in All pairs the event passed to the append with the operation’s outcome. Check Result before treating the event as successfully stored:
| Member | Type | Description |
|---|---|---|
Event |
AppendedEvent |
The event submitted for append, including its context and content |
Event.Content |
object |
The event object supplied to the append (cast to your event type for assertions) |
Event.Context |
EventContext |
Metadata: event source, sequence number, correlation ID, causation chain, etc. |
Event.Context.EventSourceId |
EventSourceId |
The event source the event was appended for |
Event.Context.SequenceNumber |
EventSequenceNumber |
Assigned position, or unavailable for a failed append |
Event.Context.CorrelationId |
CorrelationId |
The append’s correlation ID |
Event.Context.Causation |
IEnumerable<Causation> |
The causation chain active at the time of the append |
Result |
AppendResult |
The outcome of the append operation |
Result.IsSuccess |
bool |
true when there are no constraint violations, concurrency violations, or errors |
Result.SequenceNumber |
EventSequenceNumber |
Assigned sequence number; EventSequenceNumber.Unavailable when the append failed |
Result.HasConstraintViolations |
bool |
true when at least one constraint violation was returned |
Result.HasConcurrencyViolations |
bool |
true when at least one concurrency violation was returned |
Result.HasErrors |
bool |
true when at least one error was returned |
Result.ConstraintViolations |
IEnumerable<ConstraintViolation> |
Constraint violations, if any |
Result.ConcurrencyViolation |
ConcurrencyViolation? |
Concurrency violation, if any |
Result.Errors |
IEnumerable<AppendError> |
Errors, if any |
Asserting on Collected Events
Section titled “Asserting on Collected Events”IEventAppendCollection exposes three members:
| Member | Description |
|---|---|
All |
A snapshot of every AppendedEventWithResult captured so far |
Last |
The most recently captured AppendedEventWithResult; throws when nothing has been collected |
WaitForCount(count, timeout?) |
Waits asynchronously until at least count events have been collected |
Single event
Section titled “Single event”The setup context appends ItemRegistered after starting the collector. A spec derived from Given<TSetup> can inspect it through Context. These facts check that one entry arrived with the expected event type and a successful result:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [Collection(ChronicleCollection.Name)] public class and_collecting_the_registered_item(given.an_event_append_collection_scope context) : Given<given.an_event_append_collection_scope>(context) { [Fact] void should_collect_one_event() => Context.AppendedEventsCollector.All.Count.ShouldEqual(1); [Fact] void should_have_appended_the_event() => Context.AppendedEventsCollector.All[0].Event.Content.ShouldBeOfExactType<ItemRegistered>(); [Fact] void should_be_successful() => Context.AppendedEventsCollector.All[0].Result.IsSuccess.ShouldBeTrue(); [Fact] void should_have_a_valid_sequence_number() => Context.AppendedEventsCollector.All[0].Result.SequenceNumber.IsActualValue.ShouldBeTrue(); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionSingleItemRegistered do use Cratis.Chronicle.Events.EventType, id: "testing-collection-single-item-registered"
defstruct [:name]end
defmodule MyApp.TestingCollectionSingleEventTest do use Cratis.Chronicle.Testing.Case, event_types: [MyApp.Events.TestingCollectionSingleItemRegistered]
alias MyApp.Events.TestingCollectionSingleItemRegistered
test "exactly one event is captured", %{chronicle: client} do event_source_id = "item-#{System.unique_integer([:positive])}"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( event_source_id, %TestingCollectionSingleItemRegistered{name: "Widget"}, client: client )
captured = Cratis.Chronicle.Testing.appended_events(client, event_source_id)
assert [%{event: %TestingCollectionSingleItemRegistered{}, context: context}] = captured assert context.sequence_number != nil endendTypeScript does not support this workflow yet.Multiple events
Section titled “Multiple events”When an operation produces several events, select the one your assertion concerns. This example finds SecondItemAdded by type and checks its name instead of relying on its position in the collection:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [EventType] public record FirstItemAdded(string Name);
[EventType] public record SecondItemAdded(string Name);
namespace given { public class a_multiple_events_scope(ChronicleInProcessFixture fixture) : Specification(fixture) { public EventSourceId EventSourceId = null!; public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(FirstItemAdded), typeof(SecondItemAdded)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because() { AppendedEventsCollector = StartCollectingAppends(); await EventStore.EventLog.Append(EventSourceId, new FirstItemAdded("Widget")); await EventStore.EventLog.Append(EventSourceId, new SecondItemAdded("Gadget")); }
void Destroy() => AppendedEventsCollector?.Dispose(); } }
[Collection(ChronicleCollection.Name)] public class and_locating_the_second_event(given.a_multiple_events_scope context) : Given<given.a_multiple_events_scope>(context) { AppendedEventWithResult SecondEvent => Context.AppendedEventsCollector.All.First(e => e.Event.Content is SecondItemAdded);
[Fact] void should_locate_the_second_event() => SecondEvent.Event.Content.ShouldBeOfExactType<SecondItemAdded>(); [Fact] void should_carry_the_correct_name() => ((SecondItemAdded)SecondEvent.Event.Content).Name.ShouldEqual("Gadget"); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionFirstItemAdded do use Cratis.Chronicle.Events.EventType, id: "testing-collection-first-item-added"
defstruct [:name]end
defmodule MyApp.Events.TestingCollectionSecondItemAdded do use Cratis.Chronicle.Events.EventType, id: "testing-collection-second-item-added"
defstruct [:name]end
defmodule MyApp.TestingCollectionMultipleEventsTest do use Cratis.Chronicle.Testing.Case, event_types: [ MyApp.Events.TestingCollectionFirstItemAdded, MyApp.Events.TestingCollectionSecondItemAdded ]
alias MyApp.Events.{TestingCollectionFirstItemAdded, TestingCollectionSecondItemAdded}
test "locating the second of several captured events", %{chronicle: client} do event_source_id = "item-#{System.unique_integer([:positive])}"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( event_source_id, %TestingCollectionFirstItemAdded{name: "Widget"}, client: client )
:ok = Cratis.Chronicle.EventSequences.EventLog.append( event_source_id, %TestingCollectionSecondItemAdded{name: "Gadget"}, client: client )
second_event = client |> Cratis.Chronicle.Testing.appended_events(event_source_id) |> Enum.map(& &1.event) |> Enum.find(&match?(%TestingCollectionSecondItemAdded{}, &1))
assert %TestingCollectionSecondItemAdded{name: "Gadget"} = second_event endendTypeScript does not support this workflow yet.Waiting for Asynchronous Appends
Section titled “Waiting for Asynchronous Appends”To prove that placing an order schedules a shipment, collect both the original OrderPlaced event and the reactor’s ShipmentScheduled follow-up. The test waits for the reactor to become active before appending the order, then waits for two collected entries before asserting on the shipment.
The reactor appends a shipment event for the same event source as the order:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [EventType] public record OrderPlaced(string OrderId);
[EventType] public record ShipmentScheduled(string OrderId);
public class ShipmentReactor(IEventLog eventLog) : IReactor { public Task OnOrderPlaced(OrderPlaced evt, EventContext ctx) => eventLog.Append(ctx.EventSourceId, new ShipmentScheduled(evt.OrderId)); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionOrderPlaced do use Cratis.Chronicle.Events.EventType, id: "testing-collection-order-placed"
defstruct [:order_id]end
defmodule MyApp.Events.TestingCollectionShipmentScheduled do use Cratis.Chronicle.Events.EventType, id: "testing-collection-shipment-scheduled"
defstruct [:order_id]end
defmodule MyApp.Reactors.TestingCollectionShipmentReactor do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.{TestingCollectionOrderPlaced, TestingCollectionShipmentScheduled}
@handles TestingCollectionOrderPlaced
# A bare event in the returned side effect uses the triggering event's own # event source id. @impl true def handle(%TestingCollectionOrderPlaced{} = event, _context), do: {:ok, %TestingCollectionShipmentScheduled{order_id: event.order_id}}endTypeScript does not support this workflow yet.The context nominates both event types and the reactor, then registers the reactor’s service:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ namespace given { public class a_shipment_reactor_context(ChronicleInProcessFixture fixture) : Specification(fixture) { public EventSourceId EventSourceId = null!; public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(OrderPlaced), typeof(ShipmentScheduled)]; public override IEnumerable<Type> Reactors => [typeof(ShipmentReactor)];
protected override void ConfigureServices(IServiceCollection services) => services.AddSingleton<ShipmentReactor>();
void Establish() => EventSourceId = EventSourceId.New();
void Destroy() => AppendedEventsCollector?.Dispose(); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.TestingCollectionShipmentContextTest do # The shared per-test-module setup: the client starts with the reactor # registered, so every test in the module gets it running synchronously # against the in-memory kernel. `Cratis.Chronicle.Testing.wait_for_observers/1` is # the deterministic replacement for `WaitForCount`/`WaitTillActive` — see the # spec in the next tab. use Cratis.Chronicle.Testing.Case, event_types: [ MyApp.Events.TestingCollectionOrderPlaced, MyApp.Events.TestingCollectionShipmentScheduled ], reactors: [MyApp.Reactors.TestingCollectionShipmentReactor]endTypeScript does not support this workflow yet.The spec starts collecting only after the reactor is active:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [Collection(ChronicleCollection.Name)] public class and_collecting_the_scheduled_shipment(and_collecting_the_scheduled_shipment.context context) : Given<and_collecting_the_scheduled_shipment.context>(context) {#pragma warning disable CS8981 // "context" is a conventional, lowercase BDD nested-class name public class context(ChronicleInProcessFixture fixture) : given.a_shipment_reactor_context(fixture) { async Task Because() { var reactor = EventStore.Reactors.GetHandlerFor<ShipmentReactor>(); await reactor.WaitTillActive();
AppendedEventsCollector = StartCollectingAppends(); await EventStore.EventLog.Append(EventSourceId, new OrderPlaced("order-123"));
// Wait for the reactor's follow-up append to arrive await AppendedEventsCollector.WaitForCount(2); } }#pragma warning restore CS8981
AppendedEventWithResult Shipment => Context.AppendedEventsCollector.All .First(e => e.Event.Content is ShipmentScheduled);
[Fact] void should_schedule_a_shipment() => Shipment.Event.Content.ShouldBeOfExactType<ShipmentScheduled>(); [Fact] void should_carry_the_order_id() => ((ShipmentScheduled)Shipment.Event.Content).OrderId.ShouldEqual("order-123"); [Fact] void should_be_successful() => Shipment.Result.IsSuccess.ShouldBeTrue(); [Fact] void should_have_a_valid_sequence_number() => Shipment.Result.SequenceNumber.IsActualValue.ShouldBeTrue(); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.TestingCollectionShipmentSpecTest do use Cratis.Chronicle.Testing.Case, event_types: [ MyApp.Events.TestingCollectionOrderPlaced, MyApp.Events.TestingCollectionShipmentScheduled ], reactors: [MyApp.Reactors.TestingCollectionShipmentReactor]
alias MyApp.Events.{TestingCollectionOrderPlaced, TestingCollectionShipmentScheduled}
test "a reactor's follow-up append is captured once observers have settled", %{chronicle: client} do order_id = "order-#{System.unique_integer([:positive])}"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( order_id, %TestingCollectionOrderPlaced{order_id: order_id}, client: client )
# Wait for the reactor's follow-up append to arrive — deterministic, no sleeps. :ok = Cratis.Chronicle.Testing.wait_for_observers(client)
shipment = client |> Cratis.Chronicle.Testing.appended_events(order_id) |> Enum.map(& &1.event) |> Enum.find(&match?(%TestingCollectionShipmentScheduled{}, &1))
assert %TestingCollectionShipmentScheduled{order_id: ^order_id} = shipment endendTypeScript does not support this workflow yet.WaitForCount accepts an optional TimeSpan timeout (default: 5 seconds) and throws
TimeoutException if the expected count is not reached in time. WaitTillActive() ensures the
reactor is registered and listening on the server before the test appends the triggering event.
The 5-second default also applies to the WaitTillActive helpers. Set the CHRONICLE_TEST_TIMEOUT_SECONDS environment variable to a positive number of seconds to change it, for example on slow CI machines. While a debugger is attached the default wait is infinite.
Checking Violations
Section titled “Checking Violations”A collected event does not necessarily mean an event was stored. When a reactor’s direct append is rejected by a constraint, the collector records the violation in AppendedEventWithResult.Result. The append returns that result instead of throwing.
Here, UniqueValueReactor directly appends UniqueValueFollowUp without ICommandPipeline. A constraint requires the follow-up’s value to be unique:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [EventType] public record UniqueValueRecorded(string UniqueValue);
[EventType] public record UniqueValueFollowUp(string UniqueValue);
public class UniqueValueFollowUpConstraint : IConstraint { public void Define(IConstraintBuilder builder) => builder.Unique(b => b.On<UniqueValueFollowUp>(e => e.UniqueValue)); }
public class UniqueValueReactor(IEventLog eventLog) : IReactor { public Task OnUniqueValueRecorded(UniqueValueRecorded evt, EventContext ctx) => eventLog.Append(ctx.EventSourceId, new UniqueValueFollowUp(evt.UniqueValue)); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestingCollectionUniqueValueRecorded do use Cratis.Chronicle.Events.EventType, id: "testing-collection-unique-value-recorded"
defstruct [:unique_value]end
defmodule MyApp.Events.TestingCollectionUniqueValueFollowUp do use Cratis.Chronicle.Events.EventType, id: "testing-collection-unique-value-follow-up"
unique(:unique_value, name: "TestingCollectionUniqueValueFollowUp")
defstruct [:unique_value]end
defmodule MyApp.Reactors.TestingCollectionUniqueValueReactor do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.{TestingCollectionUniqueValueFollowUp, TestingCollectionUniqueValueRecorded}
@handles TestingCollectionUniqueValueRecorded
@impl true def handle(%TestingCollectionUniqueValueRecorded{} = event, _context), do: {:ok, %TestingCollectionUniqueValueFollowUp{unique_value: event.unique_value}}endTypeScript does not support this workflow yet.The shared given context:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ namespace given { public class a_unique_value_reactor_context(ChronicleInProcessFixture fixture) : Specification(fixture) { public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(UniqueValueRecorded), typeof(UniqueValueFollowUp)]; public override IEnumerable<Type> ConstraintTypes => [typeof(UniqueValueFollowUpConstraint)]; public override IEnumerable<Type> Reactors => [typeof(UniqueValueReactor)];
protected override void ConfigureServices(IServiceCollection services) => services.AddSingleton<UniqueValueReactor>();
void Destroy() => AppendedEventsCollector?.Dispose(); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.TestingCollectionViolationContextTest do # Shared setup: the reactor is registered, so a duplicate unique value on its # follow-up append is rejected by the constraint instead of throwing — the # violation shows up on the captured event's result (see the spec). use Cratis.Chronicle.Testing.Case, event_types: [ MyApp.Events.TestingCollectionUniqueValueRecorded, MyApp.Events.TestingCollectionUniqueValueFollowUp ], reactors: [MyApp.Reactors.TestingCollectionUniqueValueReactor]endTypeScript does not support this workflow yet.The spec appends the same unique value from two event sources. It waits for four entries: two input appends and two follow-up attempts. One follow-up succeeds; the duplicate violates the constraint. The assertion selects the rejected result, where HasConstraintViolations is true and IsSuccess is false, and checks which event was refused:
namespace Cratis.Chronicle.Docs.EventAppendCollection{ [Collection(ChronicleCollection.Name)] public class and_a_reactor_directly_appends_a_duplicate_unique_value(and_a_reactor_directly_appends_a_duplicate_unique_value.context context) : Given<and_a_reactor_directly_appends_a_duplicate_unique_value.context>(context) {#pragma warning disable CS8981 // "context" is a conventional, lowercase BDD nested-class name public class context(ChronicleInProcessFixture fixture) : given.a_unique_value_reactor_context(fixture) { public string UniqueValue = null!;
async Task Because() { var reactor = EventStore.Reactors.GetHandlerFor<UniqueValueReactor>(); await reactor.WaitTillActive();
UniqueValue = Guid.NewGuid().ToString(); var firstEventSourceId = EventSourceId.New(); var secondEventSourceId = EventSourceId.New();
AppendedEventsCollector = StartCollectingAppends(); await EventStore.EventLog.Append(firstEventSourceId, new UniqueValueRecorded(UniqueValue)); await EventStore.EventLog.Append(secondEventSourceId, new UniqueValueRecorded(UniqueValue)); await AppendedEventsCollector.WaitForCount(4); } }#pragma warning restore CS8981
AppendedEventWithResult ViolatingAppend => Context.AppendedEventsCollector.All .First(e => e.Result.HasConstraintViolations);
[Fact] void should_have_a_constraint_violation() => ViolatingAppend.Result.HasConstraintViolations.ShouldBeTrue(); [Fact] void should_not_be_successful() => ViolatingAppend.Result.IsSuccess.ShouldBeFalse(); [Fact] void should_have_attempted_the_follow_up_event() => ViolatingAppend.Event.Content.ShouldBeOfExactType<UniqueValueFollowUp>(); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.TestingCollectionViolationSpecTest do use Cratis.Chronicle.Testing.Case, event_types: [ MyApp.Events.TestingCollectionUniqueValueRecorded, MyApp.Events.TestingCollectionUniqueValueFollowUp ], reactors: [MyApp.Reactors.TestingCollectionUniqueValueReactor]
alias MyApp.Events.{TestingCollectionUniqueValueFollowUp, TestingCollectionUniqueValueRecorded}
test "a reactor's duplicate follow-up append is rejected by the constraint", %{chronicle: client} do unique_value = "value-#{System.unique_integer([:positive])}" first_event_source_id = "value-#{System.unique_integer([:positive])}-a" second_event_source_id = "value-#{System.unique_integer([:positive])}-b"
:ok = Cratis.Chronicle.EventSequences.EventLog.append( first_event_source_id, %TestingCollectionUniqueValueRecorded{unique_value: unique_value}, client: client )
:ok = Cratis.Chronicle.EventSequences.EventLog.append( second_event_source_id, %TestingCollectionUniqueValueRecorded{unique_value: unique_value}, client: client )
# An append the kernel rejects is never committed, so it is never in # `appended_events/2` — the rejection surfaces through `wait_for_observers/1` # instead, as a reactor failure. assert {:error, [{:reactor, MyApp.Reactors.TestingCollectionUniqueValueReactor, reason}]} = Cratis.Chronicle.Testing.wait_for_observers(client)
assert {:constraint_violations, _violations} = reason
assert [%TestingCollectionUniqueValueFollowUp{unique_value: ^unique_value}] = first_event_source_id |> then(&Cratis.Chronicle.Testing.appended_events(client, &1)) |> Enum.map(& &1.event) |> Enum.filter(&match?(%TestingCollectionUniqueValueFollowUp{}, &1))
assert second_event_source_id |> then(&Cratis.Chronicle.Testing.appended_events(client, &1)) |> Enum.map(& &1.event) |> Enum.filter(&match?(%TestingCollectionUniqueValueFollowUp{}, &1)) == [] endendTypeScript does not support this workflow yet.Full Example
Section titled “Full Example”Use the shipment example with the test project setup to check a reactor against the running kernel. If you only need to specify the reactor’s handling logic, use ReactorScenario to test that behavior in process without containers.