Skip to content

Cratis Chronicle EventScenario: test event appends

Cratis Chronicle’s .NET EventScenario tests code that appends to IEventLog or IEventSequence without a server, database, or network. It runs the kernel’s append path against in-memory storage, so you can check event content and constraint outcomes before writing an integration test.

In a Cratis Specification, seed history with EventScenario.Given, append the events under test with EventScenario.When, then assert on the returned AppendResult or the event sequence. Call EventLog.Append or EventSequence.Append directly when you need other overload parameters.

The API names and kernel-backed behavior below describe .NET. Client tabs show alternatives where supported; other clients do not necessarily run the same kernel code.

Use EventScenario when the question is what your code appends or how it handles a rejected append. You can seed the history that makes a constraint relevant, attempt the next event, and inspect the outcome in one isolated spec. Use the integration fixtures when the question depends on a kernel connection, observer delivery, or persistent storage.

For a .NET spec, add Cratis.Chronicle.Testing and the Specifications test runner package to your test project:

Terminal window
dotnet add package Cratis.Specifications.XUnit
dotnet add package Cratis.Chronicle.Testing
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
public record TestingScenarioAuthorRegistered(string Name);
[EventType]
public record TestingScenarioBookAdded(string Title);
public static class TestingScenarioBasic
{
public static async Task Run()
{
var scenario = new EventScenario();
var result = await scenario.EventLog.Append(EventSourceId.New(), new TestingScenarioAuthorRegistered("John Doe"));
result.ShouldBeSuccessful();
}
}

View C# snippet source on GitHub

EventLog and EventSequence expose the same selected sequence and share its in-memory storage. The default scenario uses EventSequenceId.Log. Pass EventLog to code that expects an event log, or EventSequence when it expects the generic IEventSequence interface.

Use Given for events that happened before the operation under test. The builder appends them in order, giving your code a known history to work from:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Testing.EventSequences;
public static class TestingScenarioGiven
{
public static async Task Run()
{
var authorId = EventSourceId.New();
var scenario = new EventScenario();
await scenario.Given
.ForEventSource(authorId)
.Events(new TestingScenarioAuthorRegistered("John Doe"), new TestingScenarioBookAdded("Clean Code"));
var result = await scenario.EventLog.Append(authorId, new TestingScenarioBookAdded("The Pragmatic Programmer"));
result.ShouldBeSuccessful();
}
}

View C# snippet source on GitHub

Chain multiple ForEventSource calls to seed events for different event sources in the same scenario:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Testing.EventSequences;
public static class TestingScenarioGivenMultipleSources
{
public static async Task Run()
{
var author1Id = EventSourceId.New();
var author2Id = EventSourceId.New();
var scenario = new EventScenario();
await scenario.Given
.ForEventSource(author1Id)
.Events(new TestingScenarioAuthorRegistered("Jane Smith"));
await scenario.Given
.ForEventSource(author2Id)
.Events(new TestingScenarioAuthorRegistered("John Doe"));
}
}

View C# snippet source on GitHub

Seeded events receive increasing sequence numbers and pass through the append path, including constraint checks. If a seed is rejected, Given throws GivenEventAppendFailed so the spec cannot continue with incomplete setup. Keep the operation you want to test out of Given; its result belongs in the act phase.

Use When to attempt the append you want to assert on. It uses the same in-memory append path as Given, but returns an AppendResult for your assertions instead of treating rejection as a setup failure:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
public record TestingScenarioWhenAuthorRegistered([property: Unique(name: "TestingScenarioUniqueAuthorName")] string Name);
public static class TestingScenarioWhen
{
public static async Task Run()
{
var existingAuthorId = EventSourceId.New();
var newAuthorId = EventSourceId.New();
var scenario = new EventScenario();
// Given: an author with this name is already registered
await scenario.Given
.ForEventSource(existingAuthorId)
.Events(new TestingScenarioWhenAuthorRegistered("John Doe"));
// When: attempt to register the same name under a new event source — When returns the AppendResult
var result = await scenario.When
.ForEventSource(newAuthorId)
.Events(new TestingScenarioWhenAuthorRegistered("John Doe"));
// Then: assert on the returned result
result.ShouldHaveConstraintViolation("TestingScenarioUniqueAuthorName");
}
}

View C# snippet source on GitHub

Use the append assertions to check that result. If you supply several events to one When, the builder appends them in order and stops at the first failure, returning that failed result without attempting the remaining events. If all succeed, it returns the final append’s result. This is a series of individual appends, not an atomic batch.

Read the state produced by your events through scenario.ReadModels. It builds projection and reducer results from the same storage used by Given, When, and direct EventLog appends, including events needed for child collections and joins. Defaults.Instance.EventStore.ReadModels belongs to a different store, so it cannot read this scenario’s history.

For example, suppose your discovered ProjectSummary projects ProjectOpened and ProjectRenamed. In an existing specification with an EventScenario scenario and an EventSourceId projectId:

  1. Seed the project with await scenario.Given.ForEventSource(projectId).Events(new ProjectOpened("Original"));.
  2. Act with await scenario.When.ForEventSource(projectId).Events(new ProjectRenamed("Renamed"));.
  3. Read its current state with var project = await scenario.ReadModels.GetInstanceById<ProjectSummary>(projectId.Value);. The projected name is now Renamed. Use await scenario.ReadModels.GetInstances<ProjectSummary>() to read the collection instead.

A model-bound parent with a [ChildrenFrom<T>] collection works the same way. Seed the parent and append each child to its own event source, supplying the parent identifier in the child event’s configured parentKey property. Reading the parent returns both children with their distinct keys.

To observe the collection, import System.Reactive.Linq and subscribe, for example with using var subscription = scenario.ReadModels.Observe<ProjectSummary>().Subscribe(projects => Console.WriteLine(projects.Count()));. The subscription receives the initial collection and receives it again after a successful append changes the result. Await an emission signal in a specification rather than sleeping before an assertion. Passive read models and event-target projections cannot be observed.

These reads use the in-process projection and reducer processors, not a running observer or a production read-model sink. They do not cover production sink encryption or observer lifecycle. Use ReadModelScenario to specify a read model’s transformations directly.

AppendMany appends a collection of events in one call and returns an AppendManyResult:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
public record TestingScenarioItemAddedToCart(string ItemId);
[EventType]
public record TestingScenarioItemQuantityAdjusted(string ItemId, int Quantity);
public static class TestingScenarioAppendMany
{
public static async Task Run()
{
var cartId = EventSourceId.New();
var itemId1 = "item-1";
var itemId2 = "item-2";
var scenario = new EventScenario();
var result = await scenario.EventLog.AppendMany(cartId, [
new TestingScenarioItemAddedToCart(itemId1),
new TestingScenarioItemAddedToCart(itemId2),
new TestingScenarioItemQuantityAdjusted(itemId1, 3)
]);
result.ShouldBeSuccessful();
}
}

View C# snippet source on GitHub

EventScenario runs the same closed-stream check as the kernel. A scope closed with EventSequence.CompleteStream, or by an event type declared with [ClosesStream], rejects later appends to it with a constraint violation named closed-stream.

Closing event types are found by the same discovery as other constraints. Append the closing event and assert on the rejection of a covered event:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
[ClosesStream(EventStreamIdFrom = nameof(Period), ReopenedBy = [typeof(TestingScenarioBooksReopened)])]
public record TestingScenarioBooksClosed(string Period);
[EventType]
public record TestingScenarioBooksReopened(string Period);
[EventType]
public record TestingScenarioEntryPosted(string Description);
public static class TestingScenarioClosingEvent
{
public static async Task Run()
{
using var scenario = new EventScenario();
var closing = await scenario.EventLog.Append("ledger-1", new TestingScenarioBooksClosed("2026-04"));
closing.ShouldBeSuccessful();
// Covered: same event source, same stream type, stream id taken from the closing event's Period.
var late = await scenario.EventLog.Append(
"ledger-1",
new TestingScenarioEntryPosted("Late invoice"),
"ledger",
"2026-04");
late.ShouldHaveConstraintViolation("closed-stream");
// Not covered: another event source, and the next period.
(await scenario.EventLog.Append("ledger-2", new TestingScenarioEntryPosted("Open"), "ledger", "2026-04")).ShouldBeSuccessful();
(await scenario.EventLog.Append("ledger-1", new TestingScenarioEntryPosted("Next"), "ledger", "2026-05")).ShouldBeSuccessful();
}
}

View C# snippet source on GitHub

Seed a closed state with Given, append the reopening event with When, and assert that the scope accepts events again:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
[ClosesStream(EventStreamIdFrom = nameof(Period), ReopenedBy = [typeof(TestingScenarioReopeningBooksReopened)])]
public record TestingScenarioReopeningBooksClosed(string Period);
[EventType]
public record TestingScenarioReopeningBooksReopened(string Period);
[EventType]
public record TestingScenarioReopeningEntryPosted(string Description);
public static class TestingScenarioReopeningEvent
{
public static async Task Run()
{
using var scenario = new EventScenario();
await scenario.Given
.ForEventSource("ledger-1")
.Events(new TestingScenarioReopeningBooksClosed("2026-04"));
// The reopening fact is accepted inside the scope it reopens.
var reopened = await scenario.When
.ForEventSource("ledger-1")
.Events(new TestingScenarioReopeningBooksReopened("2026-04"));
reopened.ShouldBeSuccessful();
var posted = await scenario.EventLog.Append(
"ledger-1",
new TestingScenarioReopeningEntryPosted("Correction"),
"ledger",
"2026-04");
posted.ShouldBeSuccessful();
}
}

View C# snippet source on GitHub

Manual closure goes through EventSequence. GetClosedStreams shows what is closed and by whom:

using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
public record TestingScenarioManualCloseReportEdited(string Text);
public static class TestingScenarioManualClose
{
public static async Task Run()
{
using var scenario = new EventScenario();
var scope = new ClosedStreamScope(EventSourceId: "report-1", EventStreamId: "2026-04");
var closed = await scenario.EventSequence.CompleteStream(scope);
Console.WriteLine($"Closed: {closed.IsSuccess}");
var edit = await scenario.EventLog.Append(
"report-1",
new TestingScenarioManualCloseReportEdited("Late edit"),
"monthly-report",
"2026-04");
edit.ShouldHaveConstraintViolation("closed-stream");
var closedStreams = await scenario.EventSequence.GetClosedStreams();
Console.WriteLine($"Closed scopes: {closedStreams.Count}");
}
}

View C# snippet source on GitHub

Within one AppendMany, a covered event after a closing event is refused, and close, reopen, then a covered event succeeds. A manual closure on the same scope also refuses the reopening event, because a ReopenedBy event only lifts its own constraint’s closure. See Closing streams for the rules.

Personal data marked with [PII] passes through the kernel’s encryption handler before entering in-memory event storage. Reads decrypt those values with keys held only by that scenario. The encryption schema follows the stored event generation’s markings, using discovered compliance metadata providers. An undiscovered generation raises EventSchemaNotDiscovered; a provider that cannot be activated fails with its identity and underlying cause.

Use append-result and event-sequence assertions, or read through EventLog and EventSequence, to check successful appends and the values returned to readers. A plaintext round trip alone does not prove encryption at rest. Chronicle’s own harness regressions inspect the protected content internally, but that raw-content inspection is not a public consumer assertion API.

The keys stay in memory and are not shared between scenarios. These tests cover event encryption and decryption, not database persistence, read-model sink encryption, or key-store durability. EventScenario does not support subject erasure. Test erasure against a running kernel and the intended storage provider; event redaction, covered below, is a different operation.

EventSequence.Redact(sequenceNumber, reason) and EventSequence.Redact(eventSourceId, reason, eventTypes) run synchronously inside the scenario, through the same System-sequence reactor the kernel uses. When the call returns, the targeted events are EventRedacted in their original slots with their original event source. The stored payload keeps the reason and the original event type.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Testing.EventSequences;
[EventType]
public record TestingScenarioRedactNoteWritten(string Text);
public static class TestingScenarioRedact
{
public static async Task Run()
{
using var scenario = new EventScenario();
var appended = await scenario.EventLog.Append("member-1", new TestingScenarioRedactNoteWritten("Call me at 555-0100"));
await scenario.EventSequence.Redact(appended.SequenceNumber, "Subject asked for erasure");
var events = await scenario.EventLog.GetFromSequenceNumber(EventSequenceNumber.First);
Console.WriteLine(events[0].Context.EventType.Id);
}
}

View C# snippet source on GitHub

Passing event types limits an event-source redaction to those types; passing none redacts every event of the source. Redaction works on the event log and on named sequences, and each scenario instance is isolated. See Redaction for the production behavior.

Only the two redaction requests are served. Other operations that run through the System sequence, such as Revise, fail with ”… is not available in test scenarios”. The redaction request itself is not recorded in a System sequence, and observers are not replayed because the scenario hosts none.

If your spec supplies generated event types or constraints at runtime, give it its own IClientArtifactsProvider. Create new Defaults(artifacts) and pass those defaults to new EventScenario(defaults). The supplied provider controls event type discovery, serialization, and automatic constraint discovery instead of the process-wide default.

To replace automatic constraint discovery, pass an ICanProvideConstraints as the second argument. In the (Defaults, ICanProvideConstraints?) overload, null still discovers constraints from the supplied defaults. To disable constraints, pass an empty provider whose Provide() returns an empty list. In the older explicit-provider constructors, null means no constraints; constructors without run-specific defaults still use the shared artifact provider.

To select an identity while keeping automatic discovery, use new EventScenario(eventSequenceId, eventStoreName, namespaceName). For run-specific artifacts, use new EventScenario(defaults, eventSequenceId, eventStoreName, namespaceName). Neither overload takes a constraint provider; the existing explicit-provider overload still treats null as no constraints.

When you append an older event generation, discovered migrations run and store the migrated generations alongside the original content. The generation an ordinary read delivers is a separate choice. If a migrator has constructor dependencies, supply them through the service provider passed to Defaults.

Create a new EventScenario for each specification. Each instance starts with an empty sequence at sequence number zero, then accumulates state across calls. Dispose it after the specification to release its in-memory resources.

Keep runtime-supplied event types and constraints isolated too: use per-run defaults instead of changing the shared artifact provider.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Testing.EventSequences;
using Cratis.Specifications;
using Xunit;
public class when_adding_a_book_to_an_author : Specification
{
readonly EventSourceId _authorId = EventSourceId.New();
readonly EventScenario _scenario = new();
AppendResult _result = default!;
Task Establish() =>
_scenario.Given
.ForEventSource(_authorId)
.Events(new TestingScenarioAuthorRegistered("Jane Smith"));
async Task Because() =>
_result = await _scenario.EventLog.Append(_authorId, new TestingScenarioBookAdded("Clean Code"));
[Fact] void should_append_successfully() =>
_result.ShouldBeSuccessful();
[Fact] Task should_have_appended_book_added() =>
_scenario.EventLog.ShouldHaveAppendedEvent<TestingScenarioBookAdded>(new EventSequenceNumber(1));
}

View C# snippet source on GitHub

Once the spec attempts its append, use the append assertions to check success, violations, or errors. To inspect what was appended and in what order, continue with event sequence assertions.