public async Task SingleMessageConsumeAsync_SomeEvent_PreprocessedEventAddedToQueue()
    {
        var inputMessage   = new byte[] { 1, 2, 3 };
        var inputEvent     = MotorCloudEvent.CreateTestCloudEvent(inputMessage);
        var fakeDecoder    = new Mock <IMessageDecoder>();
        var decodedMessage = new byte[] { 4, 5, 6 };

        fakeDecoder.Setup(f => f.DecodeAsync(inputMessage, It.IsAny <CancellationToken>()))
        .ReturnsAsync(decodedMessage);
        fakeDecoder.Setup(m => m.Encoding).Returns(NoOpMessageEncoder.NoEncoding);
        var preprocessedMessage = "test";
        var fakeDeserializer    = new Mock <IMessageDeserializer <string> >();

        fakeDeserializer.Setup(f => f.Deserialize(decodedMessage)).Returns(preprocessedMessage);
        var mockQueue           = new Mock <IBackgroundTaskQueue <MotorCloudEvent <string> > >();
        var fakeMessageConsumer = new Mock <IMessageConsumer <string> >();

        fakeMessageConsumer.SetupProperty(p => p.ConsumeCallbackAsync);
        CreateConsumerService(mockQueue.Object, fakeDeserializer.Object, fakeDecoder.Object,
                              fakeMessageConsumer.Object);

        await fakeMessageConsumer.Object.ConsumeCallbackAsync?.Invoke(inputEvent, CancellationToken.None) !;

        mockQueue.Verify(m =>
                         m.QueueBackgroundWorkItem(
                             It.Is <MotorCloudEvent <string> >(cloudEvent => cloudEvent.TypedData == preprocessedMessage)));
    }
예제 #2
0
        public async Task Consume_PublishIntoExtensionDefinedTopic_ConsumedEqualsPublished()
        {
            var topic           = randomizerString.Generate();
            var message         = "testMessage";
            var publisher       = GetPublisher <byte[]>("wrong_topic");
            var motorCloudEvent =
                MotorCloudEvent.CreateTestCloudEvent(message).CreateNew(Encoding.UTF8.GetBytes(message));

            motorCloudEvent.GetExtensionOrCreate(() => new KafkaTopicExtension(topic));
            await publisher.PublishMessageAsync(motorCloudEvent, CancellationToken.None);

            var    consumer             = GetConsumer <byte[]>(topic);
            string id                   = null;
            var    taskCompletionSource = new TaskCompletionSource();

            consumer.ConsumeCallbackAsync = async(dataEvent, _) =>
            {
                id = dataEvent.Id;
                taskCompletionSource.TrySetResult();
                return(await Task.FromResult(ProcessedMessageStatus.Success));
            };

            await consumer.StartAsync();

            var consumerStartTask = consumer.ExecuteAsync();

            await Task.WhenAny(consumerStartTask, taskCompletionSource.Task);

            Assert.Equal(motorCloudEvent.Id, id);
        }
예제 #3
0
    public async Task PublishMessageAsync_WithConfig_BasicPropertiesAreSet()
    {
        var basicProperties = Mock.Of <IBasicProperties>();
        var modelMock       = new Mock <IModel>();

        modelMock.Setup(x => x.CreateBasicProperties()).Returns(basicProperties);
        var rabbitConnectionFactoryMock =
            GetDefaultConnectionFactoryMock <string>(modelMock: modelMock, basicProperties: basicProperties);

        var        publisher = GetPublisher(rabbitConnectionFactoryMock.Object, GetConfig());
        const byte priority  = 1;

        var activity = new Activity(nameof(RabbitMQMessagePublisherTests));

        activity.SetIdFormat(ActivityIdFormat.W3C);
        activity.Start();

        var motorCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

        motorCloudEvent.SetActivity(activity);
        motorCloudEvent.SetRabbitMQPriority(priority);

        await publisher.PublishMessageAsync(motorCloudEvent);

        Assert.Equal(2, basicProperties.DeliveryMode);
        Assert.Equal(priority, basicProperties.Priority);
        var traceparent = Encoding.UTF8.GetString((byte[])basicProperties.Headers[
                                                      $"{BasicPropertiesExtensions.CloudEventPrefix}{DistributedTracingExtension.TraceParentAttribute.Name}"]);
        var activityContext = ActivityContext.Parse(traceparent, null);

        Assert.Equal(activity.Context.TraceId, activityContext.TraceId);
        Assert.Equal(activity.Context.SpanId, activityContext.SpanId);
        Assert.Equal(activity.Context.TraceFlags, activityContext.TraceFlags);
    }
    public void UpdateAndExtractCloudEvent_V0_6_0Header_ExtensionsAddedToCloudEvent()
    {
        var channel                      = _fixture.Connection.CreateModel();
        var basicProperties              = channel.CreateBasicProperties();
        var publisherOptions             = new RabbitMQPublisherOptions <byte[]>();
        var content                      = new byte[] { 1, 2, 3 };
        var inputCloudEvent              = MotorCloudEvent.CreateTestCloudEvent(content);
        var mockedApplicationNameService = Mock.Of <IApplicationNameService>();

        basicProperties.SetPriority(inputCloudEvent, publisherOptions);
        basicProperties.WriteCloudEventIntoHeader(inputCloudEvent);
        // manipulate basic properties to simulate outdated version
        basicProperties.Headers.Remove($"{BasicPropertiesExtensions.CloudEventPrefix}{MotorVersionExtension.MotorVersionAttribute.Name}");
        basicProperties.ContentEncoding = null;
        basicProperties.Headers.Add(
            $"{BasicPropertiesExtensions.CloudEventPrefix}{CloudEventsSpecVersion.V1_0.DataContentTypeAttribute.Name}",
            Encoding.UTF8.GetBytes($"{basicProperties.ContentType}"));
        foreach (var(key, value) in basicProperties.Headers)
        {
            if (value is byte[] byteValue)
            {
                basicProperties.Headers[key] = EscapeWithQuotes(byteValue);
            }
        }

        var outputCloudEvent = basicProperties.ExtractCloudEvent(mockedApplicationNameService,
                                                                 new ReadOnlyMemory <byte>(content));

        Assert.Equal(MotorCloudEventInfo.RequiredAttributes(Version.Parse("0.6.0.0")).Count(),
                     outputCloudEvent.GetPopulatedAttributes().Count());
        foreach (var requiredAttribute in MotorCloudEventInfo.RequiredAttributes(Version.Parse("0.6.0.0")))
        {
            Assert.Equal(inputCloudEvent[requiredAttribute], outputCloudEvent[requiredAttribute]);
        }
    }
        public async Task StartAsync_CreateSpanAsReference_ContextIsReferenced()
        {
            PrepareQueues();

            var host    = GetReverseStringService();
            var channel = _fixture.Connection.CreateModel();

            await CreateQueueForServicePublisherWithPublisherBindingFromConfig(channel);

            await host.StartAsync();

            var extensions     = new List <ICloudEventExtension>();
            var randomActivity = CreateRandomActivity();
            var distributedTracingExtension = new DistributedTracingExtension();

            distributedTracingExtension.SetActivity(randomActivity);
            extensions.Add(distributedTracingExtension);
            var motorCloudEvent = MotorCloudEvent.CreateTestCloudEvent(new byte[0], extensions: extensions);

            await PublishMessageIntoQueueOfService(channel, "12345", motorCloudEvent);

            var ctx = await GetActivityContextFromDestinationQueue(channel);

            Assert.Equal(randomActivity.Context.TraceId, ctx.TraceId);
            Assert.NotEqual(randomActivity.Context.SpanId, ctx.SpanId);
            await host.StopAsync();
        }
    private static MotorCloudEvent <byte[]> CreateMotorCloudEventWithEncoding(string encoding,
                                                                              byte[]?inputMessage = null)
    {
        var cloudEvent = MotorCloudEvent.CreateTestCloudEvent(inputMessage ?? Array.Empty <byte>());

        cloudEvent.SetEncoding(encoding);
        return(cloudEvent);
    }
예제 #7
0
    public async Task PublishMessageAsync_WithConfig_ChannelEstablished()
    {
        var rabbitConnectionFactoryMock = GetDefaultConnectionFactoryMock <string>();
        var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, GetConfig());

        await publisher.PublishMessageAsync(MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>()));

        rabbitConnectionFactoryMock.Verify(x => x.CurrentChannel, Times.Exactly(1));
    }
        public async Task PublishMessageAsync_WithConfig_ConnectionFactoryIsSet()
        {
            var mock      = GetDefaultConnectionFactoryMock();
            var config    = GetConfig();
            var publisher = GetPublisher(mock.Object, config);

            await publisher.PublishMessageAsync(MotorCloudEvent.CreateTestCloudEvent(new byte [0]));

            mock.Verify(x => x.From(config), Times.Exactly(1));
        }
        public async Task PublishMessageAsync_WithConfig_ChannelEstablished()
        {
            var connectionMock = new Mock <IConnection>();
            var rabbitConnectionFactoryMock = GetDefaultConnectionFactoryMock(connectionMock: connectionMock);
            var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, GetConfig());

            await publisher.PublishMessageAsync(MotorCloudEvent.CreateTestCloudEvent(new byte[0]));

            connectionMock.Verify(x => x.CreateModel(), Times.Exactly(1));
        }
예제 #10
0
    public async Task PublishMessageAsync_WithConfig_BasicPropertiesAreCreated()
    {
        var modelMock = new Mock <IModel>();
        var rabbitConnectionFactoryMock = GetDefaultConnectionFactoryMock <string>(modelMock: modelMock);
        var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, GetConfig());

        await publisher.PublishMessageAsync(MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>()));

        modelMock.Verify(x => x.CreateBasicProperties(), Times.Exactly(1));
    }
예제 #11
0
        private static IBackgroundTaskQueue <MotorCloudEvent <string> > CreateQueue(
            MotorCloudEvent <string>?dataCloudEvent = null, TaskCompletionSource <ProcessedMessageStatus>?status = null)
        {
            var queue = new Mock <IBackgroundTaskQueue <MotorCloudEvent <string> > >();

            queue.Setup(t => t.DequeueAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(() =>
                          new QueueItem <MotorCloudEvent <string> >(
                              dataCloudEvent ?? MotorCloudEvent.CreateTestCloudEvent(string.Empty, new Uri("test://non")),
                              status ?? new TaskCompletionSource <ProcessedMessageStatus>()));
            return(queue.Object);
        }
예제 #12
0
    public void CloudEventToKafkaMessage_CloudEventFormatJson_VerifyIdIsCorrectlyStored()
    {
        var publisher       = GetKafkaPublisher <byte[]>(CloudEventFormat.Json);
        var inputCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());
        var cloudFormatter  = new JsonEventFormatter();

        var kafkaMessage = publisher.CloudEventToKafkaMessage(inputCloudEvent);

        var cloudEvent = cloudFormatter.DecodeStructuredModeMessage(kafkaMessage.Value, null, null);

        Assert.Equal(inputCloudEvent.Id, cloudEvent.Id);
    }
    public async Task PublishMessageAsync_CloudEventOfTypeString_PublishedCloudEventHasTypeString()
    {
        var bytesPublisher        = new Mock <IRawMessagePublisher <string> >();
        var typedMessagePublisher = CreateTypedMessagePublisher(bytesPublisher.Object);
        var motorEvent            = MotorCloudEvent.CreateTestCloudEvent("test");

        await typedMessagePublisher.PublishMessageAsync(motorEvent);

        bytesPublisher.Verify(t => t.PublishMessageAsync(
                                  It.Is <MotorCloudEvent <byte[]> >(it => it.Type == motorEvent.Type),
                                  It.IsAny <CancellationToken>()), Times.Once);
    }
    public async Task PublishMessageAsync_ContextToPassed_ContextPassed()
    {
        var publisher             = new Mock <IRawMessagePublisher <string> >();
        var typedMessagePublisher = CreateTypedMessagePublisher(publisher.Object);
        var motorEvent            = MotorCloudEvent.CreateTestCloudEvent("test");

        await typedMessagePublisher.PublishMessageAsync(motorEvent);

        publisher.Verify(t => t.PublishMessageAsync(
                             It.Is <MotorCloudEvent <byte[]> >(it => it.Id == motorEvent.Id),
                             It.IsAny <CancellationToken>()), Times.Once);
    }
    public void Update_NoExtensions_OnlyRequiredAttributesInHeader()
    {
        var channel          = _fixture.Connection.CreateModel();
        var basicProperties  = channel.CreateBasicProperties();
        var publisherOptions = new RabbitMQPublisherOptions <byte[]>();
        var cloudEvent       = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

        basicProperties.SetPriority(cloudEvent, publisherOptions);
        basicProperties.WriteCloudEventIntoHeader(cloudEvent);

        VerifyPresenceOfRequiredAttributes(basicProperties, cloudEvent);
    }
        public async Task PublishMessageAsync_MessageToSerialize_IsCalledSerializedMessage()
        {
            var publisher             = new Mock <ITypedMessagePublisher <byte[]> >();
            var serializer            = new Mock <IMessageSerializer <string> >();
            var typedMessagePublisher =
                new TypedMessagePublisher <string, ITypedMessagePublisher <byte[]> >(null, publisher.Object,
                                                                                     serializer.Object);
            var motorEvent = MotorCloudEvent.CreateTestCloudEvent("test");

            await typedMessagePublisher.PublishMessageAsync(motorEvent);

            serializer.Verify(t => t.Serialize("test"), Times.Once);
        }
    public async Task PublishMessageAsync_CloudEventWithContentEncoding_PublishedCloudEventHasDefaultEncoding()
    {
        var bytesPublisher        = new Mock <IRawMessagePublisher <string> >();
        var typedMessagePublisher = CreateTypedMessagePublisher(bytesPublisher.Object, encoder: new NoOpMessageEncoder());
        var motorEvent            = MotorCloudEvent.CreateTestCloudEvent("test");

        motorEvent.SetEncoding("some-encoding");

        await typedMessagePublisher.PublishMessageAsync(motorEvent);

        bytesPublisher.Verify(t => t.PublishMessageAsync(
                                  It.Is <MotorCloudEvent <byte[]> >(it => it.GetEncoding() == NoOpMessageEncoder.NoEncoding),
                                  It.IsAny <CancellationToken>()), Times.Once);
    }
예제 #18
0
        public async void ExecuteAsync_MultipleMessage_ParallelProcessingBasedOnConfig(
            int?parallelProcessesOrProcessorCount)
        {
            parallelProcessesOrProcessorCount ??= Environment.ProcessorCount;
            var waitTimeInMs          = 200;
            var taskCompletionSources = new List <TaskCompletionSource <ProcessedMessageStatus> >();
            var queue = new Mock <IBackgroundTaskQueue <MotorCloudEvent <string> > >();
            var setupSequentialResult = queue.SetupSequence(t => t.DequeueAsync(It.IsAny <CancellationToken>()));

            for (var i = 0; i < parallelProcessesOrProcessorCount * 2; i++)
            {
                var source = new TaskCompletionSource <ProcessedMessageStatus>();
                setupSequentialResult = setupSequentialResult.ReturnsAsync(() =>
                                                                           new QueueItem <MotorCloudEvent <string> >(
                                                                               MotorCloudEvent.CreateTestCloudEvent(string.Empty, new Uri("test://non")),
                                                                               source));
                taskCompletionSources.Add(source);
            }

            var service = new Mock <INoOutputService <string> >();

            service.Setup(t =>
                          t.HandleMessageAsync(It.IsAny <MotorCloudEvent <string> >(), It.IsAny <CancellationToken>()))
            .Returns(async() =>
            {
                await Task.Delay(waitTimeInMs).ConfigureAwait(false);
                return(ProcessedMessageStatus.Success);
            });
            var queuedGenericService = CreateQueuedGenericService(service.Object, queue.Object,
                                                                  config: new QueuedGenericServiceOptions
            {
                ParallelProcesses = parallelProcessesOrProcessorCount
            });

            await queuedGenericService.StartAsync(CancellationToken.None).ConfigureAwait(false);

            await Task.Delay(Convert.ToInt32(Math.Floor(waitTimeInMs * 0.5))).ConfigureAwait(false);

            await queuedGenericService.StopAsync(CancellationToken.None).ConfigureAwait(false);

            service.Verify(t => t
                           .HandleMessageAsync(It.IsAny <MotorCloudEvent <string> >(), It.IsAny <CancellationToken>()),
                           Times.Exactly(parallelProcessesOrProcessorCount.Value));
            var done = taskCompletionSources
                       .Count(completionSource => completionSource.Task.Status == TaskStatus.RanToCompletion);

            Assert.Equal(parallelProcessesOrProcessorCount, done);
        }
예제 #19
0
    public void UseProtocolFormat_NoExtensions_OnlyRequiredAttributesInHeader()
    {
        var publisher       = GetKafkaPublisher <byte[]>();
        var consumer        = GetKafkaConsumer <byte[]>();
        var inputCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

        var kafkaMessage     = publisher.CloudEventToKafkaMessage(inputCloudEvent);
        var outputCloudEvent = consumer.KafkaMessageToCloudEvent(kafkaMessage);

        Assert.Equal(MotorCloudEventInfo.RequiredAttributes(CurrentMotorVersion).Count(),
                     outputCloudEvent.GetPopulatedAttributes().Count());
        foreach (var requiredAttribute in MotorCloudEventInfo.RequiredAttributes(CurrentMotorVersion))
        {
            Assert.Equal(inputCloudEvent[requiredAttribute], outputCloudEvent[requiredAttribute]);
        }
    }
        public async Task PublishMessageAsync_WithConfig_MessagePublished()
        {
            var basicProperties = Mock.Of <IBasicProperties>();
            var modelMock       = new Mock <IModel>();

            modelMock.Setup(x => x.CreateBasicProperties()).Returns(basicProperties);
            var rabbitConnectionFactoryMock =
                GetDefaultConnectionFactoryMock(modelMock: modelMock, basicProperties: basicProperties);
            var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, GetConfig());
            var message   = new byte[0];

            await publisher.PublishMessageAsync(MotorCloudEvent.CreateTestCloudEvent(message));

            modelMock.Verify(x => x.BasicPublish(GetConfig().PublishingTarget.Exchange,
                                                 GetConfig().PublishingTarget.RoutingKey, true, basicProperties, message));
        }
    public void Update_EncodingExtension_EncodingNotInHeaderInProperties()
    {
        var          channel          = _fixture.Connection.CreateModel();
        var          basicProperties  = channel.CreateBasicProperties();
        var          publisherOptions = new RabbitMQPublisherOptions <byte[]>();
        var          cloudEvent       = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());
        const string encoding         = "someEncoding";

        cloudEvent.SetEncoding(encoding);

        basicProperties.SetPriority(cloudEvent, publisherOptions);
        basicProperties.WriteCloudEventIntoHeader(cloudEvent);

        Assert.Equal(encoding, basicProperties.ContentEncoding);
        VerifyPresenceOfRequiredAttributes(basicProperties, cloudEvent);
    }
        public async Task PublishMessageAsync_MessageToSerialize_SerializedMessageIsPublished()
        {
            var publisher  = new Mock <ITypedMessagePublisher <byte[]> >();
            var serializer = new Mock <IMessageSerializer <string> >();
            var bytes      = new byte[] { 1, 2, 3, 4 };

            serializer.Setup(t => t.Serialize(It.IsAny <string>())).Returns(bytes);
            var typedMessagePublisher =
                new TypedMessagePublisher <string, ITypedMessagePublisher <byte[]> >(null, publisher.Object,
                                                                                     serializer.Object);
            var motorEvent = MotorCloudEvent.CreateTestCloudEvent("test");

            await typedMessagePublisher.PublishMessageAsync(motorEvent);

            publisher.Verify(t => t.PublishMessageAsync(
                                 It.Is <MotorCloudEvent <byte[]> >(it => it.Data == bytes),
                                 It.IsAny <CancellationToken>()), Times.Once);
        }
예제 #23
0
    public async Task PublishMessageAsync_CloudEventWithRoutingKeyExtensionAndOverwriteExchange_MessagePublished()
    {
        const string customExchange   = "cloud-event-exchange";
        const string customRoutingKey = "cloud-event-routing-key";

        var modelMock = new Mock <IModel>();

        modelMock.Setup(x => x.CreateBasicProperties()).Returns(Mock.Of <IBasicProperties>());
        var rabbitConnectionFactoryMock = GetDefaultConnectionFactoryMock <string>(modelMock: modelMock);
        var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, overwriteExchange: true);

        var motorCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

        motorCloudEvent.SetRabbitMQBinding(customExchange, customRoutingKey);
        await publisher.PublishMessageAsync(motorCloudEvent);

        modelMock.Verify(x => x.BasicPublish(DefaultExchange,
                                             customRoutingKey, true, It.IsAny <IBasicProperties>(), It.IsAny <ReadOnlyMemory <byte> >()));
    }
    public void UpdateAndExtractCloudEvent_NoExtensions_CloudEventWithRequiredExtensions()
    {
        var channel                      = _fixture.Connection.CreateModel();
        var basicProperties              = channel.CreateBasicProperties();
        var publisherOptions             = new RabbitMQPublisherOptions <byte[]>();
        var content                      = new byte[] { 1, 2, 3 };
        var inputCloudEvent              = MotorCloudEvent.CreateTestCloudEvent(content);
        var mockedApplicationNameService = Mock.Of <IApplicationNameService>();

        basicProperties.SetPriority(inputCloudEvent, publisherOptions);
        basicProperties.WriteCloudEventIntoHeader(inputCloudEvent);
        var outputCloudEvent = basicProperties.ExtractCloudEvent(mockedApplicationNameService,
                                                                 new ReadOnlyMemory <byte>(content));

        foreach (var requiredAttribute in MotorCloudEventInfo.RequiredAttributes(CurrentMotorVersion))
        {
            Assert.Equal(inputCloudEvent[requiredAttribute], outputCloudEvent[requiredAttribute]);
        }
    }
예제 #25
0
    public async Task PublishMessageAsync_WithCloudEventFormatJson_MessagePublished()
    {
        var basicProperties = Mock.Of <IBasicProperties>();
        var modelMock       = new Mock <IModel>();

        modelMock.Setup(x => x.CreateBasicProperties()).Returns(basicProperties);
        var rabbitConnectionFactoryMock =
            GetDefaultConnectionFactoryMock <string>(modelMock: modelMock, basicProperties: basicProperties);
        var config    = GetConfig();
        var publisher = GetPublisher(rabbitConnectionFactoryMock.Object, config, cloudEventFormat: CloudEventFormat.Json);
        var message   = MotorCloudEvent.CreateTestCloudEvent(new byte[] { });

        await publisher.PublishMessageAsync(message);

        var jsonEventFormatter = new JsonEventFormatter();
        var bytes = jsonEventFormatter.EncodeStructuredModeMessage(message.ConvertToCloudEvent(), out _);

        modelMock.Verify(x => x.BasicPublish(config.PublishingTarget.Exchange,
                                             config.PublishingTarget.RoutingKey, true, basicProperties, It.Is <ReadOnlyMemory <byte> >(t => t.ToArray().SequenceEqual(bytes.ToArray()))));
    }
        public async Task StartAsync_CreateCustomExtension_ExtensionIsPassedThrough()
        {
            var consumer  = new InMemoryConsumer <string>();
            var publisher = new InMemoryPublisher <string>();

            using var host = GetReverseStringService(consumer, publisher);

            await host.StartAsync();

            var motorCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

            motorCloudEvent.SetSomeCustomExtension(DateTimeOffset.MaxValue);

            await consumer.AddMessage(motorCloudEvent);

            var receivedCloudEvent = publisher.Events.First();

            Assert.Equal(DateTimeOffset.MaxValue, receivedCloudEvent.GetSomeCustomExtension());
            await host.StopAsync();
        }
        public async Task StartAsync_CreateSpanAsReference_ContextIsReferenced()
        {
            var consumer  = new InMemoryConsumer <string>();
            var publisher = new InMemoryPublisher <string>();

            using var host = GetReverseStringService(consumer, publisher);

            await host.StartAsync();

            var randomActivity  = CreateRandomActivity();
            var motorCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());

            motorCloudEvent.SetActivity(randomActivity);
            await consumer.AddMessage(motorCloudEvent);

            var ctx = publisher.Events.First().GetActivityContext();

            Assert.Equal(randomActivity.Context.TraceId, ctx.TraceId);
            Assert.NotEqual(randomActivity.Context.SpanId, ctx.SpanId);
            await host.StopAsync();
        }
    public async Task PublishMessageAsync_MessageToSerialize_SerializedMessageIsPublished()
    {
        var publisher       = new Mock <IRawMessagePublisher <string> >();
        var serializer      = new Mock <IMessageSerializer <string> >();
        var encoder         = new Mock <IMessageEncoder>();
        var serializedBytes = new byte[] { 1, 2, 3, 4 };
        var encodedBytes    = new byte[] { 4, 3, 2, 1 };

        serializer.Setup(t => t.Serialize(It.IsAny <string>())).Returns(serializedBytes);
        encoder.Setup(t => t.EncodeAsync(serializedBytes, It.IsAny <CancellationToken>()))
        .ReturnsAsync(encodedBytes);
        encoder.SetupGet(c => c.Encoding).Returns("someEncoding");
        var typedMessagePublisher = CreateTypedMessagePublisher(publisher.Object, serializer.Object, encoder.Object);
        var motorEvent            = MotorCloudEvent.CreateTestCloudEvent("test");

        await typedMessagePublisher.PublishMessageAsync(motorEvent);

        publisher.Verify(t => t.PublishMessageAsync(
                             It.Is <MotorCloudEvent <byte[]> >(it => it.Data == encodedBytes),
                             It.IsAny <CancellationToken>()), Times.Once);
    }
예제 #29
0
    public async Task PublisherPublishMessageAsync_SomeMessage_PublishedEqualsConsumed()
    {
        var builder = RabbitMQTestBuilder
                      .CreateWithQueueDeclare(_fixture)
                      .Build();
        var publisher = builder.GetPublisher <byte[]>();

        const byte priority = 222;
        var        message  = new byte[] { 3, 2, 1 };

        var cloudEvent = MotorCloudEvent.CreateTestCloudEvent(message);

        cloudEvent.SetRabbitMQPriority(priority);

        await publisher.PublishMessageAsync(cloudEvent);

        var results = await builder.GetMessageFromQueue();

        Assert.Equal(priority, results.GetRabbitMQPriority());
        Assert.Equal(message, results.Data);
    }
        public async Task PublishMessageAsync_CloudEventWithRoutingKeyExtension_MessagePublished()
        {
            const string customExchange   = "cloud-event-exchange";
            const string customRoutingKey = "cloud-event-routing-key";

            var modelMock = new Mock <IModel>();

            modelMock.Setup(x => x.CreateBasicProperties()).Returns(Mock.Of <IBasicProperties>());
            var rabbitConnectionFactoryMock = GetDefaultConnectionFactoryMock(modelMock: modelMock);
            var publisher  = GetPublisher(rabbitConnectionFactoryMock.Object);
            var extensions = new List <ICloudEventExtension>
            {
                new RabbitMQBindingConfigExtension(customExchange, customRoutingKey)
            };

            await publisher.PublishMessageAsync(
                MotorCloudEvent.CreateTestCloudEvent(new byte[0], extensions: extensions));

            modelMock.Verify(x => x.BasicPublish(customExchange,
                                                 customRoutingKey, true, It.IsAny <IBasicProperties>(), It.IsAny <byte[]>()));
        }