示例#1
0
        public async Task StartAsync_should_consume_messages()
        {
            var processor = NSubstitute.Substitute.For <IMessageProcessor>();

            var messages = new[]
            {
                DummyMessage.New(),
                DummyMessage.New(),
            };
            var asyncMessages = GetMessagesAsync(messages);

            var reader = NSubstitute.Substitute.For <ChannelReader <DummyMessage> >();

            reader.ReadAllAsync()
            .ReturnsForAnyArgs(asyncMessages);

            var logger = NSubstitute.Substitute.For <ILogger <InMemorySubscriber <DummyMessage> > >();

            var sut = new InMemorySubscriber <DummyMessage>(processor, reader, logger);
            await sut.StartAsync();

            foreach (var message in messages)
            {
                await processor.Received(1).ProcessAsync(message);
            }
        }
        public async Task PublishAsync_should_publish_message()
        {
            var message = DummyMessage.New();

            var topicName = "lorem";

            var producerResult = new DeliveryResult <Guid, byte[]>()
            {
                Status = PersistenceStatus.Persisted
            };
            var producer = NSubstitute.Substitute.For <IProducer <Guid, byte[]> >();

            producer.ProduceAsync(topicName, Arg.Any <Message <Guid, byte[]> >(), Arg.Any <CancellationToken>())
            .Returns(producerResult);

            var serializer = NSubstitute.Substitute.For <ITransportSerializer>();
            var logger     = NSubstitute.Substitute.For <ILogger <KafkaPublisherExecutor> >();

            var sut = new KafkaPublisherExecutor(producer, serializer, logger);

            await sut.PublishAsync(message, topicName);

            await producer.Received(1)
            .ProduceAsync(topicName,
                          Arg.Is((Message <Guid, byte[]> km) => km.Headers.Any(h =>
                                                                               h.Key == HeaderNames.MessageType) &&
                                 km.Key == message.Id));
        }
        public void Resolve_should_return_message()
        {
            var messageType    = typeof(DummyMessage);
            var message        = DummyMessage.New();
            var encodedMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
            var messageBytes   = Encoding.UTF8.GetBytes(encodedMessage);

            var decoder = NSubstitute.Substitute.For <ISerializer>();

            decoder.Deserialize(messageBytes, messageType).Returns(message);

            var resolver = NSubstitute.Substitute.For <ITypeResolver>();

            resolver.Resolve(messageType.FullName).Returns(messageType);

            var sut = new MessageParser(resolver, decoder);

            var consumeResult = new ConsumeResult <Guid, byte[]>()
            {
                Message = new Message <Guid, byte[]>()
                {
                    Headers = new Headers()
                    {
                        { HeaderNames.MessageType, Encoding.UTF8.GetBytes(messageType.FullName) }
                    },
                    Value = messageBytes
                }
            };
            var result = sut.Parse(consumeResult);

            result.Should().Be(message);
        }
        public void Resolve_should_return_message()
        {
            var decoder  = NSubstitute.Substitute.For <ISerializer>();
            var resolver = NSubstitute.Substitute.For <ITypeResolver>();
            var sut      = new MessageParser(decoder, resolver);

            var basicProperties = NSubstitute.Substitute.For <IBasicProperties>();

            var messageType = typeof(DummyMessage);
            var headers     = new Dictionary <string, object>()
            {
                { HeaderNames.MessageType, Encoding.UTF8.GetBytes(messageType.FullName) }
            };

            basicProperties.Headers.Returns(headers);

            var message        = DummyMessage.New();
            var encodedMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
            var messageBytes   = Encoding.UTF8.GetBytes(encodedMessage);

            decoder.Deserialize(messageBytes, messageType).Returns(message);

            resolver.Resolve(messageType.FullName).Returns(messageType);

            var result = sut.Resolve(basicProperties, messageBytes);

            result.Should().Be(message);
        }
        public void Create_should_return_valid_context()
        {
            var channel    = NSubstitute.Substitute.For <IModel>();
            var references = new QueueReferences("exchange", "queue", "routingKey", "deadletterExch", "deadLetterQ");

            var pool = NSubstitute.Substitute.For <IPublisherChannelContextPool>();

            var ctx = new PublisherChannelContext(channel, references, pool);

            pool.Get(references)
            .Returns(ctx);

            var factory = NSubstitute.Substitute.For <IQueueReferenceFactory>();

            factory.Create((IMessage)null)
            .ReturnsForAnyArgs(references);

            var sut = new PublisherChannelFactory(pool, factory);

            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.Channel.Should().Be(channel);
            result.QueueReferences.Should().Be(references);
        }
示例#6
0
        public async Task StartAsync_should_log_exceptions()
        {
            var messages = new[]
            {
                DummyMessage.New(),
            };
            var asyncMessages = GetMessagesAsync(messages);

            var processor = NSubstitute.Substitute.For <IMessageProcessor>();
            var ex        = new Exception("whoops");

            processor.When(p => p.ProcessAsync(messages[0], Arg.Any <CancellationToken>()))
            .Throw(ex);

            var reader = NSubstitute.Substitute.For <ChannelReader <DummyMessage> >();

            reader.ReadAllAsync()
            .ReturnsForAnyArgs(asyncMessages);

            var logger = new FakeLogger <InMemorySubscriber <DummyMessage> >();

            var sut = new InMemorySubscriber <DummyMessage>(processor, reader, logger);
            await sut.StartAsync();

            logger.Logs.Count.Should().Be(1);
            logger.Logs.Should().Contain(l => l.ex == ex);
        }
示例#7
0
        public async Task Can_consume_message_2()
        {
            var dummyMessage = new DummyMessage();
            var messageStub  = new TransportLevelMessageBuilder()
                               .WithType(nameof(DummyMessage))
                               .WithData(dummyMessage)
                               .Build();
            var messageResult = new MessageResultBuilder()
                                .WithTransportLevelMessage(messageStub)
                                .Build();

            var services = new ServiceCollection();

            services.AddScoped <Scoped>();
            services.AddConsumer(options =>
            {
                options.WithBootstrapServers("dummyBootstrapServer");
                options.WithGroupId("dummyGroupId");
                options.RegisterMessageHandler <DummyMessage, DummyMessageHandler>("dummyTopic", nameof(DummyMessage));

                options.WithUnitOfWork <UnitOfWork>();

                options.WithTopicSubscriberScopeFactory(new TopicSubscriberScopeFactoryStub(new TopicSubscriberScopeStub(messageResult)));
            });
            var serviceProvider = services.BuildServiceProvider();

            var consumer = serviceProvider.GetRequiredService <Consumer>();

            await consumer.ConsumeSingle(CancellationToken.None);

            Assert.Equal(dummyMessage, DummyMessageHandler.LastHandledMessage);
            Assert.Equal(1, Scoped.Instanciated);
        }
        public async Task ReadMessagesToProcess_should_not_return_sent_messages()
        {
            var messages = new[]
            {
                DummyMessage.New(),
                DummyMessage.New(),
                DummyMessage.New(),
            };
            var sut = new InMemoryOutboxRepository();

            foreach (var message in messages)
            {
                await sut.AppendAsync(message);
            }

            var lockId = await sut.LockAsync(messages[0]);

            await sut.ReleaseAsync(messages[0], lockId);

            var results = await sut.ReadMessagesToProcess();

            results.Should().NotBeNull()
            .And.HaveCount(2)
            .And.NotContain(messages[0]);
        }
        public async Task CleanProcessedAsync_should_remove_processed_messages()
        {
            var messages = new[]
            {
                DummyMessage.New(),
                DummyMessage.New(),
                DummyMessage.New(),
            };
            var sut = new InMemoryOutboxRepository();

            foreach (var message in messages)
            {
                await sut.AppendAsync(message);
            }

            var results = await sut.ReadMessagesToProcess();

            results.Should().NotBeNull().And.Contain(messages);

            foreach (var message in messages)
            {
                await sut.LockAsync(message);
            }

            await sut.CleanProcessedAsync();

            results = await sut.ReadMessagesToProcess();

            results.Should().NotBeNull().And.BeEmpty();
        }
示例#10
0
        public void Resolve_should_return_message()
        {
            var messageType  = typeof(DummyMessage);
            var messageTopic = "DummyMessage";

            ;            var message = DummyMessage.New();
            var encodedMessage       = Newtonsoft.Json.JsonConvert.SerializeObject(message);
            var messageBytes         = Encoding.UTF8.GetBytes(encodedMessage);

            var decoder = NSubstitute.Substitute.For <ITransportSerializer>();

            decoder.Deserialize(messageBytes, messageType).Returns(message);

            var queueReferenceFactory = NSubstitute.Substitute.For <IQueueReferenceFactory>();

            queueReferenceFactory.GetQueueType(messageTopic).Returns(messageType);

            var sut = new MessageParser(decoder, queueReferenceFactory);

            var consumeResult = new ConsumeResult <Guid, byte[]>()
            {
                Topic   = messageTopic,
                Message = new Message <Guid, byte[]>()
                {
                    Value = messageBytes
                }
            };
            var result = sut.Parse(consumeResult);

            result.Should().Be(message);
        }
        public async Task MarkAsSentAsync_should_throw_when_message_lock_id_invalid()
        {
            var message = DummyMessage.New();
            var sut     = new InMemoryOutboxRepository();

            await sut.AppendAsync(message);

            await Assert.ThrowsAsync <ArgumentException>(async() => await sut.ReleaseAsync(message, Guid.Empty));
        }
示例#12
0
        /// <summary>
        /// 发送piece信息
        /// pieces: <len=0009+X><id=7><index><begin><block>
        /// </summary>
        /// <param name="index">片断索引号</param>
        /// <param name="begin">子片断的起始位置</param>
        /// <param name="pieces">子片断的数据</param>
        public void SendPiece(int index, int begin, byte[] pieces)
        {
            //更新上传速率
            connecter.UpdateUploadRate(pieces.Length);

            //发送piece信息
            message = DummyMessageFactory.GetPieceMessage(index, begin, pieces);
            encryptedConnection.SendMessage(message.Encode());
        }
示例#13
0
        public void CanInvokeHelper()
        {
            var handler        = new DummyMessageHandler();
            var genericHandler = handler as IMessageHandler <DummyMessage>;
            var message        = new DummyMessage();

            BusWrapper.InvokeHandlerWrapper(genericHandler, message);

            Assert.AreEqual(1, handler.Count);
        }
        public async Task BeginProcessingAsync_should_throw_when_message_already_locked()
        {
            var message = DummyMessage.New();

            var sut = new InMemoryOutboxRepository();
            await sut.AppendAsync(message);

            await sut.LockAsync(message);

            await Assert.ThrowsAsync <LockException>(async() => await sut.LockAsync(message));
        }
        public void Create_should_return_valid_references()
        {
            var sp      = NSubstitute.Substitute.For <IServiceProvider>();
            var sut     = new QueueReferenceFactory(sp);
            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.TopicName.Should().Be("dummymessage");
            result.DeadLetterTopicName.Should().Be("dummymessage.dead");
        }
示例#16
0
        public void Serialize_should_return_json_bytes_from_class()
        {
            var sut = new KeySerializer <DummyMessage>();

            var message      = DummyMessage.New();
            var jsonMessage  = JsonSerializer.Serialize(message);
            var expectedData = Encoding.UTF8.GetBytes(jsonMessage);

            var result = sut.Serialize(message, default);

            result.Should().BeEquivalentTo(expectedData);
        }
        public void Create_should_return_valid_references()
        {
            var sut     = new QueueReferenceFactory();
            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.ExchangeName.Should().Be("dummymessage");
            result.QueueName.Should().Be("dummymessage.workers");
            result.DeadLetterExchangeName.Should().Be("dummymessage.dead");
            result.DeadLetterQueue.Should().Be("dummymessage.dead.workers");
        }
示例#18
0
 public void Handle(DummyMessage message)
 {
     Data.Identifier = message.Id;
     TimesDummyMessageHandlerExecuted++;
     if (FirstHandle != null)
     {
         FirstHandle.Set();
     }
     bus.Send(new MessageSentBySaga()
     {
         Id = message.Id
     });
 }
示例#19
0
        public void Create_should_return_valid_references()
        {
            var sp      = NSubstitute.Substitute.For <IServiceProvider>();
            var sysInfo = SystemInfo.New();
            var sut     = new QueueReferenceFactory(sp, sysInfo);
            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.ExchangeName.Should().Be("dummymessage");
            result.QueueName.Should().Be("dummymessage.workers");
            result.DeadLetterExchangeName.Should().Be("dummymessage.dead");
            result.DeadLetterQueue.Should().Be("dummymessage.dead.workers");
        }
        public void Cannot_start_process_manager_with_events_other_than_start_events()
        {
            IProcessManager <TestProcessManagerState, string> processManager = null;

            var testMessage = new DummyMessage <TestEventEnd>("processId", new TestEventEnd("aggregateId"));

            A.CallTo(() => processManagerRepository.Get(typeof(TestProcessManager), "processId")).ReturnsLazily(() => processManager);
            A.CallTo(() => processManagerRepository.Save(A <IProcessManager> ._)).Invokes(x => processManager = (IProcessManager <TestProcessManagerState, string>)x.Arguments[0]);

            target.Register <TestProcessManager>();

            ((Action)(() => target.Handle(testMessage))).Should().Throw <InvalidOperationException>()
            .And.Message.Contains("does not match any start events for").Should().Be(true);
        }
示例#21
0
        public void TestSerialise()
        {
            var message = new DummyMessage {
                MessageProperty = "Something"
            };

            var serialised =
                new JsonMessageSerialiser(this._messageTypeDictionary).Serialise(
                    new Envelope <DummyMessage> {
                Message = message
            });

            Assert.IsFalse(string.IsNullOrEmpty(serialised));
        }
        public void Should_send_to_first_destination()
        {
            var routingSlip = new RoutingSlipBuilder().CreateRoutingSlip(Guid.NewGuid(), "foo");

            var bus = new Bus();
            var router = new Router(bus);

            var message = new DummyMessage();
            router.SendToFirstStep(message, routingSlip);

            bus.GetMessageHeader(message, Router.RoutingSlipHeaderKey).ShouldNotBeNull();
            bus.ExplicitlySent.Count().ShouldEqual(1);
            bus.ExplicitlySent.First().Item1.ShouldEqual("foo");
            bus.ExplicitlySent.First().Item2.ShouldEqual(message);
        }
 public void ReadWriteBinSerMsgs()
 {
     using (var ms = new MemoryStream())
     {
         var dm = new DummyMessage()
         {
             I = 1, D = 2.2, S = "Test"
         };
         _sh.BinarySerialize(ms, dm);
         ms.Seek(0, SeekOrigin.Begin);
         var dmds = (DummyMessage)_sh.BinaryDeserialize(ms);
         Assert.AreEqual(dm.I, dmds.I);
         Assert.AreEqual(dm.D, dmds.D);
         Assert.AreEqual(dm.S, dmds.S);
     }
 }
        public async Task Should_send_to_first_destination()
        {
            var bus = new TestableMessageSession();

            var message = new DummyMessage();

            await((IMessageSession)bus).Route(message, Guid.NewGuid(), "foo");

            bus.SentMessages.Length.ShouldBe(1);

            var sentMessage = bus.SentMessages[0];

            sentMessage.Options.GetHeaders()[Router.RoutingSlipHeaderKey].ShouldNotBeNull();
            sentMessage.Options.GetDestination().ShouldBe("foo");
            sentMessage.Message.ShouldBe(message);
        }
示例#25
0
        public static async Task <DummyMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [Dummy(ConStr = "MyConStrSetting")] DummyMessage inDummy,
            ILogger log)
        {
            // output binding
            DummyMessage outDummy = new DummyMessage
            {
                Id   = "Sending out from",
                Name = inDummy.Name
            };

            // print the input binding to screen
            //return new OkObjectResult($"I got Id: {inDummy.Id} and Name: {inDummy.Name} from the binding");
            return(outDummy);
        }
示例#26
0
        public void Should_send_to_first_destination()
        {
            var routingSlip = new RoutingSlipBuilder().CreateRoutingSlip(Guid.NewGuid(), "foo");

            var bus    = new Bus();
            var router = new Router(bus);

            var message = new DummyMessage();

            router.SendToFirstStep(message, routingSlip);

            bus.GetMessageHeader(message, Router.RoutingSlipHeaderKey).ShouldNotBeNull();
            bus.ExplicitlySent.Count().ShouldEqual(1);
            bus.ExplicitlySent.First().Item1.ShouldEqual("foo");
            bus.ExplicitlySent.First().Item2.ShouldEqual(message);
        }
        public void Create_should_use_default_creator_when_none_defined()
        {
            var sp  = NSubstitute.Substitute.For <IServiceProvider>();
            var sut = new QueueReferenceFactory(sp, messageType =>
            {
                var topicName = messageType.Name.ToLower();
                return(new QueueReferences(topicName, topicName + ".dead"));
            });

            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.TopicName.Should().Be("dummymessage");
            result.DeadLetterTopicName.Should().Be("dummymessage.dead");
        }
示例#28
0
        public async Task Has_expected_number_of_creations_and_disposals_when_singleton()
        {
            var dummyMessage = new DummyMessage();
            var messageStub  = new TransportLevelMessageBuilder()
                               .WithType(nameof(DummyMessage))
                               .WithData(dummyMessage)
                               .Build();
            var messageResult = new MessageResultBuilder()
                                .WithTransportLevelMessage(messageStub)
                                .Build();

            var services = new ServiceCollection();

            services.AddTransient <Repository>();
            services.AddSingleton <IHostApplicationLifetime, DummyApplicationLifetime>();
            services.AddTransient <DummyMessageHandler>();
            services.AddLogging();

            var createCount  = 0;
            var disposeCount = 0;

            services.AddSingleton <ScopeSpy>(provider => new ScopeSpy(onCreate: () => createCount++, onDispose: () => disposeCount++));

            var serviceProvider = services.BuildServiceProvider();

            var consumerConfiguration = new ConsumerConfigurationBuilder()
                                        .WithGroupId("dummy")
                                        .WithBootstrapServers("dummy")
                                        .RegisterMessageHandler <DummyMessage, DummyMessageHandler>("dummyTopic", nameof(DummyMessage))
                                        .WithConsumerScopeFactory(_ => new ConsumerScopeFactoryStub(new ConsumerScopeStub(messageResult)))
                                        .WithUnitOfWorkFactory(new ServiceProviderUnitOfWorkFactory(serviceProvider))
                                        .Build();

            var consumer = new ConsumerBuilder()
                           .WithMessageHandlerRegistry(consumerConfiguration.MessageHandlerRegistry)
                           .WithUnitOfWorkFactory(consumerConfiguration.UnitOfWorkFactory)
                           .WithConsumerScopeFactory(consumerConfiguration.ConsumerScopeFactory)
                           .WithEnableAutoCommit(consumerConfiguration.EnableAutoCommit)
                           .Build();

            await consumer.ConsumeSingle(CancellationToken.None);

            await consumer.ConsumeSingle(CancellationToken.None);

            Assert.Equal(1, createCount);
            Assert.Equal(0, disposeCount);
        }
        public void Publish_FakeMessage_ShouldInvokeOneHandler()
        {
            // Arrange
            IMessageBus <DummyMessage>      messageBus = new MemoryMessageBus <DummyMessage>();
            Mock <IHandler <DummyMessage> > mock       = new Mock <IHandler <DummyMessage> >();

            mock.Setup(x => x.Handle(It.IsNotNull <DummyMessage>()));
            IHandler <DummyMessage> fakeMessageHandler = mock.Object;
            DummyMessage            dummyMessage       = new DummyMessage();

            // Act
            messageBus.Subscribe(fakeMessageHandler);
            messageBus.Publish(dummyMessage);

            // Assert
            mock.Verify(m => m.Handle(It.IsNotNull <DummyMessage>()), Times.Once);
        }
示例#30
0
        public async Task PublishAsync_should_write_message_to_proper_channel()
        {
            var message = DummyMessage.New();

            var channelFactory = NSubstitute.Substitute.For <IChannelFactory>();
            var writer         = NSubstitute.Substitute.For <ChannelWriter <DummyMessage> >();

            channelFactory.GetWriter <DummyMessage>()
            .Returns(writer);

            var sut = new InMemoryPublisher(channelFactory);

            await sut.PublishAsync(message);

            await writer.Received(1)
            .WriteAsync(message, Arg.Any <CancellationToken>());
        }
        public void Create_should_return_valid_context()
        {
            var connection = NSubstitute.Substitute.For <IBusConnection>();
            var factory    = NSubstitute.Substitute.For <IQueueReferenceFactory>();
            var references = new QueueReferences("exchange", "queue", "deadletterExch", "deadLetterQ");

            factory.Create(null)
            .ReturnsForAnyArgs(references);

            var sut = new PublisherChannelFactory(connection, factory);

            var message = DummyMessage.New();
            var result  = sut.Create(message);

            result.Should().NotBeNull();
            result.Channel.Should().NotBeNull();
            result.QueueReferences.Should().Be(references);
        }