コード例 #1
0
ファイル: AggregateRootTests.cs プロジェクト: mah1212/Weapsy
        public void Should_set_id()
        {
            var id        = Guid.NewGuid();
            var aggregate = new FakeAggregate(id);

            Assert.AreEqual(id, aggregate.Id);
        }
コード例 #2
0
ファイル: AggregateTests.cs プロジェクト: oguzhaneren/ses
        public void Taking_uncommitted_events_with_applied_one_uncommitted_event_returns_1()
        {
            var sut = new FakeAggregate();

            sut.BussinesOperation();
            Assert.Equal(1, sut.TakeUncommittedEvents().Length);
        }
コード例 #3
0
ファイル: AggregateRootTests.cs プロジェクト: mah1212/Weapsy
        public void Should_set_new_id_if_it_is_empty()
        {
            var id        = Guid.Empty;
            var aggregate = new FakeAggregate(id);

            Assert.AreNotEqual(id, aggregate.Id);
        }
コード例 #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>()));
            }
        }
コード例 #5
0
            public void CanHandleCommandIfVersionGreaterThanZero()
            {
                var aggregate = new FakeAggregate(version: 1);
                var command   = new FakeCommand();

                aggregate.Handle(command);
            }
コード例 #6
0
            public void StepThroughIfAggregateHashNotSetd()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                pipelineHook.PreSave(aggregate, null);
            }
コード例 #7
0
ファイル: AggregateTests.cs プロジェクト: oguzhaneren/ses
        public void Taking_uncommitted_events_from_empty_aggregate_returns_empty_list()
        {
            var sut    = new FakeAggregate();
            var events = sut.TakeUncommittedEvents();

            Assert.NotNull(events);
        }
コード例 #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);
 }
コード例 #9
0
            public void CanHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command = new FakeCommand();

                aggregate.Handle(command);
            }
コード例 #10
0
            public void CanNotHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command   = new FakeCommand();

                Assert.Throws <InvalidOperationException>(() => aggregate.Handle(command));
            }
コード例 #11
0
            public void CanNotHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command = new FakeCommand();

                Assert.Throws<InvalidOperationException>(() => aggregate.Handle(command));
            }
コード例 #12
0
 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);
 }
コード例 #13
0
            public void CanHandleCommandIfVersionEqualsZero()
            {
                var aggregate = new FakeAggregate(version: 0);
                var command   = new FakeCommand();

                aggregate.Handle(command);
            }
コード例 #14
0
            public void StepThroughIfAggregateHashNotSetd()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                pipelineHook.PreSave(aggregate, null);
            }
コード例 #15
0
            public void CanHandleCommandIfVersionGreaterThanZero()
            {
                var aggregate = new FakeAggregate(version: 1);
                var command = new FakeCommand();

                aggregate.Handle(command);
            }
コード例 #16
0
        public void ApplyChangeWithNoChangeShouldNotFail()
        {
            var agg = new FakeAggregate();

            agg.DoFakeEvent3();
            agg.Version.Should().Be(0);
        }
コード例 #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);
            });
        }
コード例 #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);
            });
        }
コード例 #19
0
        protected EventStoreTestContext()
        {
            Fixture = new Fixture();

            _taskCount   = 100;
            _aggregateId = Guid.NewGuid();
            _aggregate   = FakeAggregate.Create(_aggregateId, "initial text");
        }
コード例 #20
0
ファイル: AggregateTests.cs プロジェクト: oguzhaneren/ses
        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);
        }
コード例 #21
0
            public void StepThroughIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostGet(aggregate);
            }
コード例 #22
0
            public void StepThroughIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();

                pipelineHook.PostGet(aggregate);
            }
コード例 #23
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));
            }
コード例 #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();
        }
コード例 #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());
            }
コード例 #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);
 }
コード例 #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());
            }
コード例 #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));
            }
コード例 #29
0
            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);
            }
コード例 #30
0
            public void StepThroughOnErrorIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate    = new FakeAggregate();

                aggregate.UpdateHash();

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

                aggregate.VerifyHash();
            }
コード例 #31
0
            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);
            }
コード例 #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)));
            }
コード例 #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);
            }
コード例 #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);
            }
        }
コード例 #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);
            }
コード例 #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);
        }
コード例 #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]);
        }
コード例 #38
0
ファイル: AggregateTests.cs プロジェクト: oguzhaneren/ses
        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);
        }
コード例 #39
0
            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());
            }
コード例 #40
0
            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());
            }
コード例 #41
0
            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());
            }
コード例 #42
0
            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));
            }
コード例 #43
0
            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
            }
コード例 #44
0
            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);
            }
コード例 #45
0
            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));
            }
コード例 #46
0
            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);
                }
            }
コード例 #47
0
            public void StepThroughOnErrorIfAggregateHashUnchanged()
            {
                var pipelineHook = new AggregateStateValidator();
                var aggregate = new FakeAggregate();

                aggregate.UpdateHash();

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

                aggregate.VerifyHash();
            }
コード例 #48
0
 protected override void When()
 {
         _aggregate = _creationStrategy.CreateAggregateRoot<FakeAggregate>();
 }
コード例 #49
0
            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);
                }
            }
コード例 #50
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());
            }
コード例 #51
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());
            }
コード例 #52
0
            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
            }
コード例 #53
0
            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);
            }
コード例 #54
0
            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);
                }
            }
コード例 #55
0
            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));
            }
コード例 #56
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)));
            }
コード例 #57
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);
            }
コード例 #58
0
ファイル: DaisyProgramTests.cs プロジェクト: Ancestry/Daisy
 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();
 }
コード例 #59
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);
            }
コード例 #60
0
            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();
            }