Exemplo n.º 1
0
        public void Should_set_id()
        {
            var id        = Guid.NewGuid();
            var aggregate = new FakeAggregate(id);

            Assert.AreEqual(id, aggregate.Id);
        }
Exemplo n.º 2
0
        public void Taking_uncommitted_events_with_applied_one_uncommitted_event_returns_1()
        {
            var sut = new FakeAggregate();

            sut.BussinesOperation();
            Assert.Equal(1, sut.TakeUncommittedEvents().Length);
        }
Exemplo n.º 3
0
        public void Should_set_new_id_if_it_is_empty()
        {
            var id        = Guid.Empty;
            var aggregate = new FakeAggregate(id);

            Assert.AreNotEqual(id, aggregate.Id);
        }
Exemplo n.º 4
0
        public async Task SnapshotStore_SaveAsyncInvokesSerializeOnIAggregateSerializer()
        {
            var options = SetupContext();

            using (var context = new InfrastructureContext(options))
            {
                var mockSerializer = new Mock <IAggregateSerializer>();
                mockSerializer.Setup(s => s.Serialize(It.IsAny <FakeAggregate>()))
                .Returns <FakeAggregate>(aggr =>
                {
                    var payload = JsonConvert.SerializeObject(
                        aggr,
                        new JsonSerializerSettings
                    {
                        ConstructorHandling            = ConstructorHandling.AllowNonPublicDefaultConstructor,
                        TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
                        TypeNameHandling = TypeNameHandling.All,
                        ContractResolver = new Serialization.NonPublicPropertiesContractResolver()
                    });


                    return(Encoding.UTF8.GetBytes(payload));
                });

                var sut       = new SnapshotStore(mockSerializer.Object, context);
                var aggregate = new FakeAggregate(Guid.Empty);

                await sut.SaveAsync(aggregate);

                mockSerializer.Setup(s => s.Serialize(It.IsAny <FakeAggregate>()));
            }
        }
Exemplo n.º 5
0
            public void CanHandleCommandIfVersionGreaterThanZero()
            {
                var aggregate = new FakeAggregate(version: 1);
                var command   = new FakeCommand();

                aggregate.Handle(command);
            }
Exemplo n.º 6
0
            public void StepThroughIfAggregateHashNotSetd()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                pipelineHook.PreSave(aggregate, null);
            }
Exemplo n.º 7
0
        public void Taking_uncommitted_events_from_empty_aggregate_returns_empty_list()
        {
            var sut    = new FakeAggregate();
            var events = sut.TakeUncommittedEvents();

            Assert.NotNull(events);
        }
Exemplo n.º 8
0
 private void before_each()
 {
     _bucketId    = new BucketId("bucket-id");
     _aggregate   = new FakeAggregate(Guid.NewGuid());
     _readStreams = new FakeIReadStreams();
     _target      = new UnitOfWork(_bucketId, _readStreams, null, null);
 }
            public void CanHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command = new FakeCommand();

                aggregate.Handle(command);
            }
Exemplo n.º 10
0
            public void CanNotHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command   = new FakeCommand();

                Assert.Throws <InvalidOperationException>(() => aggregate.Handle(command));
            }
Exemplo n.º 11
0
            public void CanNotHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command = new FakeCommand();

                Assert.Throws<InvalidOperationException>(() => aggregate.Handle(command));
            }
 private void when_handle_multiple_times()
 {
     before = () =>
     {
         var @event    = new FakeEventWithHandler();
         var aggregate = new FakeAggregate();
         var target    = new DefaultEventHandlerWithNoCache();
         var stopwatch = Stopwatch.StartNew();
         for (var i = 0; i < Times; i++)
         {
             target.Handle(aggregate, @event);
         }
         _elapsedNoCache = stopwatch.Elapsed;
     };
     act = () =>
     {
         var @event    = new FakeEventWithHandler();
         var stopwatch = Stopwatch.StartNew();
         for (var i = 0; i < Times; i++)
         {
             _target.Handle(_aggregate, @event);
         }
         _elapsed = stopwatch.Elapsed;
     };
     it["executes handler multiple times"] = () => _aggregate.Counter.ShouldBe(Times);
     it["is faster than with no cache"]    = () => _elapsed.ShouldBeLessThan(_elapsedNoCache);
 }
Exemplo n.º 13
0
            public void CanHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command   = new FakeCommand();

                aggregate.Handle(command);
            }
            public void StepThroughIfAggregateHashNotSetd()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                pipelineHook.PreSave(aggregate, null);
            }
Exemplo n.º 15
0
            public void CanHandleCommandIfVersionGreaterThanZero()
            {
                var aggregate = new FakeAggregate(version: 1);
                var command = new FakeCommand();

                aggregate.Handle(command);
            }
        public void ApplyChangeWithNoChangeShouldNotFail()
        {
            var agg = new FakeAggregate();

            agg.DoFakeEvent3();
            agg.Version.Should().Be(0);
        }
Exemplo n.º 17
0
        public void Should_Redirect_Change_Created_By_Action_To_Event_Handler()
        {
            const int expectedUncommittedChanges = 2;
            const int expectedVersion            = 1;

            var aggregate = new FakeAggregate(Guid.NewGuid(), nameof(FakeAggregate));

            aggregate.PerformAction();

            var uncommittedChanges = (aggregate as IEnumerable <UncommittedChange>);

            Assert.Equal(expectedVersion, (aggregate as IAggregateRoot).Version);
            Assert.Equal(expectedUncommittedChanges, uncommittedChanges.Count());
            Assert.Collection(
                uncommittedChanges,
                uncommittedChange =>
            {
                Assert.NotNull(uncommittedChange.Event);
                Assert.IsType <FakeCreateEvent>(uncommittedChange.Event);
            },
                uncommittedChange =>
            {
                Assert.NotNull(uncommittedChange.Event);
                Assert.IsType <FakeDummyActionEvent>(uncommittedChange.Event);
            });
        }
Exemplo n.º 18
0
        public async Task Should_Publish_Aggregate_Events_When_Saving_Through_Repository()
        {
            const int expectedChanges = 2;

            var changes           = new List <Change>();
            var aggregateId       = Guid.NewGuid();
            var cancellationToken = default(CancellationToken);

            var storage    = Substitute.For <IStorage>();
            var repository = new AggregateRootRepository <FakeAggregate>(storage, null);

            var aggregate = new FakeAggregate(aggregateId, nameof(FakeAggregate));

            aggregate.Subscribe(changes.Add);

            aggregate.PerformAction();

            Assert.Empty(changes);

            await repository.SaveAsync(aggregate, cancellationToken);

            Assert.Equal(expectedChanges, changes.Count);
            Assert.Collection(
                changes,
                change =>
            {
                Assert.NotNull(change.Event);
                Assert.IsType <FakeCreateEvent>(change.Event);
            },
                change =>
            {
                Assert.NotNull(change.Event);
                Assert.IsType <FakeDummyActionEvent>(change.Event);
            });
        }
Exemplo n.º 19
0
        protected EventStoreTestContext()
        {
            Fixture = new Fixture();

            _taskCount   = 100;
            _aggregateId = Guid.NewGuid();
            _aggregate   = FakeAggregate.Create(_aggregateId, "initial text");
        }
Exemplo n.º 20
0
        public void Taking_snapshot_from_aggregate_with_applied_one_uncommitted_event_returns_that_event_was_applied()
        {
            var sut = new FakeAggregate();

            sut.BussinesOperation();
            var snapshot = (FakeAggregateState)sut.GetSnapshot().State;

            Assert.True(snapshot.FakeEventApplied);
        }
Exemplo n.º 21
0
            public void StepThroughIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostGet(aggregate);
            }
            public void StepThroughIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostGet(aggregate);
            }
            public void ThrowMemberAccessExceptionIfHashInvalid()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();
                aggregate.State = Guid.NewGuid();

                Assert.Throws<MemberAccessException>(() => pipelineHook.PreSave(aggregate, null));
            }
Exemplo n.º 24
0
        private void AddAggregateLink(DaisyAst ast, string rawStatement)
        {
            var statement = new FakeAggregate <int, int>(rawStatement).Link(rawStatement);

            new AstCollector(ast)
            .OfType <StatementNode>()
            .Where(x => x.Text == rawStatement)
            .Select(x => { x.LinkedStatement = statement; return(x); })    //Sigh, I wish I had a for each
            .ToList();
        }
Exemplo n.º 25
0
            public void CaptureAggregateTypeIfFirstCommit()
            {
                var aggregate      = new FakeAggregate(GuidStrategy.NewGuid(), 0);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                eventStore.Verify(mock => mock.Save(It.Is <Commit>(c => c.Headers[Header.Aggregate] == typeof(FakeAggregate).GetFullNameWithAssembly())), Times.Once());
            }
Exemplo n.º 26
0
 private void before_each()
 {
     _id                  = Guid.Parse("bcb724f5-562f-4706-b470-570fa7174ec0");
     _bucketId            = new BucketId("bucket-id");
     _aggregate           = new FakeAggregate(_id);
     _createSessions      = new FakeICreateSessions();
     _writeSessionStreams = new FakeIWriteStreams();
     _readStreams         = new FakeIReadStreams();
     _target              = new UnitOfWork(_bucketId, _readStreams, _createSessions, _writeSessionStreams);
 }
Exemplo n.º 27
0
            public void SaveSnapshotIfRequired()
            {
                var aggregate      = new FakeAggregate(GuidStrategy.NewGuid(), 9);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object, new AggregateStoreSettings());

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                snapshotStore.Verify(mock => mock.Save(It.Is <Snapshot>(s => s.StreamId == aggregate.Id && s.Version == 10)), Times.Once());
            }
Exemplo n.º 28
0
            public void ThrowMemberAccessExceptionIfHashInvalid()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                aggregate.UpdateHash();
                aggregate.State = Guid.NewGuid();

                Assert.Throws <MemberAccessException>(() => pipelineHook.PreSave(aggregate, null));
            }
            public void MethodsMatchingCustomNameAreIncluded()
            {
                var attribute = new ApplyByConventionAttribute { MethodName = "Custom" };
                var applyMethods = attribute.GetApplyMethods(typeof(FakeAggregate));
                var applyMethod = applyMethods.Single().Value;
                var aggregate = new FakeAggregate();

                applyMethod(aggregate, new FakeEvent());

                Assert.True(aggregate.Handled);
            }
Exemplo n.º 30
0
            public void StepThroughOnErrorIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostSave(aggregate, null, new InvalidOperationException());

                aggregate.VerifyHash();
            }
            public void MethodsMatchingCustomNameAreIncluded()
            {
                var attribute = new HandleByConventionAttribute { MethodName = "Custom" };
                var handleMethods = attribute.GetHandleMethods(typeof(FakeAggregate), new Mock<IServiceProvider>().Object);
                var handleMethod = handleMethods.Single().Value;
                var aggregate = new FakeAggregate();

                handleMethod(aggregate, new FakeCommand());

                Assert.True(aggregate.Handled);
            }
Exemplo n.º 32
0
            public void GetOrCreateWillReturnExistingAggregateIfAlreadyExists()
            {
                var command           = new FakeCommand();
                var aggregateId       = GuidStrategy.NewGuid();
                var existingAggregate = new FakeAggregate(aggregateId, 1);

                aggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), aggregateId)).Returns(existingAggregate);

                using (new CommandContext(aggregateId, HeaderCollection.Empty, new CommandEnvelope(aggregateId, command)))
                    Assert.Same(existingAggregate, aggregateStore.Object.GetOrCreate(aggregateId, (FakeAggregate aggregate) => aggregate.InitializeWith(command)));
            }
Exemplo n.º 33
0
            public void IncrementAggregateVersionIfSuccessful()
            {
                var version        = 11;
                var aggregate      = new FakeAggregate(GuidStrategy.NewGuid(), version);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                Assert.Equal(version + 1, aggregate.Version);
            }
Exemplo n.º 34
0
        public void Should_Enumerate_Aggregate()
        {
            IEnumerable aggregate = new FakeAggregate(Guid.NewGuid(), nameof(FakeAggregate));

            Assert.Single(aggregate);

            foreach (var change in aggregate)
            {
                Assert.IsType <UncommittedChange>(change);
            }
        }
Exemplo n.º 35
0
            public void IgnoreDuplicateCommits()
            {
                var aggregate      = new FakeAggregate(GuidStrategy.NewGuid(), 8);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object, new AggregateStoreSettings());

                eventStore.Setup(mock => mock.Save(It.IsAny <Commit>())).Throws <DuplicateCommitException>();

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                eventStore.Verify(mock => mock.Save(It.IsAny <Commit>()), Times.Once);
            }
Exemplo n.º 36
0
        public void ApplyEvent_WithUnsupportedEvent_ThrowsUnapplicableEventException()
        {
            // Arrange
            var mockAggregate = new FakeAggregate();
            var stubEvent     = new UnappliedEvent();

            // Act
            Action applyUnapplicable = () => mockAggregate.ApplyEvent(stubEvent);

            // Assert
            Assert.Throws <UnapplicableEvent>(applyUnapplicable);
        }
Exemplo n.º 37
0
        public void ApplyEvent_WithSupportedEvent_AppliesEvent()
        {
            // Arrange
            var mockAggregate = new FakeAggregate();
            var mockEvent     = new AppliedEvent1();

            // Act
            mockAggregate.ApplyEvent(mockEvent);

            // Assert
            Assert.Equal(mockEvent, mockAggregate.applied_events[0]);
        }
Exemplo n.º 38
0
        public void Taking_uncommitted_events_without_adding_any_from_restored_aggregate_returns_empty_list()
        {
            var sut    = new FakeAggregate();
            var events = new List <IEvent>
            {
                new FakeEvent()
            }.ToArray();

            sut.Restore(SequentialGuid.NewGuid(), events.ToArray());
            events = sut.TakeUncommittedEvents();
            Assert.Equal(0, events.Length);
        }
            public void UseCachedAggregateIfAvailable()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                memoryCache.Add(aggregate.CacheKey, aggregate, new CacheItemPolicy());

                Assert.Same(aggregate, cachedAggregateStore.Get(typeof(FakeAggregate), aggregate.Id));

                decoratedAggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), aggregate.Id), Times.Never());
            }
            public void LoadFromUnderlyingStoreIfNotCached()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                decoratedAggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), aggregate.Id)).Returns(aggregate);

                cachedAggregateStore.Get(typeof(FakeAggregate), aggregate.Id);

                decoratedAggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), aggregate.Id), Times.Once());
            }
            public void RetrieveCommandHandlerBasedOnCommandType()
            {
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);

                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { }));
                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                Processor.Process(message);

                HandlerRegistry.Verify(mock => mock.GetHandlerFor(command), Times.Once());
            }
            public void UpdateCacheOnSuccessfulSave()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                memoryCache.Add(aggregate.CacheKey, aggregate, new CacheItemPolicy());

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    cachedAggregateStore.Save(aggregate, context);

                Assert.NotSame(aggregate, memoryCache.Get(aggregate.CacheKey));
            }
            public void CopyAggregateBeforeSaving()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                // ReSharper disable AccessToDisposedClosure
                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                {
                    cachedAggregateStore.Save(aggregate, context);
                    decoratedAggregateStore.Verify(mock => mock.Save(It.Is<Aggregate>(copy => !ReferenceEquals(aggregate, copy)), context), Times.Once());
                }
                // ReSharper restore AccessToDisposedClosure
            }
            public void UseSnapshotIfAvailable()
            {
                var id = GuidStrategy.NewGuid();
                var snapshot = new FakeAggregate(id, 10);
                var events = new Event[] { new FakeEvent(), new FakeEvent() };
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object);

                snapshotStore.Setup(mock => mock.GetSnapshot(typeof(FakeAggregate), id, Int32.MaxValue)).Returns(new Snapshot(id, 10, snapshot));
                eventStore.Setup(mock => mock.GetStream(id, 11)).Returns(new[] { new Commit(1L, DateTime.UtcNow, Guid.NewGuid(), id, 11, HeaderCollection.Empty, new EventCollection(events)) });

                var aggregate = aggregateStore.Get(typeof(FakeAggregate), id);

                snapshotStore.Verify(mock => mock.GetSnapshot(typeof(FakeAggregate), id, Int32.MaxValue), Times.Once());

                Assert.Equal(11, aggregate.Version);
            }
            public void ReloadAggregateOnConcurrencyException()
            {
                var save = 0;
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);
                var ex = new ConcurrencyException();

                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)));
                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);
                AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() =>
                {
                    if (++save == 1)
                        throw ex;
                });

                Processor.Process(message);

                AggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId), Times.Exactly(2));
            }
            public void GetOrCreateWillReturnNewAggregateIfAggregateDoesNotAlreadyExist()
            {
                var command = new FakeCommand();
                var aggregateId = GuidStrategy.NewGuid();
                var newAggregate = new FakeAggregate(aggregateId, 0);

                aggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), aggregateId)).Returns(newAggregate);

                using (new CommandContext(aggregateId, HeaderCollection.Empty, new CommandEnvelope(aggregateId, command)))
                {
                    aggregateStore.Setup(mock => mock.Save(newAggregate, It.IsAny<CommandContext>())).Returns(new SaveResult(new FakeAggregate(aggregateId, 1), new Commit(GuidStrategy.NewGuid(), aggregateId, 1, HeaderCollection.Empty, EventCollection.Empty)));

                    var savedAggregate = aggregateStore.Object.GetOrCreate(aggregateId, (FakeAggregate aggregate) => aggregate.InitializeWith(command));

                    Assert.Equal(1, savedAggregate.Version);
                }
            }
            public void StepThroughOnErrorIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostSave(aggregate, null, new InvalidOperationException());

                aggregate.VerifyHash();
            }
 protected override void When()
 {
         _aggregate = _creationStrategy.CreateAggregateRoot<FakeAggregate>();
 }
            public void DoNotVerifyInitializedIfImplicitCreateAllowed()
            {
                var aggregate = new FakeAggregate(explicitCreateRequired: false, version: 0);
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    commandHandler.Handle(context);

                    Assert.True(aggregate.Handled);
                }
            }
            public void CaptureAggregateTypeIfFirstCommit()
            {
                var aggregate = new FakeAggregate(GuidStrategy.NewGuid(), 0);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                eventStore.Verify(mock => mock.Save(It.Is<Commit>(c => c.Headers[Header.Aggregate] == typeof(FakeAggregate).GetFullNameWithAssembly())), Times.Once());
            }
            public void SaveSnapshotIfRequired()
            {
                var aggregate = new FakeAggregate(GuidStrategy.NewGuid(), 9);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object, new AggregateStoreSettings());

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                snapshotStore.Verify(mock => mock.Save(It.Is<Snapshot>(s => s.StreamId == aggregate.Id && s.Version == 10)), Times.Once());
            }
            public void RemoveAggregateFromCacheOnConcurrencyException()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                // ReSharper disable AccessToDisposedClosure
                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                {
                    memoryCache.Add(aggregate.CacheKey, aggregate, new CacheItemPolicy());
                    decoratedAggregateStore.Setup(mock => mock.Save(It.Is<Aggregate>(copy => !ReferenceEquals(aggregate, copy)), context)).Throws<ConcurrencyException>();

                    Assert.Throws<ConcurrencyException>(() => cachedAggregateStore.Save(aggregate, context));
                    Assert.False(memoryCache.Contains(aggregate.CacheKey));
                }
                // ReSharper restore AccessToDisposedClosure
            }
            public void DoNotSaveAggregateOnSuccessIfNoEventsRaised()
            {
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { });

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                    commandHandler.Handle(context);

                AggregateStore.Verify(mock => mock.Save(aggregate, It.IsAny<CommandContext>()), Times.Never);
            }
            public void VerifyInitializedIfExplictCreateRequired()
            {
                var aggregate = new FakeAggregate(explicitCreateRequired: true, version: 0);
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    var ex = Assert.Throws<InvalidOperationException>(() => commandHandler.Handle(context));

                    Assert.Equal(Exceptions.AggregateNotInitialized.FormatWith(typeof(FakeAggregate), Guid.Empty), ex.Message);
                }
            }
            public void WillTimeoutEventuallyIfCannotSave()
            {
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);
                var processor = new CommandProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new CommandProcessorSettings { RetryTimeout = TimeSpan.FromMilliseconds(20) });

                SystemTime.ClearOverride();

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);
                AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() => { throw new ConcurrencyException(); });
                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)));

                Assert.Throws<TimeoutException>(() => processor.Process(message));
            }
            public void GetOrCreateWillReturnExistingAggregateIfAlreadyExists()
            {
                var command = new FakeCommand();
                var aggregateId = GuidStrategy.NewGuid();
                var existingAggregate = new FakeAggregate(aggregateId, 1);

                aggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), aggregateId)).Returns(existingAggregate);

                using (new CommandContext(aggregateId, HeaderCollection.Empty, new CommandEnvelope(aggregateId, command)))
                    Assert.Same(existingAggregate, aggregateStore.Object.GetOrCreate(aggregateId, (FakeAggregate aggregate) => aggregate.InitializeWith(command)));
            }
            public void IgnoreDuplicateCommits()
            {
                var aggregate = new FakeAggregate(GuidStrategy.NewGuid(), 8);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object, new AggregateStoreSettings());

                eventStore.Setup(mock => mock.Save(It.IsAny<Commit>())).Throws<DuplicateCommitException>();

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                eventStore.Verify(mock => mock.Save(It.IsAny<Commit>()), Times.Once);
            }
Exemplo n.º 58
0
 private void AddAggregateLink(DaisyAst ast, string rawStatement)
 {
     var statement = new FakeAggregate<int,int>(rawStatement).Link(rawStatement);
     new AstCollector(ast)
         .OfType<StatementNode>()
         .Where(x => x.Text == rawStatement)
         .Select(x => { x.LinkedStatement = statement; return x; }) //Sigh, I wish I had a for each
         .ToList();
 }
            public void IncrementAggregateVersionIfSuccessful()
            {
                var version = 11;
                var aggregate = new FakeAggregate(GuidStrategy.NewGuid(), version);
                var aggregateStore = new AggregateStore(aggregateUpdater.Object, snapshotStore.Object, eventStore.Object);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                    aggregateStore.Save(aggregate, context);

                Assert.Equal(version + 1, aggregate.Version);
            }
            public void UpdateHashOnSuccessfulSave()
            {
                var commit = (Commit)FormatterServices.GetUninitializedObject(typeof(Commit));
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();
                aggregate.State = Guid.NewGuid();

                pipelineHook.PostSave(aggregate, commit, null);

                aggregate.VerifyHash();
            }