public void AggregateCache_GetByIdAsyncWithoutConfigureShouldThrowException()
        {
            var guid = Guid.NewGuid();
            var testAggregate = new TestAggregate();

            AggregateCache.Instance.Awaiting(x => x.GetByIdAsync<TestAggregate>(guid)).ShouldThrow<InvalidOperationException>();
        }
 public void SetUp()
 {
     testAggregate = new TestAggregate(Guid.NewGuid());
     mockUnitOfWork.Setup(x => x.Delete(testAggregate));
     repository.UnitOfWork = mockUnitOfWork.Object;
     repository.Delete(testAggregate);
 }
 public void SetUp()
 {
     var testAggregate = new TestAggregate(Guid.NewGuid(), string.Empty);
     aggregateHelper.StoreTestAggregate(testAggregate);
     aggregateHelper.DeleteLastCreatedTestAggregate();
     retrievedAggregate = aggregateHelper.RetrieveLastCreatedTestAggregate();
 }
Example #4
0
        public void sequence_domain_event_process_test()
        {
            var processor = ObjectContainer.Resolve<IMessageProcessor<ProcessingDomainEventStreamMessage, DomainEventStreamMessage, bool>>();

            var note = new TestAggregate(ObjectId.GenerateNewStringId(), "initial title");
            var aggregate = note as IAggregateRoot;
            var message1 = CreateMessage(aggregate);

            aggregate.AcceptChanges(1);
            note.ChangeTitle("title1");
            var message2 = CreateMessage(aggregate);

            aggregate.AcceptChanges(2);
            note.ChangeTitle("title2");
            var message3 = CreateMessage(aggregate);

            processor.Process(new ProcessingDomainEventStreamMessage(message1, new DomainEventStreamProcessContext(message1)));
            processor.Process(new ProcessingDomainEventStreamMessage(message3, new DomainEventStreamProcessContext(message3)));
            processor.Process(new ProcessingDomainEventStreamMessage(message2, new DomainEventStreamProcessContext(message2)));

            _waitHandle.WaitOne();

            for (var i = 0; i < 3; i++)
            {
                Assert.AreEqual(i + 1, _versionList[i]);
            }
        }
 public void SetUp()
 {
     var testAggregate = new TestAggregate(Guid.NewGuid(), string.Empty);
     aggregateHelper.StoreTestAggregate(testAggregate);
     retrievedAggregate = aggregateHelper.RetrieveLastCreatedTestAggregate();
     aggregateHelper.UpdateLastCreatedTestAggregateName("interruption");
     retrievedAggregate.Value.SetName("updated name");
 }
 public void SetUp()
 {
     var testAggregate = new TestAggregate(Guid.NewGuid(), string.Empty);
     aggregateHelper.StoreTestAggregate(testAggregate);
     retrievedAggregate = aggregateHelper.RetrieveLastCreatedTestAggregate();
     versionBeforeUpdate = retrievedAggregate.Value.Version;
     aggregateHelper.UpdateLastCreatedTestAggregateName(UPDATED_NAME);
     retrievedAggregate = aggregateHelper.RetrieveLastCreatedTestAggregate();
 }
        public void CanFetchSavedAggregate()
        {
            var storage = new MongoStorage();
            var aggregate = new TestAggregate(1);
            storage.SaveOrUpdate(aggregate);

            var fetchedItem = storage.FetchById<TestAggregate>(aggregate.AggregateIdentity);
            Assert.That(fetchedItem, Is.Not.Null);
        }
        internal void DeleteTestAggregate(TestAggregate aggregate)
        {
            var repository = new Repository<TestAggregate, TestEntity>();
            using (var unitOfWork = new UnitOfWorkFactory(TestSettings.BoilerMongoConfiguration).CreateUnitOfWork())
            {
                repository.UnitOfWork = unitOfWork;
                repository.Delete(aggregate);

                unitOfWork.Commit();
            }
        }
        public void CanSearchSavedAggregate()
        {
            int valueToFind = 123;
            var storage = new MongoStorage();
            var aggregate = new TestAggregate(valueToFind);
            storage.SaveOrUpdate(aggregate);

            TestAggregate fetchedItem =
                storage.SearchFor<TestAggregate>(i => i.FindValue == valueToFind).FirstOrDefault();
            Assert.That(fetchedItem, Is.Not.Null);
            Assert.That(fetchedItem.FindValue, Is.EqualTo(valueToFind));
        }
Example #10
0
        public async Task SaveChanges_CommitsOnlyChangedAggregates()
        {
            TestAggregate testAggregate = Substitute.ForPartsOf <TestAggregate>(Guid.NewGuid());

            domainClasses.Add(new DomainClassInfo(TestAggregateClassId, null, testAggregate.GetType()));

            sut.Add(testAggregate);

            await sut.SaveChangesAsync();

            testAggregate.Received(0).Commit();
        }
        public void Setup()
        {
            // This will clear the cache between runs.
            var cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();

            foreach (var cacheKey in cacheKeys)
            {
                MemoryCache.Default.Remove(cacheKey);
            }

            _testStore = new TestInMemoryEventStore();
            _rep1      = new CacheRepository(new Repository(_testStore, new TestEventPublisher()), _testStore);
            _rep2      = new CacheRepository(new Repository(_testStore, new TestEventPublisher()), _testStore);

            _aggregate = new TestAggregate(Guid.NewGuid());
            _rep1.Save(_aggregate);

            var t1 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep1.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep1.Save(aggregate);
                }
            });

            var t2 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep2.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep2.Save(aggregate);
                }
            });
            var t3 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep2.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep2.Save(aggregate);
                }
            });

            t1.Start();
            t2.Start();
            t3.Start();

            Task.WaitAll(t1, t2, t3);
        }
Example #12
0
        public void Handle(RunCrawlerCommand command)
        {
            _crawler.Configuration.CrawlTimeoutSeconds  = command.RunCrawlerConfigurationDto.CrawlTimeoutSeconds ?? 30;
            _crawler.Configuration.MaxConcurrentThreads = command.RunCrawlerConfigurationDto.MaxConcurrentThreads ?? 1;
            _crawler.Configuration.MaxPagesToCrawl      = command.RunCrawlerConfigurationDto.MaxPagesToCrawl ?? 100;

            _crawler.Run(command.RunCrawlerConfigurationDto.Url);

            var aggregate = new TestAggregate(command.Guid, command.RunCrawlerConfigurationDto.Url);

            aggregate.Version = -1;
            _eventRepository.Save <TestAggregate>(aggregate, aggregate.Version);
        }
Example #13
0
        public void AggregateShouldHaveTheCorrectValuesWhenLoadedFromHistory()
        {
            var guid   = Guid.NewGuid();
            var events = new List <IDomainEvent>();

            events.Add(new TestAggregateCreatedEvent(guid, typeof(TestAggregate), String.Empty));

            var aggregate = new TestAggregate();

            aggregate.LoadFromHistory(events);

            aggregate.Id.Should().Be(guid);
        }
        public async Task stored_instance_can_be_correctly_retrieved()
        {
            var aggregateRoot = TestAggregate.NewFrom(_testAggregateId);

            aggregateRoot.DoTransformationWith("NewValue");

            await _store.SaveChanges(aggregateRoot);

            var result = await _store.Get <TestAggregate>(_testAggregateId);

            result.IsSuccess.Should().BeTrue();
            result.Value.Value.Should().Be("NewValue");
        }
Example #15
0
            public void Should_Retrieve_Aggregate()
            {
                IEventSourcedAggregateRepository <TestAggregate, Guid> repository = Factory.CreateTestAggregateRepository();

                TestAggregate aggregate = new TestAggregate(Guid.NewGuid());

                repository.Save(aggregate);

                TestAggregate fromRepo = repository.GetById(aggregate.Id);

                Assert.NotNull(fromRepo);
                Assert.Equal(aggregate.Id, fromRepo.Id);
            }
        public void RepositoryShouldPersistEventToEventStoreWhenAggregateWasSaved()
        {
            EventBus   eventBus;
            EventStore eventStore;
            var        repository = EnvironmentMock.CreateEnvironment <TestAggregate>(out eventBus, out eventStore);

            var guid      = Guid.NewGuid();
            var aggregate = new TestAggregate(guid, String.Empty);

            repository.Save(aggregate, -1);

            eventStore.GetEventsByAggregateId(guid).Count().Should().Be(1);
        }
        internal void StoreTestAggregate(TestAggregate testAggregate)
        {
            var repository = new Repository<TestAggregate, TestEntity>();
            using (var unitOfWork = new UnitOfWorkFactory(TestSettings.BoilerMongoConfiguration).CreateUnitOfWork())
            {
                repository.UnitOfWork = unitOfWork;
                repository.Add(testAggregate);

                unitOfWork.Commit();

                LastCreatedAggregateId = testAggregate.Id;
            }
        }
Example #18
0
        public void Setup()
        {
            _eventStore     = new TestInMemoryEventStore();
            _eventPublisher = new TestEventPublisher();
            var aggregateFactory = new AggregateFactory(new TestDependencyResolver());

            _rep        = new Repository <ISingleSignOnToken>(aggregateFactory, _eventStore, _eventPublisher, new NullCorrelationIdHelper());
            _unitOfWork = new UnitOfWork <ISingleSignOnToken>(_rep);

            _aggregate = new TestAggregate(Guid.NewGuid());
            _aggregate.DoSomething();
            _rep.Save(_aggregate);
        }
Example #19
0
        public void VersionOfAggregateCreateEventShouldBeZero()
        {
            EventBus   eventBus;
            EventStore eventStore;
            var        repository = EnvironmentMock.CreateEnvironment <TestAggregate>(out eventBus, out eventStore);

            var guid      = Guid.NewGuid();
            var aggregate = new TestAggregate(guid, "Test Aggregate 1");

            repository.Save(aggregate, -1);

            eventStore.GetEventsByAggregateId(guid).FirstOrDefault().Version.Should().Be(0);
        }
Example #20
0
        protected override void Context()
        {
            base.Context();

            this._storeEvents = Wireup.Init().UsingInMemoryPersistence().Build();
            this._repository1 = new EventStoreRepository(this._storeEvents, new AggregateFactory(), new ConflictDetector());
            this._repository2 = new EventStoreRepository(this._storeEvents, new AggregateFactory(), new ConflictDetector());

            _aggregateId = Guid.NewGuid();
            var aggregate = new TestAggregate(_aggregateId, "my name is..");

            _repository1.Save(aggregate, Guid.NewGuid());
        }
Example #21
0
 public When_saving_fails()
 {
     _memoryCache = new MemoryCache();
     _testRep     = new TestRepository();
     _rep         = new CacheRepository(_testRep, new TestInMemoryEventStore(), _memoryCache);
     _aggregate   = _testRep.Get <TestAggregate>(Guid.NewGuid());
     _aggregate.DoSomething();
     try
     {
         _rep.Save(_aggregate, 100);
     }
     catch (Exception) { }
 }
        public When_evicting_cache_entry()
        {
            _memoryCache = new MemoryCache();
            _rep         = new CacheRepository(new TestRepository(), new TestEventStore(), _memoryCache);
            _aggregate   = _rep.Get <TestAggregate>(Guid.NewGuid());
            ManualResetEvent resetEvent;
            var field = _rep.GetType().GetField("_locks", BindingFlags.Static | BindingFlags.NonPublic);

            _locks = (ConcurrentDictionary <Guid, ManualResetEvent>)field.GetValue(_rep);
            _locks.TryGetValue(_aggregate.Id, out resetEvent);
            _memoryCache.Remove(_aggregate.Id);
            resetEvent.WaitOne(500);
        }
Example #23
0
        public async Task ResolveAsyncTest()
        {
            var repository = new InMemoryRepository <TestAggregate, Guid>();
            var expected   = new TestAggregate(new Guid("E5318031-FF08-47A3-A35D-EE8F56B64C67"));
            await repository.StoreAsync(expected);

            var actual = await repository.ResolveAsync(new Guid("E5318031-FF08-47A3-A35D-EE8F56B64C67"));

            Assert.True(ReferenceEquals(expected, actual));
            Assert.Equal(expected.Id, actual.Id);

            Assert.Null(await repository.ResolveAsync(new Guid("CF85F4DC-1766-4EB8-BDBB-4B29872D9479")));
        }
            public async Task Should_Append_To_Domain_Event_Store()
            {
                IDomainEventAsyncStore <TestAggregate, Guid> eventStore = Factory.CreateEventAsyncStore <TestAggregate, Guid>();

                // Create aggregate.
                TestAggregate aggregate = new TestAggregate(Guid.NewGuid());
                await eventStore.SaveAsync(aggregate);

                IDomainEventStream <Guid> stream = await eventStore.GetDomainEventStreamAsync(aggregate.Id);

                Assert.NotNull(stream);
                Assert.Equal(aggregate.Id, stream.AggregateId);
                Assert.Equal(1, stream.DomainEventCount);
            }
        public async Task Can_load_the_requested_version()
        {
            await _eventStoreInitialized;
            var   aggregate = new TestAggregate(_id);

            aggregate.DoSomething();
            aggregate.DoSomething();
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById <TestAggregate>(_id, 2);

            aggregate.Version.Should().Be(2);
        }
Example #26
0
        public void Create_ValidData_ReturnsAggregate()
        {
            //Arrange
            var guid = Guid.Parse("5ffdfca6-2cb6-4a22-8943-339a65298a2b");

            //Act
            var ta = TestAggregate.Create(TestAggregateId.FromGuid(guid), StringValue.FromString("testtest"), BoolValue.FromBool(true));

            //Assert
            Assert.IsNotNull(ta);
            Assert.AreEqual(guid, ta.Id);
            Assert.AreEqual("testtest", ta.MyString.Value);
            Assert.AreEqual(true, ta.MyBool.Value);
        }
        public GetNotSnapshotableAggregateTest()
        {
            var eventStore = new TestEventStore();

            _snapshotStore = new TestSnapshotStore();
            var snapshotStrategy   = new DefaultSnapshotStrategy(_snapshotStore);
            var repository         = new SnapshotRepository(_snapshotStore, snapshotStrategy, new Repository(eventStore), eventStore);
            var eventStoreSettings = new TestEventStoreSettings {
                SessionLockEnabled = false
            };
            var session = new Session(repository, eventStoreSettings, null);

            _aggregate = session.GetAsync <TestAggregate>(Guid.NewGuid().ToString()).Result;
        }
Example #28
0
            public void Should_Invoke_Multiple_Registered_Domain_Event_Handlers()
            {
                TestDomainEventHandler handler1 = new TestDomainEventHandler(_testOutput);
                TestDomainEventHandler handler2 = new TestDomainEventHandler(_testOutput);
                TestDomainEventHandler handler3 = new TestDomainEventHandler(_testOutput);

                IEventSourcedAggregateRepository <TestAggregate, Guid> repository = Factory.CreateTestAggregateRepository(reg =>
                {
                    reg.Register <TestAggregateCreatedEvent>(() => handler1);
                    reg.Register <OperationExecutedEvent>(() => handler1);
                    reg.Register <TestAggregateCreatedEvent>(() => handler2);
                    reg.Register <OperationExecutedEvent>(() => handler2);
                    reg.Register <TestAggregateCreatedEvent>(() => handler3);
                    reg.Register <OperationExecutedEvent>(() => handler3);
                });

                TestAggregate aggregate = new TestAggregate(Guid.NewGuid());

                aggregate.ExecuteSomeOperation("Test Operation");
                repository.Save(aggregate);

                // Event may not have yet been handled in background.
                Thread.Sleep(500);

                // Aggregate should be stored.
                TestAggregate storedAggregate = repository.GetById(aggregate.Id);

                Assert.Equal(aggregate.Id, storedAggregate.Id);

                // Handler1 should have 2 events.
                // 1. TestAggregateCreated
                // 2. TestAggregateModified
                Assert.Equal(2, handler1.HandledEvents.Count);
                Assert.Contains(handler1.HandledEvents, (e) => e is TestAggregateCreatedEvent);
                Assert.Contains(handler1.HandledEvents, (e) => e is OperationExecutedEvent);

                // Handler2 should have 2 events.
                // 1. TestAggregateCreated
                // 2. TestAggregateModified
                Assert.Equal(2, handler2.HandledEvents.Count);
                Assert.Contains(handler2.HandledEvents, (e) => e is TestAggregateCreatedEvent);
                Assert.Contains(handler2.HandledEvents, (e) => e is OperationExecutedEvent);

                // Handler3 should have 2 events.
                // 1. TestAggregateCreated
                // 2. TestAggregateModified
                Assert.Equal(2, handler3.HandledEvents.Count);
                Assert.Contains(handler3.HandledEvents, (e) => e is TestAggregateCreatedEvent);
                Assert.Contains(handler3.HandledEvents, (e) => e is OperationExecutedEvent);
            }
        public void When_cancel_existing_scheduled_future_event()
        {
            _aggregate = new TestAggregate(Guid.NewGuid());
            var testValue = "value D";

            _aggregate.ScheduleInFuture(DateTime.Now.AddSeconds(400), testValue);
            _aggregate.ScheduleInFuture(DateTime.Now.AddSeconds(400), "test value E");

            _futureEventA = _aggregate.GetEvents <FutureEventScheduledEvent>().First();
            _futureEvent_out_of_criteria = _aggregate.GetEvents <FutureEventScheduledEvent>().Skip(1).First();

            _aggregate.ClearEvents();
            _aggregate.CancelFutureEvents(testValue);
        }
        public async Task Should_persist_events()
        {
            var aggregate = new TestAggregate(_id);
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id);
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id);

            aggregate.Version.Should().Be(2);
        }
Example #31
0
        public void AddItem()
        {
            var sut = new TestAggregate(100);

            sut.AddItem("Description", 1, 10.00, true);

            Assert.AreEqual(2, sut.Events.Count, "Events");
            Assert.AreEqual(2, sut.Version, "Version");
            Assert.AreEqual(1, sut.Items.Count, "Items");
            Assert.AreEqual("Description", sut.Items[0].Description, "Description");
            Assert.AreEqual(1, sut.Items[0].Quantity, "Quantity");
            Assert.AreEqual(10.00, sut.Items[0].Price, "Price");
            Assert.AreEqual(true, sut.Items[0].Taxable, "Taxable");
        }
 public void ThrowsOnRequestingSpecificVersionHigherThanExists()
 {
     foreach (var repo in _repos)
     {
         var id   = Guid.NewGuid();
         var tAgg = new TestAggregate(id);
         tAgg.RaiseBy(1);
         tAgg.RaiseBy(1);
         tAgg.RaiseBy(1);
         tAgg.RaiseBy(1); //v4
         repo.Save(tAgg, Guid.NewGuid(), h => { });
         Assert.Throws <AggregateVersionException>(() => repo.GetById <TestAggregate>(id, 50));
     }
 }
Example #33
0
        public void can_replay_all()
        {
            foreach (var repo in _repos)
            {
                var r = repo as MockEventStoreRepository;
                if (r == null)
                {
                    continue;
                }
                var q = new TestQueue();
                r.Subscribe(q);

                var id1  = Guid.NewGuid();
                var tAgg = new TestAggregate(id1);
                tAgg.RaiseBy(1);
                tAgg.RaiseBy(2);
                tAgg.RaiseBy(3);
                repo.Save(tAgg, Guid.NewGuid(), h => { });

                var id2   = Guid.NewGuid();
                var tAgg2 = new TestAggregate(id2);
                tAgg2.RaiseBy(4);
                tAgg2.RaiseBy(5);
                tAgg2.RaiseBy(6);
                repo.Save(tAgg2, Guid.NewGuid(), h => { });

                Assert.Equal(8, q.Messages.Count);
                var bus = new InMemoryBus("all");
                var q2  = new TestQueue(bus);
                r.ReplayAllOnto(bus);
                q2.Messages
                .AssertNext <TestAggregateMessages.NewAggregate>(
                    correlationId: id1)
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 1, "Event mismatch wrong amount")
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 2, "Event mismatch wrong amount")
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 3, "Event mismatch wrong amount")
                .AssertNext <TestAggregateMessages.NewAggregate>(
                    correlationId: id2)
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 4, "Event mismatch wrong amount")
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 5, "Event mismatch wrong amount")
                .AssertNext <TestAggregateMessages.Increment>(
                    m => m.Amount == 6, "Event mismatch wrong amount")
                .AssertEmpty();
            }
        }
Example #34
0
        public When_saving_same_aggregate_in_parallel()
        {
            _cache = new TestMemoryCache();
            // This will clear the cache between runs.
            //var cacheKeys = _cache. (.Select(kvp => kvp.Key).ToList();
            //foreach (var cacheKey in cacheKeys)
            //    MemoryCache.Default.Remove(cacheKey);

            _testStore = new TestInMemoryEventStore();
            _rep1      = new CacheRepository(new Repository(_testStore), _testStore, _cache);
            _rep2      = new CacheRepository(new Repository(_testStore), _testStore, _cache);

            _aggregate = new TestAggregate(Guid.NewGuid());
            _rep1.Save(_aggregate);

            var t1 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep1.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep1.Save(aggregate);
                }
            });

            var t2 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep2.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep2.Save(aggregate);
                }
            });
            var t3 = new Task(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    var aggregate = _rep2.Get <TestAggregate>(_aggregate.Id);
                    aggregate.DoSomething();
                    _rep2.Save(aggregate);
                }
            });

            t1.Start();
            t2.Start();
            t3.Start();

            Task.WaitAll(t1, t2, t3);
        }
Example #35
0
        public async Task DeleteTestAggregate_DeletesRow()
        {
            var testId             = Guid.NewGuid();
            var savedTestAggregate = new TestAggregate(testId);
            await _repository.SaveTestAggregate(savedTestAggregate);

            await _repository.DeleteTestAggregate(testId);

            var rows = await _fixture.DbContext.Events
                       .Where(e => e.StreamId == testId)
                       .ToListAsync();

            rows.Should().HaveCount(0);
        }
Example #36
0
        public void ShouldNotSaveSnapshotWithOneExistingSnapshot()
        {
            // ARRANGE
            var testAggregate = new TestAggregate(Guid.NewGuid());

            // ACT
            // Publish 7 events. This should create a snapshot
            testAggregate.PublishInitialTestEvent();
            testAggregate.PublishAddressTestEvent();
            testAggregate.PublishInitialTestEvent();

            // ASSERT
            Assert.AreEqual(8, testAggregate.GetUncommittedEvents().Count);
        }
Example #37
0
 public When_saving_fails()
 {
     _cache     = new MemoryCache();
     _testRep   = new TestRepository();
     _rep       = new CacheRepository(_testRep, new TestInMemoryEventStore(), _cache);
     _aggregate = _testRep.Get <TestAggregate>(Guid.NewGuid()).Result;
     _aggregate.DoSomething();
     _testRep.Throw = true;
     try
     {
         _rep.Save(_aggregate).Wait();
     }
     catch (Exception) { }
 }
        public void Given_a_10000_events_large_aggregate()
        {
            var historyTypes = Seq.OfTypes <Ec1>()
                               .Concat(
                1.Through(10)
                .SelectMany(
                    index => 1.Through(996)
                    .Select(_ => typeof(E1))
                    .Concat(Seq.OfTypes <E2, E4, E6, E8>()))).ToList();

            var aggregate = TestAggregate.FromEvents(DummyTimeSource.Now, Guid.NewGuid(), historyTypes);

            _history = aggregate.History.Cast <AggregateRootEvent>().ToList();
        }
Example #39
0
        public void SetUp()
        {
            Fixture.Inject <ITransientFaultHandler <IOptimisticConcurrencyRetryStrategy> >(
                new TransientFaultHandler <IOptimisticConcurrencyRetryStrategy>(
                    Fixture.Create <ILog>(),
                    new OptimisticConcurrencyRetryStrategy(new EventFlowConfiguration())));

            _resolverMock   = InjectMock <IResolver>();
            _eventStoreMock = InjectMock <IEventStore>();
            _testAggregate  = new TestAggregate(TestId.New);

            _eventStoreMock
            .Setup(s => s.LoadAggregateAsync <TestAggregate, TestId>(It.IsAny <TestId>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(_testAggregate));
        }
Example #40
0
        public AggregateProjectorTest()
        {
            var id        = new TestId();
            var aggregate = new TestAggregate(id);

            aggregate.AddEvent1();
            aggregate.AddEvent2();
            _aggregate   = aggregate;
            _projections = new List <BaseTestProjection>
            {
                new PartialProjection(),
                new IgnoringPartialProjection(),
                new FullProjection()
            };
        }
Example #41
0
        public void ChangeItem()
        {
            var sut = new TestAggregate(100);

            sut.AddItem("Description", 1, 10.00, true);

            sut.ChangeItem(1, "New Description");
            sut.ChangeItem(1, 10);

            Assert.AreEqual(4, sut.Events.Count, "Events");
            Assert.AreEqual(4, sut.Version, "Version");
            Assert.AreEqual(1, sut.Items.Count, "Items");
            Assert.AreEqual("New Description", sut.Items[0].Description, "Description");
            Assert.AreEqual(10, sut.Items[0].Quantity, "Quantity");
        }
        public async Task Can_create_save_load_and_update()
        {
            var id = "someaggregate-" + Guid.NewGuid();
            var aggregate = new TestAggregate(id);
            aggregate.DoSomething();
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(id);
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(id);

            aggregate.Version.Should().Be(3);
        }
        public async Task Can_create_save_load_and_update()
        {
            await _eventStoreInitialized;
            var aggregate = new TestAggregate(_id);
            aggregate.DoSomething();
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id);
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id);

            aggregate.Version.Should().Be(3);
        }
        public void ItShouldWriteEventsProperly()
        {
            var eventStoreConnection = EventStoreConnection.Create();
            eventStoreConnection.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113));

            var getEventStore = new GetEventStore(eventStoreConnection);

            var testAggregate = new TestAggregate() {Id = Guid.NewGuid()};
            getEventStore.SaveEventsFor<TestAggregate>(testAggregate.Id, ExpectedVersion.Any, new List<Event>(){new Tested(Guid.NewGuid()){Prop = 1}});

            var readEvents = getEventStore.LoadEventsFor<TestAggregate>(testAggregate.Id);

            Assert.AreEqual(1, readEvents.Count());

            var resolvedEvent = readEvents.First();
            Assert.AreEqual(1, ((Tested) resolvedEvent).Prop);
        }
Example #45
0
        public void Storing_aggregate_should_preserve_values()
        {
            Guid aggregateId = Guid.NewGuid();
            Guid commandId = Guid.NewGuid();
            var commandMetadata = new CommandMetadata
                                      {
                                          CommandId = commandId,
                                          TargetType = typeof(TestAggregate),
                                          TargetId = aggregateId
                                      };
            _facade.Execute(commandMetadata, x => ((TestAggregate) x).TestMethod("Simon"));

            var restoredRoot = new TestAggregate(aggregateId);
             _repository.Load(restoredRoot, aggregateId, null);

            Assert.AreEqual("Simon", restoredRoot.HelloText);
        }
        public void AggregateCache_GetByIdAsyncUsesACachedVersion()
        {
            var guid = Guid.NewGuid();
            var testAggregate = new TestAggregate();
            var eventStore = new Mock<IEventStore>();
            eventStore.Setup(x => x.GetByIdAsync<TestAggregate>(guid)).Verifiable();

            var repo = new Mock<IRepository<TestAggregate>>();
            repo.Setup(x => x.GetByIdAsync(guid)).Returns(Task.FromResult<TestAggregate>(testAggregate)).Verifiable();
            var funcWasCalled = false;
            Func<Type, object> func = (x) => { funcWasCalled = true; return repo.Object; };

            AggregateCache.Instance.Configure(eventStore.Object, func);

            TestAggregate result = AggregateCache.Instance.GetByIdAsync<TestAggregate>(guid).Result;

            result.Should().Be(testAggregate);
            funcWasCalled.Should().BeTrue();

            eventStore.Verify(x => x.GetByIdAsync<TestAggregate>(guid), Times.Never);

        }
        public async Task Can_load_the_requested_version()
        {
            await _eventStoreInitialized;
            var aggregate = new TestAggregate(_id);
            aggregate.DoSomething();
            aggregate.DoSomething();
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id, 2);

            aggregate.Version.Should().Be(2);
        }
 public void TestFixtureSetUp()
 {
     var testAggregate = new TestAggregate(id, string.Empty);
     aggregateHelper.StoreTestAggregate(testAggregate);
 }
        public async Task Should_throw_an_exception_on_duplicate_write()
        {
            await _eventStoreInitialized;
            var aggregate = new TestAggregate(_id);

            aggregate.DoSomething();
            aggregate.DoSomething();
            aggregate.DoSomething();
            await _sut.Save(aggregate, Guid.NewGuid());

            aggregate = await _sut.GetById<TestAggregate>(_id, 2);
            aggregate.DoSomething();

            Func<Task> act = () => _sut.Save(aggregate, Guid.NewGuid());

            act.ShouldThrow<Exception>();
        }
Example #50
0
 public TestEntity(TestAggregate parent, TestEntityId identity)
     : base(parent, identity)
 {
 }
        public void AggregateCache_HandleAsyncUsesTheEventStoreIfNoCachedVersion()
        {
            var guid = Guid.NewGuid();
            var testAggregate = new TestAggregate();
            var eventStore = new Mock<IEventStore>();
            eventStore.Setup(x => x.GetByIdAsync<TestAggregate>(guid)).Returns(Task.FromResult<TestAggregate>(testAggregate)).Verifiable();

            var repo = new Mock<IRepository<TestAggregate>>();
            repo.Setup(x => x.GetByIdAsync(guid)).Returns(Task.FromResult<TestAggregate>(null)).Verifiable();
            var funcWasCalled = false;
            Func<Type, object> func = (x) => {
                funcWasCalled = true;
                return repo.Object;
            };

            var @event = new TestEvent();

            AggregateCache.Instance.Configure(eventStore.Object, func);

            AggregateCache.Instance.Awaiting(x => x.HandleAsync<TestAggregate, TestEvent>(guid, @event)).ShouldNotThrow();

            funcWasCalled.Should().BeTrue();

            eventStore.Verify(x => x.GetByIdAsync<TestAggregate>(guid), Times.Once);

            testAggregate.WasApplyEventCalled.Should().BeTrue();

        }
        public void ClearsEventsFromAggregateOnceCommitted()
        {
            var aggregateToSave = new TestAggregate(Guid.NewGuid());
            aggregateToSave.ProduceEvents(10);
            _repo.Save(aggregateToSave, Guid.NewGuid(), d => { });

            Assert.AreEqual(0, ((IAggregate) aggregateToSave).GetUncommittedEvents().Count);
        }
 private static Guid SaveTestAggregateWithoutCustomHeaders(IRepository repository, int numberOfEvents)
 {
     var aggregateToSave = new TestAggregate(Guid.NewGuid());
     aggregateToSave.ProduceEvents(numberOfEvents);
     repository.Save(aggregateToSave, Guid.NewGuid(), d => { });
     return aggregateToSave.Id;
 }
        public void SavesCommitHeadersOnEachEvent()
        {
            var commitId = Guid.NewGuid();
            var aggregateToSave = new TestAggregate(Guid.NewGuid());
            aggregateToSave.ProduceEvents(20);
            _repo.Save(aggregateToSave, commitId, d => {
                d.Add("CustomHeader1", "CustomValue1");
                d.Add("CustomHeader2", "CustomValue2");
            });

            var read = _connection.ReadStreamEventsForward(string.Format("aggregate-{0}", aggregateToSave.Id), 1, 20, false);
            foreach (var serializedEvent in read.Events)
            {
                var parsedMetadata = JObject.Parse(Encoding.UTF8.GetString(serializedEvent.OriginalEvent.Metadata));
                var deserializedCommitId = parsedMetadata.Property("CommitId").Value.ToObject<Guid>();
                Assert.AreEqual(commitId, deserializedCommitId);

                var deserializedCustomHeader1 = parsedMetadata.Property("CustomHeader1").Value.ToObject<string>();
                Assert.AreEqual("CustomValue1", deserializedCustomHeader1);

                var deserializedCustomHeader2 = parsedMetadata.Property("CustomHeader2").Value.ToObject<string>();
                Assert.AreEqual("CustomValue2", deserializedCustomHeader2);
            }
        }
Example #55
0
 public void SetUp()
 {
     this.aggregate = new TestAggregate();
 }
 public void it_should_throw_duplicate_key_exception()
 {
     var testAggregate = new TestAggregate(id, string.Empty);
     aggregateHelper.StoreTestAggregate(testAggregate);
 }