// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using FakeItEasy; using Squidex.Infrastructure.EventSourcing; using Squidex.Infrastructure.States; namespace Squidex.Infrastructure.TestHelpers { public sealed class TestState where T : class, new() { private readonly List> events = new List>(); private readonly ISnapshotStore snapshotStore = A.Fake>(); private HandleSnapshot? handleSnapshot; private HandleEvent? handleEvent; public DomainId Id { get; } public IPersistenceFactory PersistenceFactory { get; } public IPersistence Persistence { get; } = A.Fake>(); public long Version { get; set; } = EtagVersion.Empty; public T Snapshot { get; set; } = new T(); public TestState(string id, IPersistenceFactory? persistenceFactory = null) : this(DomainId.Create(id), persistenceFactory) { } public TestState(DomainId id, IPersistenceFactory? persistenceFactory = null) { Id = id; PersistenceFactory = persistenceFactory ?? A.Fake>(); A.CallTo(() => PersistenceFactory.Snapshots) .Returns(snapshotStore); A.CallTo(() => Persistence.Version) .ReturnsLazily(() => Version); A.CallTo(() => snapshotStore.ReadAllAsync(A._)) .ReturnsLazily(() => new List> { new SnapshotResult(id, Snapshot, Version, true) }.ToAsyncEnumerable()); A.CallTo(() => PersistenceFactory.WithEventSourcing(A._, id, A._)) .Invokes(x => { handleEvent = x.GetArgument(2); }) .Returns(Persistence); A.CallTo(() => PersistenceFactory.WithSnapshots(A._, id, A>._)) .Invokes(x => { handleSnapshot = x.GetArgument>(2); }) .Returns(Persistence); A.CallTo(() => PersistenceFactory.WithSnapshotsAndEventSourcing(A._, id, A>._, A._)) .Invokes(x => { handleSnapshot = x.GetArgument>(2); handleEvent = x.GetArgument(3); }) .Returns(Persistence); A.CallTo(() => Persistence.WriteEventsAsync(A>>._, A._)) .Invokes(x => { events.AddRange(x.GetArgument>>(0)!); }); A.CallTo(() => Persistence.WriteSnapshotAsync(A._, A._)) .Invokes(x => { Snapshot = x.GetArgument(0)!; }); A.CallTo(() => Persistence.ReadAsync(A._, A._)) .Invokes(x => { handleSnapshot?.Invoke(Snapshot, Version); if (handleEvent != null) { foreach (var @event in events) { handleEvent(@event); } } }); A.CallTo(() => Persistence.DeleteAsync(A._)) .Invokes(x => { Snapshot = new T(); }); } public void AddEvent(Envelope @event) { events.Add(@event); } public void AddEvent(IEvent @event) { events.Add(Envelope.Create(@event)); } } }