public async Task Should_consume_submit_order_command()
        {
            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                // 메시지를 Publish 하고, Response가 필요없는 경우, 그냥 직접 InputQueue 에 메시지를 전송해볼 수 있다.
                // --> 그러면, 정상적인 경우? 라면 등록된 Consumer 가 메시지를 수신하겠지?
                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId        = orderId,
                    Timestamp      = InVar.Timestamp,
                    CustomerNumber = "12345",
                });

                Assert.That(consumer.Consumed.Select <SubmitOrder>().Any(), Is.True);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_Consume_AccountCheckCommand()
        {
            var harness         = new InMemoryTestHarness();
            var consumerHarness = harness.Consumer <ApprovalsSubscriptionsHandler>();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new AccountCheckCommand
                {
                    Id        = Guid.NewGuid().ToString(),
                    ProfileId = Guid.NewGuid().ToString()
                });

                // did the endpoint consume the message
                Assert.True(await harness.Consumed.Any <AccountCheckCommand>());

                // did the actual consumer consume the message
                Assert.True(await consumerHarness.Consumed.Any <AccountCheckCommand>());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_respond_with_rejection_if_test_file()
        {
            // Arrange (Given)
            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer <SubmitFileInfoConsumer>();

            await harness.Start();

            try
            {
                var fileId        = NewId.NextGuid();
                var requestClient = await harness.ConnectRequestClient <SubmitFileInfo>();

                // Act (When)
                var response = await requestClient.GetResponse <FileInfoSubmissionRejected>(new
                {
                    FileId = fileId,
                    InVar.Timestamp,
                    FileName = "TEST.file",
                    Folder   = "c:/folder/"
                });

                // Assert (Then)
                Assert.Equal <Guid>(response.Message.FileId, fileId);
                Assert.True(consumer.Consumed.Select <SubmitFileInfo>().Any());
                Assert.True(harness.Sent.Select <FileInfoSubmissionRejected>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_consume_the_published_event()
        {
            var consumerHarness = _harness.Consumer(() =>
                                                    new SomethingHappenedHandler(NullLogger <SomethingHappenedHandler> .Instance));

            try
            {
                await _harness.Start().ConfigureAwait(false);

                await _harness.InputQueueSendEndpoint.Send <ISomethingHappened>(new {
                    Data      = "something",
                    Timestamp = DateTimeOffset.UtcNow
                }).ConfigureAwait(false);

                // did the endpoint consume the message
                (await _harness.Consumed.Any <ISomethingHappened>().ConfigureAwait(false)).Should().BeTrue();

                // did the actual consumer consume the message
                (await consumerHarness.Consumed.Any <ISomethingHappened>().ConfigureAwait(false)).Should().BeTrue();

                // ensure that no faults were published by the consumer
                (await _harness.Published.Any <Fault <ISomethingHappened> >().ConfigureAwait(false)).Should().BeFalse();
            }
            finally
            {
                await _harness.Stop().ConfigureAwait(false);
            }
        }
        public async void InMemory()
        {
            var counter = new FaultCounter();
            var harness = new InMemoryTestHarness();

            try
            {
                harness.OnConfigureInMemoryBus += cfg =>
                                                  cfg.UseRetry(x =>
                {
                    x.Immediate(1);
                    x.ConnectRetryObserver(new RetryObserver(counter));
                });

                harness.OnConfigureInMemoryReceiveEndpoint += cfg => harness.Handler <PingMessage>(cfg, ctx => throw new Exception());

                await harness.Start();

                var faultHandlerTask = harness.SubscribeHandler <Fault <PingMessage> >();

                await harness.InputQueueSendEndpoint.Send(new PingMessage(), ctx =>
                {
                    ctx.ResponseAddress = harness.BusAddress;
                    ctx.FaultAddress    = harness.BusAddress;
                });

                await faultHandlerTask;

                Assert.Equal(1, counter.Faults);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_consume_submit_order_commands()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            var consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(consumer.Consumed.Select <SubmitOrder>().Any(), Is.True);

                Assert.That(harness.Sent.Select <OrderSubmissionAccepted>().Any(), Is.False);
                Assert.That(harness.Sent.Select <OrderSubmissionRejected>().Any(), Is.False);
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #7
0
        public async Task Should_publish_order_submitted_event()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(3)
            };
            var consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();
                await harness.InputQueueSendEndpoint.Send <SubmitOrderCommand>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    Customer = "1234"
                });

                harness.Published.Select <OrderSubmittedEvent>().Any().Should().BeTrue();
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_publish_order_submitted_event()
        {
            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(await harness.Published.Any <OrderSubmitted>(), Is.True);
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #9
0
        public async Task Should_keep_em_separated()
        {
            var internalHarness = new InMemoryTestHarness("internal");
            var externalHarness = new InMemoryTestHarness("external");

            ConsumerTestHarness <RelayConsumer> internalConsumer = internalHarness.Consumer(() => new RelayConsumer(externalHarness.Bus));
            ConsumerTestHarness <RelayConsumer> externalConsumer = externalHarness.Consumer(() => new RelayConsumer(internalHarness.Bus));

            var realConsumer = internalHarness.Consumer <RealConsumer>();

            await internalHarness.Start();

            try
            {
                await externalHarness.Start();

                try
                {
                    await externalHarness.Bus.Publish(new A());

                    realConsumer.Consumed.Select <A>().Any().ShouldBeTrue();
                }
                finally
                {
                    await externalHarness.Stop();
                }
            }
            finally
            {
                await internalHarness.Stop();
            }
        }
        public async Task Should_publish_fileinfo_submitted_event()
        {
            // Arrange (Given)
            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer <SubmitFileInfoConsumer>();

            await harness.Start();

            try
            {
                var fileId = NewId.NextGuid();

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

                // Assert (Then)
                Assert.True(harness.Published.Select <FileInfoSubmitted>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_consume_submit_fileinfo_commands()
        {
            // Arrange (Given)
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            var consumer = harness.Consumer <SubmitFileInfoConsumer>();

            await harness.Start();

            try
            {
                var fileId = NewId.NextGuid();

                // Act (When)
                await harness.InputQueueSendEndpoint.Send <SubmitFileInfo>(new
                {
                    FileId = fileId,
                    InVar.Timestamp,
                    FileName = "filename.file",
                    Folder   = "c:/folder/"
                });

                // Assert (Then)
                Assert.True(consumer.Consumed.Select <SubmitFileInfo>().Any());
                Assert.False(harness.Sent.Select <FileInfoSubmissionAccepted>().Any());
                Assert.False(harness.Sent.Select <FileInfoSubmissionRejected>().Any());
            }
            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 <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);

                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 Should_respond_with_rejected_if_test()
        {
            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

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

                var response = await requestClient.GetResponse <OrderSubmissionRejected>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "TEST123"
                });

                Assert.That(response.Message.OrderId, Is.EqualTo(orderId));

                Assert.That(consumer.Consumed.Select <SubmitOrder>().Any(), Is.True);

                Assert.That(harness.Sent.Select <OrderSubmissionRejected>().Any(), Is.True);
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #15
0
        public async Task If_transformation_success_AssetReady_event_is_success()
        {
            // Arrange
            repositoryPackage.ArchiveRecordId = "113";
            assetManager.Setup(e => e.ConvertPackage("113", AssetType.Gebrauchskopie, false, It.IsAny <RepositoryPackage>()))
            .ReturnsAsync(new PackageConversionResult {
                Valid = true, FileName = "113.zip"
            });
            cacheHelper.Setup(e => e.GetFtpUrl(It.IsAny <IBus>(), It.IsAny <CacheRetentionCategory>(), It.IsAny <string>()))
            .ReturnsAsync("ftp://UsageCopyPublic:@someurl:9000/113");
            cacheHelper.Setup(e => e.SaveToCache(It.IsAny <IBus>(), It.IsAny <CacheRetentionCategory>(), It.IsAny <string>()))
            .ReturnsAsync(true);

            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer(() => new TransformPackageConsumer(assetManager.Object, cacheHelper.Object, harness.Bus));

            harness.Consumer(() => assetReady.Object);

            await harness.Start();

            try
            {
                // Act
                await harness.InputQueueSendEndpoint.Send <ITransformAsset>(new TransformAsset
                {
                    AssetType         = AssetType.Gebrauchskopie,
                    RepositoryPackage = repositoryPackage,
                    CallerId          = "2223",
                    RetentionCategory = CacheRetentionCategory.UsageCopyPublic
                });


                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <ITransformAsset>());

                // did the actual consumer consume the message
                Assert.That(await consumer.Consumed.Any <ITransformAsset>());

                // the consumer publish the event
                Assert.That(await harness.Published.Any <IAssetReady>());

                // ensure that no faults were published by the consumer
                Assert.That(await harness.Published.Any <Fault <IAssetReady> >(), Is.False);

                // did the actual consumer consume the message
                Assert.That(await harness.Consumed.Any <IAssetReady>());
                var message = harness.Consumed.Select <IAssetReady>().FirstOrDefault();

                // Assert
                Assert.That(message != null);
                message.Context.Message.ArchiveRecordId.Should().Be("113");
                message.Context.Message.CallerId = "2223";
                message.Context.Message.Valid.Should().Be(true);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task If_AppendPackage_failed_Sync_process_is_set_to_failed()
        {
            // Arrange
            try
            {
                var ar = new ArchiveRecord {
                    ArchiveRecordId = "345"
                };
                var mutationId   = 666;
                var errMsg       = "Some error message";
                var appendResult = new RepositoryPackageResult {
                    Valid = false, Success = false, ErrorMessage = errMsg
                };
                repositoryManager.Setup(e => e.AppendPackageToArchiveRecord(It.IsAny <ArchiveRecord>(), It.IsAny <long>(), It.IsAny <int>()))
                .ReturnsAsync(appendResult);

                var appendPackageConsumer = harness.Consumer(() => new AppendPackageConsumer(repositoryManager.Object));
                harness.Consumer(() => archiveRecordAppendPackageConsumer.Object);

                await harness.Start();

                // Act
                await harness.InputQueueSendEndpoint.Send <IArchiveRecordAppendPackage>(new
                {
                    ArchiveRecord = ar,
                    MutationId    = mutationId
                });

                // Wait for the results

                Assert.That(await harness.Consumed.Any <IArchiveRecordAppendPackage>());
                Assert.That(await appendPackageConsumer.Consumed.Any <IArchiveRecordAppendPackage>());

                Assert.That(await harness.Published.Any <IArchiveRecordUpdated>());
                var context = harness.Published.Select <IArchiveRecordUpdated>().First().Context;

                // Assert
                context.Message.ActionSuccessful.Should().Be(false);
                context.Message.MutationId.Should().Be(mutationId);
                context.Message.ErrorMessage.Should().Be(errMsg);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task MassTransitInstrumentationConsumerAndHandlerTest()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using (Sdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .AddMassTransitInstrumentation()
                   .Build())
            {
                var harness         = new InMemoryTestHarness();
                var consumerHarness = harness.Consumer <TestConsumer>();
                var handlerHarness  = harness.Handler <TestMessage>();
                await harness.Start();

                try
                {
                    await harness.InputQueueSendEndpoint.Send <TestMessage>(new
                    {
                        Text = "Hello, world!",
                    });

                    Assert.True(await harness.Consumed.SelectAsync <TestMessage>().Any());
                    Assert.True(await consumerHarness.Consumed.SelectAsync <TestMessage>().Any());
                    Assert.True(await handlerHarness.Consumed.SelectAsync().Any());
                }
                finally
                {
                    await harness.Stop();
                }
            }

            Assert.Equal(10, activityProcessor.Invocations.Count);

            var sends    = this.GetActivitiesFromInvocationsByOperationName(activityProcessor.Invocations, OperationName.Transport.Send);
            var receives = this.GetActivitiesFromInvocationsByOperationName(activityProcessor.Invocations, OperationName.Transport.Receive);
            var consumes = this.GetActivitiesFromInvocationsByOperationName(activityProcessor.Invocations, OperationName.Consumer.Consume);
            var handles  = this.GetActivitiesFromInvocationsByOperationName(activityProcessor.Invocations, OperationName.Consumer.Handle);

            foreach (var activity in sends)
            {
                Assert.Equal("SEND /input_queue", activity.DisplayName);
            }

            foreach (var activity in receives)
            {
                Assert.Equal("RECV /input_queue", activity.DisplayName);
            }

            foreach (var activity in consumes)
            {
                Assert.Equal("CONSUME OpenTelemetry.Contrib.Instrumentation.MassTransit.Tests.TestConsumer", activity.DisplayName);
            }

            foreach (var activity in handles)
            {
                Assert.Equal("HANDLE TestMessage/OpenTelemetry.Contrib.Instrumentation.MassTransit.Tests", activity.DisplayName);
            }
        }
예제 #18
0
        public async Task If_PrepareForTransformation_failed_Sync_process_is_set_to_failed()
        {
            try
            {
                // Arrange
                var ar = new ArchiveRecord
                {
                    ArchiveRecordId = "112", PrimaryData = null // This provokes a failure
                };
                var orderId = 777;


                var consumer = harness.Consumer(() => new PrepareForTransformationConsumer(assetManager.Object, scanProcessorMock.Object, transformEngineMock.Object,
                                                                                           preparationEngine.Object));
                await harness.Start();

                // Act
                await harness.InputQueueSendEndpoint.Send(new PrepareForTransformationMessage()
                {
                    AssetType             = AssetType.Gebrauchskopie,
                    RepositoryPackage     = repositoryPackage,
                    CallerId              = "123",
                    OrderItemId           = orderId,
                    ProtectWithPassword   = false,
                    RetentionCategory     = CacheRetentionCategory.UsageCopyPublic,
                    PrimaerdatenAuftragId = 458
                });

                // Wait for the results
                Assert.That(await harness.Consumed.Any <PrepareForTransformationMessage>());
                Assert.That(await consumer.Consumed.Any <PrepareForTransformationMessage>());

                Assert.That(await harness.Published.Any <IAssetReady>());
                var context = harness.Published.Select <IAssetReady>().First().Context;

                // Assert
                context.Message.ArchiveRecordId.Should().Be(ar.ArchiveRecordId);
                context.Message.OrderItemId.Should().Be(orderId);
                context.Message.Valid.Should().BeFalse();
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #19
0
        public async Task If_Package_not_valid_Sync_process_is_set_to_failed()
        {
            // Arrange
            var harness = new InMemoryTestHarness();

            try
            {
                var ar = new ArchiveRecord {
                    ArchiveRecordId = "344"
                };
                var mutationId   = 999;
                var errMsg       = "Some other error message";
                var appendResult = new RepositoryPackageInfoResult {
                    Valid = false, Success = true, ErrorMessage = errMsg
                };
                repositoryManager.Setup(e => e.ReadPackageMetadata(It.IsAny <string>(), It.IsAny <string>())).Returns(appendResult);

                var readMetadataConsumer = harness.Consumer(() => readPackageMetadataConsumer.Object);
                harness.Consumer(() => new ReadPackageMetadataConsumer(repositoryManager.Object));
                harness.Consumer(() => readPackageMetadataConsumer.Object);

                await harness.Start();

                // Act
                await harness.InputQueueSendEndpoint.Send <IArchiveRecordAppendPackageMetadata>(new
                {
                    ArchiveRecord = ar,
                    MutationId    = mutationId
                });


                // Assert
                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <IArchiveRecordAppendPackageMetadata>());

                // did the actual consumer consume the message
                Assert.That(await readMetadataConsumer.Consumed.Any <IArchiveRecordAppendPackageMetadata>());

                // the consumer publish the event
                Assert.That(await harness.Published.Any <IArchiveRecordUpdated>());

                // ensure that no faults were published by the consumer
                Assert.That(await harness.Published.Any <Fault <IArchiveRecordUpdated> >(), Is.False);

                // did the actual consumer consume the message
                var message = harness.Published.Select <IArchiveRecordUpdated>().First().Context.Message;

                // Assert
                message.ActionSuccessful.Should().Be(false);
                message.MutationId.Should().Be(mutationId);
                message.ErrorMessage.Should().Be(errMsg);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task If_Update_succeeds_Sync_process_is_set_to_success()
        {
            // Arrange
            var ar = new ArchiveRecord
            {
                ArchiveRecordId = "3245", Security = new ArchiveRecordSecurity
                {
                    MetadataAccessToken = new List <string> {
                        "BAR"
                    },
                    PrimaryDataFulltextAccessToken = new List <string> {
                        "BAR"
                    },
                    PrimaryDataDownloadAccessToken = new List <string> {
                        "BAR"
                    }
                }
            };
            var mutationId = 124;

            indexManager.Setup(e => e.UpdateArchiveRecord(It.IsAny <ConsumeContext <IUpdateArchiveRecord> >()));

            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer(() => new UpdateArchiveRecordConsumer(indexManager.Object));

            await harness.Start();

            try
            {
                // Act
                await harness.InputQueueSendEndpoint.Send <IUpdateArchiveRecord>(new
                {
                    ArchiveRecord = ar,
                    MutationId    = mutationId
                });

                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <IUpdateArchiveRecord>());

                // did the actual consumer consume the message
                Assert.That(await consumer.Consumed.Any <IUpdateArchiveRecord>());

                // was the update ArchiveRecord message sent
                Assert.That(await harness.Published.Any <IArchiveRecordUpdated>());
                var message = harness.Published.Select <IArchiveRecordUpdated>().FirstOrDefault();

                // Assert
                Assert.That(message != null);
                message.Context.Message.ActionSuccessful.Should().Be(true);
                message.Context.Message.MutationId.Should().Be(mutationId);
                message.Context.Message.ErrorMessage.Should().Be(null);
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #21
0
        public async Task ShouldMapMassTransitTagsForReceiveMessageToOpenTelemetrySpecification()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using (Sdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .AddMassTransitInstrumentation()
                   .Build())
            {
                var harness         = new InMemoryTestHarness();
                var consumerHarness = harness.Consumer <TestConsumer>();
                var handlerHarness  = harness.Handler <TestMessage>();
                await harness.Start();

                try
                {
                    await harness.InputQueueSendEndpoint.Send <TestMessage>(new { Text = "Hello, world!" });

                    Assert.True(await harness.Consumed.SelectAsync <TestMessage>().Any());
                    Assert.True(await consumerHarness.Consumed.SelectAsync <TestMessage>().Any());
                    Assert.True(await handlerHarness.Consumed.SelectAsync().Any());
                }
                finally
                {
                    await harness.Stop();
                }

                var expectedMessageContext = harness.Sent.Select <TestMessage>().FirstOrDefault()?.Context;
                var actualActivity         = this.GetActivitiesFromInvocationsByOperationName(activityProcessor.Invocations, OperationName.Transport.Receive).LastOrDefault();

                Assert.NotNull(actualActivity);
                Assert.NotNull(expectedMessageContext);

                Assert.Equal("/input_queue consume", actualActivity.DisplayName);
                Assert.Equal(ActivityKind.Consumer, actualActivity.Kind);
                Assert.Equal("loopback", actualActivity.GetTagValue(SemanticConventions.AttributeMessagingSystem)?.ToString());

                Assert.Equal(expectedMessageContext.MessageId.ToString(), actualActivity.GetTagValue(SemanticConventions.AttributeMessagingMessageId)?.ToString());
                Assert.Equal(expectedMessageContext.ConversationId.ToString(), actualActivity.GetTagValue(SemanticConventions.AttributeMessagingConversationId)?.ToString());
                Assert.Equal(expectedMessageContext.DestinationAddress.AbsolutePath, actualActivity.GetTagValue(SemanticConventions.AttributeMessagingDestination)?.ToString());
                Assert.Equal(expectedMessageContext.DestinationAddress.Host, actualActivity.GetTagValue(SemanticConventions.AttributeNetPeerName)?.ToString());

                Assert.Null(actualActivity.GetTagValue(TagName.MessageId));
                Assert.Null(actualActivity.GetTagValue(TagName.ConversationId));
                Assert.Null(actualActivity.GetTagValue(TagName.DestinationAddress));

                Assert.Null(actualActivity.GetTagValue(TagName.SpanKind));
                Assert.Null(actualActivity.GetTagValue(TagName.PeerService));

                Assert.Null(actualActivity.GetTagValue(TagName.PeerAddress));
                Assert.Null(actualActivity.GetTagValue(TagName.PeerHost));
                Assert.Null(actualActivity.GetTagValue(TagName.MessageTypes));
                Assert.Null(actualActivity.GetTagValue(TagName.SourceAddress));
                Assert.Null(actualActivity.GetTagValue(TagName.SourceHostMachine));
            }
        }
        public async Task Should_have_a_familiar_syntax()
        {
            MessageCorrelation.UseCorrelationId<LegacyMessage>(x => x.TransactionId);

            var harness = new InMemoryTestHarness();
            harness.OnConfigureInMemoryBus += configurator =>
            {
                configurator.Send<IEvent>(x =>
                {
                    x.UseCorrelationId(p => p.TransactionId);
                });
            };

            Task<ConsumeContext<INewUserEvent>> handled = null;
            Task<ConsumeContext<OtherMessage>> otherHandled = null;
            Task<ConsumeContext<LegacyMessage>> legacyHandled = null;
            harness.OnConfigureInMemoryReceiveEndpoint += configurator =>
            {
                handled = harness.Handled<INewUserEvent>(configurator);
                otherHandled = harness.Handled<OtherMessage>(configurator);
                legacyHandled = harness.Handled<LegacyMessage>(configurator);
            };


            await harness.Start();
            try
            {
                var transactionId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send<INewUserEvent>(new {TransactionId = transactionId});

                ConsumeContext<INewUserEvent> context = await handled;

                Assert.IsTrue(context.CorrelationId.HasValue);
                Assert.That(context.CorrelationId.Value, Is.EqualTo(transactionId));

                await harness.InputQueueSendEndpoint.Send<OtherMessage>(new {CorrelationId = transactionId});

                ConsumeContext<OtherMessage> otherContext = await otherHandled;

                Assert.IsTrue(otherContext.CorrelationId.HasValue);
                Assert.That(otherContext.CorrelationId.Value, Is.EqualTo(transactionId));

                await harness.InputQueueSendEndpoint.Send<LegacyMessage>(new {TransactionId = transactionId});

                ConsumeContext<LegacyMessage> legacyContext = await legacyHandled;

                Assert.IsTrue(legacyContext.CorrelationId.HasValue);
                Assert.That(legacyContext.CorrelationId.Value, Is.EqualTo(transactionId));
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #23
0
 public async Task Teardown()
 {
     try
     {
         await TestHarness.Stop();
     }
     finally
     {
         await Provider.DisposeAsync();
     }
 }
        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();
            }
        }
        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 If_delete_is_requested_record_is_removed_from_index()
        {
            // Arrange
            var archvieRecordId = "34599";
            var mutationId      = 6616;
            var ar = new ArchiveRecord {
                ArchiveRecordId = archvieRecordId, Metadata = new ArchiveRecordMetadata {
                    PrimaryDataLink = null
                }
            };

            harvestManager.Setup(e => e.BuildArchiveRecord(archvieRecordId)).Returns(ar);

            var harness  = new InMemoryTestHarness();
            var consumer = harness.Consumer(() => new SyncArchiveRecordConsumer(harvestManager.Object, findArchiveRecordClient.Object, cachedHarvesterSetting.Object));

            await harness.Start();

            try
            {
                // Act
                await harness.InputQueueSendEndpoint.Send <ISyncArchiveRecord>(new
                {
                    ArchiveRecordId = archvieRecordId,
                    MutationId      = mutationId,
                    Action          = "delete"
                });


                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <ISyncArchiveRecord>());

                // did the actual consumer consume the message
                Assert.That(await consumer.Consumed.Any <ISyncArchiveRecord>());
                var message = harness.Consumed.Select <ISyncArchiveRecord>().FirstOrDefault();

                // was the delete message sent
                Assert.That(await harness.Sent.Any <IRemoveArchiveRecord>());

                // Assert
                Assert.That(message != null);
                message.Context.Message.ArchiveRecordId.Should().Be(archvieRecordId);
                message.Context.Message.MutationId.Should().Be(mutationId);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                await harness.Stop();
            }
        }
예제 #27
0
        public async Task If_Package_is_valid_the_package_is_scheduled_for_sync()
        {
            // Arrange
            var harness = new InMemoryTestHarness();

            try
            {
                var ar = new ArchiveRecord {
                    ArchiveRecordId = "478"
                };
                var mutationId   = 777;
                var errMsg       = string.Empty;
                var appendResult = new RepositoryPackageInfoResult
                {
                    Valid = true, Success = true, ErrorMessage = errMsg, PackageDetails = new RepositoryPackage {
                        ArchiveRecordId = ar.ArchiveRecordId
                    }
                };
                repositoryManager.Setup(e => e.ReadPackageMetadata(It.IsAny <string>(), It.IsAny <string>())).Returns(appendResult);

                var readMetadataConsumer = harness.Consumer(() => readPackageMetadataConsumer.Object);
                harness.Consumer(() => new ReadPackageMetadataConsumer(repositoryManager.Object));
                harness.Consumer(() => readPackageMetadataConsumer.Object);

                await harness.Start();

                // Act
                await harness.InputQueueSendEndpoint.Send <IArchiveRecordAppendPackageMetadata>(new
                {
                    ArchiveRecord = ar,
                    MutationId    = mutationId
                });

                // Assert
                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <IArchiveRecordAppendPackageMetadata>());

                // did the actual consumer consume the message
                Assert.That(await readMetadataConsumer.Consumed.Any <IArchiveRecordAppendPackageMetadata>());

                Assert.That(await harness.Sent.Any <IScheduleForPackageSync>());
                var message = harness.Sent.Select <IScheduleForPackageSync>().First().Context.Message;

                // Assert
                message.Workload.ArchiveRecord.ArchiveRecordId.Should().Be(ar.ArchiveRecordId);
                message.Workload.MutationId.Should().Be(mutationId);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task DisposeAsync()
        {
            await _bus.Stop();

            using (var connection = _dbFixture.GetConnection())
                using (var command = connection.CreateCommand())
                {
                    await connection.OpenAsync();

                    command.CommandText = "TRUNCATE TABLE " + _dbFixture.TableName;
                    await command.ExecuteNonQueryAsync();
                }
        }
예제 #29
0
        public async Task Teardown()
        {
            try
            {
                await TestHarness.Stop();
            }
            finally
            {
                await Provider.DisposeAsync();
            }

            RestoreDefaultQuartzSystemTime();
        }
예제 #30
0
        public async void Roles()
        {
            await harness.Start();

            harness.Consumer <RoleDomainEvent>(() =>
            {
                // harness.Consume<RoleDomainEvent>( )
                return(new RoleDomainEvent(null, null));
            });

            try
            {
            }
            catch (Exception ex)
            {
                await harness.Stop();
            }
            finally
            {
                await harness.Stop();
            }
        }