Esempio n. 1
0
        public async Task Should_create_a_state_instance()
        {
            // Arrange (Given)
            var harness = new InMemoryTestHarness();
            var fileHandlerStateMachine = new FileHandlerStateMachine();
            var saga = harness.StateMachineSaga <FileHandlerState, FileHandlerStateMachine>(fileHandlerStateMachine);

            await harness.Start();

            try
            {
                var fileId = NewId.NextGuid();

                await harness.Bus.Publish <FileInfoSubmitted>(new
                {
                    FileId    = fileId,
                    Timestamp = InVar.Timestamp,
                    FileName  = "filename.file",
                    Folder    = "c:/folder/"
                });

                var instanceID = await saga.Exists(fileId, x => x.Submitted);

                var instance = saga.Sagas.Contains(instanceID.Value);

                Assert.NotNull(instanceID);
                Assert.True(saga.Created.Select(x => x.CorrelationId == fileId).Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 2
0
        public async Task Should_insert_new_state_instance_on_submitted()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderSubmitted>(new
                {
                    OrderId         = orderId,
                    ExternalOrderId = "00000001"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                var instance = saga.Sagas.Contains(instanceId.Value);
                Assert.That(instance.ExternalOrderId, Is.EqualTo("00000001"));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public SagaSampleStateMachineTests(DefaultWebHostTestFixture fixture, ITestOutputHelper output)
        {
            _testOffset = TimeSpan.Zero;
            _harness    = new InMemoryTestHarness();
            _harness.OnConfigureInMemoryBus += ConfigureInMemoryBus;
            var machine = new SagaSampleStateMachine();

            _stateMachineSagaTestHarness = _harness.StateMachineSaga <SagaSampleInstanceState, SagaSampleStateMachine>(machine);
            _harness.Start().Wait();
            fixture.Output = output;
            _client        = fixture.CreateClient();
            _fixture       = fixture;
            _output        = output;

            var inputQueueAddress = _harness.InputQueueAddress;
            var requestClient     = _harness.CreateRequestClient <SagaStatusRequestedEvent>();

            MockedObjects.SagaStatusRequestClient.Setup(e => e.GetResponse <SagaStatus, SagaStatusNotFound>(It.IsAny <SagaStatusRequestedEvent>(), It.IsAny <CancellationToken>(), It.IsAny <RequestTimeout>()))
            .Returns((SagaStatusRequestedEvent o, CancellationToken token, RequestTimeout timeout) =>
            {
                return(requestClient.GetResponse <SagaStatus, SagaStatusNotFound>(o));
            });

            MockedObjects.IPublishEndpoint.Setup(e => e.Publish(It.IsAny <SagaStartedEvent>(), It.IsAny <CancellationToken>()))
            .Returns((SagaStartedEvent o, CancellationToken token) =>
            {
                return(_harness.Bus.Publish(o));
            });
        }
Esempio n. 4
0
        public async Task Should_handle_the_initial_state()
        {
            var harness = new InMemoryTestHarness();
            StateMachineSagaTestHarness <Instance, TestStateMachine> saga = harness.StateMachineSaga <Instance, TestStateMachine>(_machine);

            Guid sagaId = Guid.NewGuid();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new Start
                {
                    CorrelationId = sagaId
                });

                Assert.IsTrue(harness.Consumed.Select <Start>().Any(), "Message not received");

                Instance instance = saga.Created.Contains(sagaId);
                Assert.IsNotNull(instance, "Saga instance not found");

                Assert.AreEqual(instance.CurrentState, _machine.Running);
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 5
0
        public async Task Should_create_a_state_instance()
        {
            var orderStateMachine = new OrderStateMachine();
            var harness           = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(new OrderStateMachine());

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <OrderSubmitted>(new {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "123456"
                });

                var instance = saga.Created.Contains(orderId);
                await saga.Exists(orderId, x => x.Submitted); //race condtion wait for state change

                Assert.True(saga.Created.Select(x => x.CorrelationId == orderId).Any());

                Assert.NotNull(instance);
                Assert.Equal(orderStateMachine.Submitted.Name, instance.CurrentState);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_create_a_state_instance()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness();
            var saga    = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                var instance = saga.Sagas.Contains(instanceId.Value);
                Assert.That(instance.CustomerNumber, Is.EqualTo("12345"));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_respond_to_status_checks()
        {
            var harness           = new InMemoryTestHarness();
            var orderStateMachine = new OrderStateMachine();
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);
            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();
                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = customerNumber
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);
                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);
                var requestClient = await harness.ConnectRequestClient <CheckOrder>();

                var response = await requestClient.GetResponse <OrderStatus>(new
                {
                    OrderId = orderId
                });

                Assert.That(response.Message.State, Is.EqualTo(orderStateMachine.Submitted.Name));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Test_thing()
        {
            var harness = new InMemoryTestHarness();

            harness.OnConfigureInMemoryBus += Harness_OnConfigureInMemoryBus;
            var saga     = harness.StateMachineSaga(new TestSagaStateMachine(), new InMemorySagaRepository <TestSagaState>(), "saga");
            var consumer = harness.Consumer <TestConsumer>("consumer");

            await harness.Start();

            try
            {
                var values   = Enumerable.Range(0, 16).Select(i => Guid.NewGuid()).ToArray();
                var response = await harness.Bus.Request <TestSagaRequest, TestSagaResponse>(new TestSagaRequest()
                {
                    CorrelationId = Guid.NewGuid(), Values = values
                });

                response.Message.Values.Should().HaveCount(16);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_create_a_state_instance()
        {
            var harness = new InMemoryTestHarness();
            StateMachineSagaTestHarness <OrderState, OrderStateMachine> saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(new OrderStateMachine());

            await harness.Start();

            try
            {
                Guid orderId = NewId.NextGuid();

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Guid?instanceId = await saga.Exists(orderId, x => x.Submitted);

                instanceId.Should().Be(orderId);

                OrderState instance = saga.Sagas.Contains(instanceId.Value);
                instance.CustomerNumber.Should().Be("12345");
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 10
0
        public async Task Should_handle_the_stop_state()
        {
            var harness = new InMemoryTestHarness();
            StateMachineSagaTestHarness <Instance, TestStateMachine> saga = harness.StateMachineSaga <Instance, TestStateMachine>(_machine);

            var sagaId = Guid.NewGuid();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new Start { CorrelationId = sagaId });

                await harness.InputQueueSendEndpoint.Send(new Stop { CorrelationId = sagaId });

                Assert.IsTrue(harness.Consumed.Select <Start>().Any(), "Start not received");
                Assert.IsTrue(harness.Consumed.Select <Stop>().Any(), "Stop not received");

                var instance = saga.Created.ContainsInState(sagaId, _machine, _machine.Final);
                Assert.IsNotNull(instance, "Saga instance not found");
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 11
0
 public async Task SetUp()
 {
     _harness = new InMemoryTestHarness {
         TestTimeout = TimeSpan.FromSeconds(5)
     };
     _orderStateMachine = new OrderStateMachine();
     _saga = _harness.StateMachineSaga <OrderState, OrderStateMachine>(_orderStateMachine);
     await _harness.Start();
 }
        public async Task InitializeTestHarness()
        {
            _harness     = new InMemoryTestHarness();
            _machine     = new LifeStateMachine();
            _sagaHarness = _harness.StateMachineSaga <LifeState, LifeStateMachine>(_machine);

            // Note: This style can be used in old test environments, where InitializeTestHarness may not be async.
            //_harness.Start().Wait();
            await _harness.Start();
        }
Esempio n. 13
0
        public StateMachine_Specs()
        {
            _sagaId       = Guid.NewGuid();
            _assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

            _harness    = new InMemoryTestHarness();
            _repository = new EventStoreSagaRepository <Instance>(EventStoreFixture.Connection);
            var machine = new TestStateMachine();

            _harness.StateMachineSaga(machine, _repository);
        }
        public virtual async Task BeforeEachTest()
        {
            TestHarness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(4)
            };
            StateMachine    = new GreetingsStateMachine();
            SagaTestHarness =
                TestHarness.StateMachineSaga <GreetingsState, GreetingsStateMachine>(StateMachine);

            await TestHarness.Start();
        }
        public async Task Should_update_info_when_submitted_after_any_other_state()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(3)
            };
            var orderStateMachine = new OrderStateMachine();
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = Guid.NewGuid();
                await harness.Bus.Publish <OrderSubmittedEvent>(new
                {
                    OrderId = orderId
                });

                var instance = await saga.Exists(orderId, x => x.Submitted);

                instance.Should().NotBeNull();

                await harness.Bus.Publish <OrderAcceptedEvent>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                });

                instance = await saga.Exists(orderId, x => x.Accepted);

                instance.Should().NotBeNull();

                var timestamp = new DateTime(2020, 01, 01);
                await harness.Bus.Publish <OrderSubmittedEvent>(new
                {
                    OrderId        = orderId,
                    CustomerNumber = "0987",
                    Timestamp      = timestamp
                });

                instance = await saga.Exists(orderId, x => x.Accepted);

                instance.Should().NotBeNull();

                var data = saga.Sagas.Contains(orderId);
                data.SubmitDate.Should().Be(timestamp);
                data.CustomerNumber.Should().Be("0987");
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task LivingSearchStateMachine_Should_Be_Tested()
        {
            var config = new MessageBusConfig
            {
                PubmedParserQueueName = "pubmedParser",
                PubmedSearchQueueName = "pubmedSearch",
                RabbitMqConfig        = new RabbitMqConfig
                {
                    SchemeName = "rabbitmq",
                    Hostname   = "localhost",
                    Username   = "******",
                    Password   = "******"
                }
            };
            var machine = new LivingSearchStateMachine(config);

            var harness     = new InMemoryTestHarness();
            var sagaHarness = harness.StateMachineSaga <LivingSearchState, LivingSearchStateMachine>(machine);
            var saga        = harness.Saga <LivingSearchState>();

            await harness.Start();

            try
            {
                Guid sagaId = NewId.NextGuid();

                await harness.Bus.Publish <ILivingSearchEnabledOnProjectEvent>(new
                {
                    ProjectId              = default(Guid),
                    LivingSearchId         = sagaId,
                    SearchString           = default(string),
                    UpdateInterval         = default(int),
                    BatchSize              = default(int),
                    SearchEngineName       = default(string),
                    SystematicSearchPrefix = default(string)
                });

                // did the endpoint consume the message
                Assert.NotNull(harness.Sent);

                Assert.True(harness.Consumed.Select <ILivingSearchEnabledOnProjectEvent>().Any());

                // did the actual consumer consume the message
                Assert.True(sagaHarness.Consumed.Select <ILivingSearchEnabledOnProjectEvent>().Any());

                var instance = sagaHarness.Created.ContainsInState(sagaId, machine, machine.Initial);
                Assert.NotNull(instance);
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 17
0
        public StateMachine_Specs(EventStoreFixture fixture)
        {
            _fixture = fixture;
            _sagaId  = Guid.NewGuid();

            _harness    = new InMemoryTestHarness();
            _repository = new EventStoreSagaRepository <Instance>(_fixture.Connection);
            _machine    = new TestStateMachine();
            _saga       = _harness.StateMachineSaga(_machine, _repository);

            TaskUtil.Await(StartHarness);
        }
Esempio n. 18
0
        public async Task Setup()
        {
            correlationId = Guid.NewGuid();
            stateMachine  = new GameStateMachine(new Mock <ILogger <GameStateMachine> >().Object,
                                                 Options.Create(new RabbitMQConfiguration
            {
                Endpoint = "rabbitmq://localhost"
            }));

            harness         = new InMemoryTestHarness();
            sagaTestHarness = harness.StateMachineSaga <GameSaga, GameStateMachine>(stateMachine);
            await harness.Start();
        }
Esempio n. 19
0
        public async Task Should_respond_when_file_deleted()
        {
            // Arrange (Given)
            var harness = new InMemoryTestHarness();
            var fileHandlerStateMachine = new FileHandlerStateMachine();
            var saga = harness.StateMachineSaga <FileHandlerState, FileHandlerStateMachine>(fileHandlerStateMachine);

            await harness.Start();

            try
            {
                var fileId = NewId.NextGuid();

                await harness.Bus.Publish <FileInfoSubmitted>(new
                {
                    FileId    = fileId,
                    Timestamp = InVar.Timestamp,
                    FileName  = "filename.file",
                    Folder    = "c:/folder/"
                });

                Assert.True(saga.Created.Select(x => x.CorrelationId == fileId).Any());


                var instanceId = await saga.Exists(fileId, x => x.Submitted);

                Assert.NotNull(instanceId);

                var instance = saga.Sagas.Contains(instanceId.Value);

                await harness.Bus.Publish <FileDeletedFromOriginFolder>(new
                {
                    FileId   = fileId,
                    FileName = "filename.file",
                    Folder   = "c:/folder/"
                });

                instanceId = await saga.Exists(fileId, x => x.DeletedFromOriginFolder);

                var requestClient = await harness.ConnectRequestClient <CheckFileInfo>();

                var response = await requestClient.GetResponse <FileStatus>(new { FileId = fileId });

                Assert.Equal(response.Message.State, fileHandlerStateMachine.DeletedFromOriginFolder.Name);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_create_a_state_instance()
        {
            var harness = new InMemoryTestHarness()
            {
                TestTimeout = TimeSpan.FromSeconds(1)
            };
            var orderStateMachine = new OrderStateMachine();
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            var orderId        = NewId.NextGuid();
            var customerNumber = "1234";

            try
            {
                // 아래는 "없는 걸" 테스트 하므로, Timeout 문제 발생함. 따라서 test harness에 timeout 을 주었다.
                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.False);

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId        = orderId,
                    Timestamp      = InVar.Timestamp,
                    CustomerNumber = customerNumber
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);


                // 비동기 코드에 대한 테스트는 항상 Race Condition이 있을 수 있다.
                // 으래 코드는 `Task.Delay()` 가 없으면 실패한다. (테스트 코드가 실행되는 속도가 메시지 처리되는 속도 보다 빠르기 때문)
                // await Task.Delay(TimeSpan.FromSeconds(1));
                // var instance = saga.Created.Contains(orderId);
                // Assert.That(instance, Is.Not.Null);
                // Assert.That(instance.CurrentState, Is.EqualTo(orderStateMachine.Submitted.Name));

                // 따라서, Masstransit Test Harness Saga 는 "특정 saga 가 특정 상태가 되기를 대기 하게 할 수 있다.
                // orderId 의 correlation id 를 가지는 saga 가 submitted 상태에 있을 때 가지 대기
                var instanceId = await saga.Exists(orderId, x => x.Submitted, timeout : null);  // timeout 을 null 로 주면, Test harness의 TestTimeout 값이 사용됨.

                Assert.That(instanceId, Is.Not.Null);

                var instance = saga.Sagas.Contains(instanceId.Value);
                Assert.That(instance.CustomerNumber, Is.EqualTo(customerNumber));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public void Test_BillingMessageMachine_SendMessage(string printJobName, string activityTypeCode, string issueSystemCode)
        {
            // arrange
            var printJobService = MockRepository.GenerateMock <IPrintJobService>();
            var logger          = MockRepository.GenerateMock <IMessageLogger>();
            var harness         = new InMemoryTestHarness();
            var machine         = new BillingMessageMachine(printJobService, logger);
            var saga            = harness.StateMachineSaga <BillingMessageState, BillingMessageMachine>(machine);

            printJobService
            .Expect(p => p.GetPolicyTransactions("A123456", "58f31946b12b441892cd798973aab87e"))
            .Return(Task.FromResult <string>(this.transactionStatusValidXml.ToString()));

            printJobService
            .Expect(p => p.PostPrintJobRequest(Arg.Is("A123456"), Arg.Is("00"), Arg.Is("1"), Arg.Is(printJobName), Arg <string> .Is.Anything, Arg.Is("58f31946b12b441892cd798973aab87e")))
            .Return(Task.FromResult <string>("printed!"));

            var accountActivity = new AccountActivity
            {
                ActivityTypeCode = activityTypeCode,
                Policy           = new Policy
                {
                    PolicyNumber    = "A123456",
                    Mod             = "00",
                    IssueSystemCode = issueSystemCode
                }
            };

            // act
            harness.Start().Wait();

            harness.Bus.Publish <IAccountActivity>(accountActivity).Wait();

            // wait for the publish to do its thing, the Wait() above doesn't guarantee much.
            var receivedMessage = harness.Consumed.Select <IAccountActivity>().FirstOrDefault();

            // assert
            printJobService.VerifyAllExpectations();
            logger.VerifyAllExpectations();

            receivedMessage.Exception.ShouldBeNull();
            harness.Consumed.Count().ShouldEqual(1);
            harness.Published.Count().ShouldEqual(1);
            harness.Sent.Count().ShouldEqual(0);
            saga.Consumed.Count().ShouldEqual(1);

            // cleanup
            harness.Stop().Wait();
        }
Esempio n. 22
0
        public StateMachineSpecs(DynamoDbEventStoreFixture fixture)
        {
            _knownEventTypes = new KnownEventTypes();
            _knownEventTypes.RegisterTypes(typeof(ProcessStarted), typeof(ProcessStopped), typeof(SomeStringAssigned));

            _fixture = fixture;
            _sagaId  = Guid.NewGuid();

            _harness    = new InMemoryTestHarness();
            _repository = new DynamoDbSagaRepository <Instance>(_fixture.Connection, _fixture.Options, _knownEventTypes);
            _machine    = new TestStateMachine();
            _saga       = _harness.StateMachineSaga(_machine, _repository);

            TaskUtil.Await(StartHarness);
        }
        public async Task Should_be_cancelled_when_CustomerAccountClosed()
        {
            var harness = new InMemoryTestHarness()
            {
                TestTimeout = TimeSpan.FromSeconds(1)
            };
            var orderStateMachine = new OrderStateMachine();
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            var orderId        = NewId.NextGuid();
            var customerNumber = "1234";

            try
            {
                // 아래는 "없는 걸" 테스트 하므로, Timeout 문제 발생함. 따라서 test harness에 timeout 을 주었다.
                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.False);

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId        = orderId,
                    Timestamp      = InVar.Timestamp,
                    CustomerNumber = customerNumber
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                await harness.Bus.Publish <CustomerAccountClosed>(new
                {
                    //CustomerId = NewId.NextGuid(), // 상관없는 필드.
                    Timestamp      = InVar.Timestamp,
                    CustomerNumber = customerNumber,
                });

                instanceId = await saga.Exists(orderId, x => x.Cancelled);

                Assert.That(instanceId, Is.Not.Null);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public void Test_BillingMessageMachine_SendMessage_InvalidCode(string printJobName, string activityTypeCode, string issueSystemCode)
        {
            // arrange
            var printJobService = MockRepository.GenerateMock <IPrintJobService>();
            var logger          = MockRepository.GenerateMock <IMessageLogger>();
            var harness         = new InMemoryTestHarness();
            var machine         = new BillingMessageMachine(printJobService, logger);
            var saga            = harness.StateMachineSaga <BillingMessageState, BillingMessageMachine>(machine);

            var accountActivity = new AccountActivity
            {
                ActivityTypeCode = activityTypeCode,
                Policy           = new Policy
                {
                    PolicyNumber    = "A123456",
                    Mod             = "00",
                    IssueSystemCode = issueSystemCode
                }
            };

            // act
            harness.Start().Wait();

            harness.Bus.Publish <IAccountActivity>(accountActivity).Wait();

            // wait for the publish to do its thing, the Wait() above doesn't guarantee much.
            var receivedMessage = harness.Consumed.Select <IAccountActivity>().FirstOrDefault();

            // assert
            var        message     = logger.GetArgumentsForCallsMadeOn <IMessageLogger>(x => x.Log(Arg <Log> .Is.Anything, Arg <string> .Is.Null, Arg <string> .Is.Null, Arg <string> .Is.Null));
            Log        argumentLog = (Log)message[0][0];
            LogMessage logMessage  = argumentLog.Messages[0];

            Assert.AreEqual(logMessage.Category, Constants.Logging.CATEGORY);
            Assert.AreEqual(logMessage.Severity, SeverityType.Information);

            printJobService.AssertWasNotCalled(p => p.GetPolicyTransactions(Arg <string> .Is.Anything, Arg <string> .Is.Anything));
            printJobService.VerifyAllExpectations();
            receivedMessage.Exception.ShouldBeNull();
            harness.Consumed.Count().ShouldEqual(1);
            harness.Published.Count().ShouldEqual(1);
            harness.Sent.Count().ShouldEqual(0);
            saga.Consumed.Count().ShouldEqual(1);

            // cleanup
            harness.Stop().Wait();
        }
        public async Task Should_cancel_order_when_account_closed()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(2)
            };
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                const string customerNumber = "12345";
                await harness.Bus.Publish <OrderSubmittedEvent>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = customerNumber
                });

                saga.Created.Select(x => x.CorrelationId == orderId).Any().Should().BeTrue();

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                instanceId.Should().NotBeNull();

                await harness.Bus.Publish <CustomerAccountClosedEvent>(new
                {
                    CustomerId     = InVar.Id,
                    CustomerNumber = customerNumber
                });

                instanceId = await saga.Exists(orderId, x => x.Cancelled);

                instanceId.Should().NotBeNull();
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_respond_to_status_check_requested_event()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(3)
            };
            var orderStateMachine = new OrderStateMachine();
            var orderSaga         = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();
                await harness.Bus.Publish <OrderSubmittedEvent>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "1234"
                });

                orderSaga.Created
                .Select(s => s.CorrelationId == orderId)
                .Any()
                .Should().BeTrue();

                var instanceId = await orderSaga.Exists(orderId, s => s.Submitted);

                instanceId.Should().NotBeNull();

                var requestClient = await harness.ConnectRequestClient <CheckOrderRequestedEvent>();

                var response = await requestClient.GetResponse <OrderStatusResponse>(new
                {
                    OrderId = orderId
                });

                orderSaga.Consumed.Select <CheckOrderRequestedEvent>().Any().Should().BeTrue();
                response.Message.State.Should().Be(orderStateMachine.Submitted.Name);
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 27
0
        public async Task Should_accept_when_order_is_accepted()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness();
            var saga    = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            EndpointConvention.Map <MyTestCommand>(new Uri("loopback://localhost/my-test-command"));

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                await harness.Bus.Publish <OrderAccepted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                });

                instanceId = await saga.Exists(orderId, x => x.Accepted);

                Assert.That(instanceId, Is.Not.Null);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_respond_to_status_check()
        {
            var harness = new InMemoryTestHarness()
            {
                TestTimeout = TimeSpan.FromSeconds(1)
            };
            var orderStateMachine = new OrderStateMachine();
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            var orderId        = NewId.NextGuid();
            var customerNumber = "1234";

            try
            {
                // 아래는 "없는 걸" 테스트 하므로, Timeout 문제 발생함. 따라서 test harness에 timeout 을 주었다.
                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.False);

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId        = orderId,
                    Timestamp      = InVar.Timestamp,
                    CustomerNumber = customerNumber
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var requestClient = await harness.ConnectRequestClient <CheckOrder>();

                var response = await requestClient.GetResponse <OrderStatus>(new
                {
                    OrderId = orderId
                });

                Assert.That(response.Message.State, Is.EqualTo(orderStateMachine.Submitted.Name));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task SubmitOrderConsumer_Accepted()
        {
            var orderStateMachine = new OrderStateMachine();
            var harness           = new InMemoryTestHarness();

            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);


            try
            {
                await harness.Start();

                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderAcceptedEvent>(new
                {
                    OrderId          = orderId,
                    CreationDateTime = InVar.Timestamp,
                    Amount           = 900
                });

                saga.Created.Select(x => x.CorrelationId == orderId).Any().Should().Be.True();

                var correlationId = await saga.Exists(orderId, x => x.Created);

                correlationId.HasValue.Should().Be.True();

                var instance = saga.Sagas.Contains(correlationId.Value);

                instance.CurrentState.Should().Be.EqualTo("Created");
                instance.CorrelationId.Should().Be.EqualTo(orderId);
                instance.Amount.Should().Be.EqualTo(900);

                harness.Sent.Select <IRequestValidateOrder>().Any().Should().Be.True();
                harness.Published.Select <IRequestValidateOrder>().Any().Should().Be.False();
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_cancel_when_customer_account_closed()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness();
            var saga    = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                await harness.Bus.Publish <ICustomerAccountClosed>(new
                {
                    CustomerId     = InVar.Id,
                    CustomerNumber = "12345"
                });

                instanceId = await saga.Exists(orderId, x => x.Canceled);

                Assert.That(instanceId, Is.Not.Null);
            }
            finally
            {
                await harness.Stop();
            }
        }