Inheritance: ServiceConnect.Interfaces.Message
        public void CreateStreamShouldSendARequestMessageToTheSpecifiedEndpoint()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<string>(), It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(task.Start);

            // Act
            var bus = new Bus(mockConfiguration.Object);

            // Act
            bus.CreateStream("TestEndpoint", message);

            // Assert
            mockProducer.Verify(x => x.Send("TestEndpoint",It.IsAny<Type>(), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(y => y["MessageType"] == "ByteStream" && y.ContainsKey("Start"))));
        }
        public void StartMessageShouldCreateANewMessageBusReadStream()
        {
            // Arrange
            var bus = new Bus(_mockConfiguration.Object);

            var mockStream = new Mock<IMessageBusReadStream>();
            mockStream.Setup(x => x.HandlerCount).Returns(1);
            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.IsAny<IList<string>>(), It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<IConfiguration>()));
            var mockProcessor = new Mock<IStreamProcessor>();
            _mockContainer.Setup(x => x.GetInstance<IStreamProcessor>(It.Is<Dictionary<string, object>>(y => y["container"] == _mockContainer.Object))).Returns(mockProcessor.Object);
            mockProcessor.Setup(x => x.ProcessMessage(It.IsAny<FakeMessage1>(), mockStream.Object));
            _mockConfiguration.Setup(x => x.GetMessageBusReadStream()).Returns(mockStream.Object);
            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            bus.StartConsuming();

            // Act
            _fakeEventHandler(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), typeof(FakeMessage1).AssemblyQualifiedName, new Dictionary<string, object>
            {
                { "Start", "" },
                { "SequenceId", Encoding.UTF8.GetBytes("TestSequence") },
                { "SourceAddress", Encoding.UTF8.GetBytes("Source") },
                { "RequestMessageId", Encoding.UTF8.GetBytes("MessageId") },
                { "MessageType", Encoding.UTF8.GetBytes("ByteStream")}
            });

            // Assert
            mockProcessor.Verify(x => x.ProcessMessage(It.IsAny<FakeMessage1>(), It.IsAny<IMessageBusReadStream>()), Times.Once);
        }
        public void CreateStreamShouldCreateAMessageBusWriteStream()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();
            var mockStream = new Mock<IMessageBusWriteStream>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings ());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            mockConfiguration.Setup(x=> x.GetMessageBusWriteStream(It.IsAny<IProducer>(), "TestEndpoint", It.IsAny<string>(), It.IsAny<IConfiguration>())).Returns(mockStream.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<string>(), It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(task.Start);

            // Act
            var bus = new Bus(mockConfiguration.Object);

            // Act
            var stream = bus.CreateStream("TestEndpoint", message);

            // Assert
            Assert.NotNull(stream);
            Assert.Equal(mockStream.Object, stream);
        }
        public void ShouldExecuteTheCorrectHandlers()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object);

            var message1HandlerReference = new HandlerReference
            {
                HandlerType = typeof (FakeHandler1),
                MessageType = typeof (FakeMessage1)
            };


            _mockContainer.Setup(x => x.GetHandlerTypes(typeof(IMessageHandler<FakeMessage1>))).Returns(new List<HandlerReference>
            {
                message1HandlerReference
            });

            var fakeHandler = new FakeHandler1();
            _mockContainer.Setup(x => x.GetInstance(typeof (FakeHandler1))).Returns(fakeHandler);

            // Act
            var message1 = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };
            messageProcessor.ProcessMessage<FakeMessage1>(JsonConvert.SerializeObject(message1), null);

            var message2 = new FakeMessage2(Guid.NewGuid())
            {
                DisplayName = "Tim Watson"
            };

            messageProcessor.ProcessMessage<FakeMessage2>(JsonConvert.SerializeObject(message2), null);

            // Assert
            Assert.Equal(message1.CorrelationId, fakeHandler.Command.CorrelationId);
            Assert.Equal(message1.Username, fakeHandler.Command.Username);
            _mockContainer.Verify(x => x.GetInstance(typeof (FakeHandler2)), Times.Never);
        }
        public void TimerShouldGetMessagesFromAggregatorAndExecuteHandler()
        {
            // Arrange
            var mockPersistor = new Mock<IAggregatorPersistor>();
            var mockContainer = new Mock<IBusContainer>();

            var timer = new AggregatorProcessor(mockPersistor.Object, mockContainer.Object, typeof(FakeAggregator));

            mockPersistor.Setup(x => x.Count(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(1);
            var aggregator = new FakeAggregator();
            var message = new FakeMessage1(Guid.NewGuid());
            mockContainer.Setup(x => x.GetInstance(typeof (FakeAggregator))).Returns(aggregator);
            mockPersistor.Setup(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(new List<object>{ message });

            // Act
            timer.StartTimer<FakeMessage1>(new TimeSpan(0, 0, 0, 0, 50));
            Thread.Sleep(90);

            // Assert 
            mockPersistor.Verify(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName), Times.Once);
            Assert.Equal(1, aggregator.Messages.Count);
            Assert.Equal(message, aggregator.Messages.First());
            timer.Dispose();
        }
        public void TimerShouldRemoveAllProcessedMessagesFromPersistor()
        {
            // Arrange
            var mockPersistor = new Mock<IAggregatorPersistor>();
            var mockContainer = new Mock<IBusContainer>();

            var timer = new AggregatorProcessor(mockPersistor.Object, mockContainer.Object, typeof(FakeAggregator));

            mockPersistor.Setup(x => x.Count(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(1);
            var aggregator = new FakeAggregator();
            var message = new FakeMessage1(Guid.NewGuid());
            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(aggregator);
            mockPersistor.Setup(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(new List<object> { message });

            // Act
            timer.StartTimer<FakeMessage1>(new TimeSpan(0, 0, 0, 0, 50));
            Thread.Sleep(100);

            // Assert 
            mockPersistor.Verify(x => x.RemoveData(typeof(FakeMessage1).AssemblyQualifiedName, message.CorrelationId), Times.Once);
           
            timer.Dispose();
        }
        public void SendShouldSendCommandUsingSpecifiedEndpoints()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockProessManagerFinder = new Mock<IProcessManagerFinder>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProcessManagerFinder()).Returns(mockProessManagerFinder.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            List<string> endPoints = new List<string> { "MyEndPoint1", "MyEndPoint2" };

            foreach (string endPoint in endPoints)
            {
                mockProducer.Setup(x => x.Send(endPoint, typeof(FakeMessage1), It.IsAny<byte[]>(), null));
            }

            // Act
            var bus = new ServiceConnect.Bus(mockConfiguration.Object);
            bus.Send(endPoints, message, null);

            // Assert
            foreach (string endPoint in endPoints)
            {
                mockProducer.Verify(x => x.Send(endPoint, typeof(FakeMessage1), It.IsAny<byte[]>(), null), Times.Once);
            }
        }
        public void SendShouldSendCommand()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockProessManagerFinder = new Mock<IProcessManagerFinder>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProcessManagerFinder()).Returns(mockProessManagerFinder.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(typeof(FakeMessage1), It.IsAny<byte[]>(), null));

            // Act
            var bus = new ServiceConnect.Bus(mockConfiguration.Object);
            bus.Send(message, null);

            // Assert
            mockProducer.Verify(x => x.Send(typeof(FakeMessage1), It.IsAny<byte[]>(), null), Times.Once);
        }
        public void SendingRequestWithCallbackShouldSendCommand()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(typeof(FakeMessage1), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()));

            // Act
            var bus = new Bus(mockConfiguration.Object);
            bus.SendRequest<FakeMessage1, FakeMessage2>(message, x => { }, null);

            // Assert
            mockProducer.Verify(x => x.Send(typeof(FakeMessage1), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()), Times.Once);
        }
        public void SendingRequestToMultipleEndpointsSynchronouslyShouldReturnResponses()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });

            Action<FakeMessage2> action = null;
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task).Callback<Action<FakeMessage2>>(r =>
            {
                action = r;
            });

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            var r1 = new FakeMessage2(Guid.NewGuid());
            var r2 = new FakeMessage2(Guid.NewGuid());

            mockProducer.Setup(x => x.Send("test1", It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(() =>
            {
                action(r1);
            });

            mockProducer.Setup(x => x.Send("test2", It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(() =>
            {
                action(r2);
                task.Start();
            });

            // Act
            var bus = new Bus(mockConfiguration.Object);
            IList<FakeMessage2> responses = bus.SendRequest<FakeMessage1, FakeMessage2>(new List<string>{ "test1", "test2" }, message, null, 1000);

            // Assert
            Assert.Equal(2, responses.Count);
            Assert.True(responses.Contains(r1));
            Assert.True(responses.Contains(r2));
        }
        public void SendingRequestToMultipleEndpointsShouldPassResponsesToCallbackHandler()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });

            int count = 0;
            var r1 = new FakeMessage2(Guid.NewGuid());
            var r2 = new FakeMessage2(Guid.NewGuid());

            var responses = new List<FakeMessage2>();
            Action<FakeMessage2> action = message2 =>
            {
                count++;
                responses.Add(message2);
            };

            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Callback<Action<object>>(a =>
            {
                a(r1);
                a(r2);
            }).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()));

            // Act
            var bus = new Bus(mockConfiguration.Object);
            bus.SendRequest(message, action, null);

            // Assert
            mockRequestConfiguration.Verify(x => x.SetHandler(It.IsAny<Action<object>>()), Times.Exactly(1));
            Assert.Equal(2, count);
            Assert.True(responses.Contains(r1));
            Assert.True(responses.Contains(r2));
        }
        public void RouteShouldSendCommandWithRoutingSlipHeader()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockProessManagerFinder = new Mock<IProcessManagerFinder>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProcessManagerFinder()).Returns(mockProessManagerFinder.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            const string endPoint1 = "MyEndPoint1";
            const string endPoint2 = "MyEndPoint2";

            mockProducer.Setup(x => x.Send(endPoint1, It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()));

            // Act
            var bus = new ServiceConnect.Bus(mockConfiguration.Object);
            bus.Route(message, new List<string> { endPoint1, endPoint2 });

            // Assert
            mockProducer.Verify(x => x.Send(endPoint1, It.IsAny<Type>(), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(i => i.Count == 1)), Times.Once);
            mockProducer.Verify(x => x.Send(endPoint1, It.IsAny<Type>(), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(i => i.ContainsKey("RoutingSlip"))), Times.Once);
            mockProducer.Verify(x => x.Send(endPoint1, It.IsAny<Type>(), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(i => i.ContainsValue("[\"MyEndPoint2\"]"))), Times.Once);
        }
        public void PublishWithRoutingKeyShouldPublishMessage()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockProessManagerFinder = new Mock<IProcessManagerFinder>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProcessManagerFinder()).Returns(mockProessManagerFinder.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Publish(typeof(FakeMessage1), It.IsAny<byte[]>(), null));

            // Act
            var bus = new ServiceConnect.Bus(mockConfiguration.Object);
            bus.Publish(message, "routingkey1");

            // Assert
            mockProducer.Verify(x => x.Publish(typeof(FakeMessage1), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(i => i.ContainsKey("RoutingKey"))), Times.Once);
        }
        public void PublishRequestShouldPublishMessagesAndReturnResponses()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockProessManagerFinder = new Mock<IProcessManagerFinder>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProcessManagerFinder()).Returns(mockProessManagerFinder.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());

            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });

            Action<FakeMessage2> action = null;
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task).Callback<Action<FakeMessage2>>(r =>
            {
                action = r;
            });

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            var r1 = new FakeMessage2(Guid.NewGuid());
            var r2 = new FakeMessage2(Guid.NewGuid());

            mockProducer.Setup(x => x.Publish(It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(() =>
            {
                action(r1);
                action(r2);
                task.Start();
            });

            // Act
            var bus = new Bus(mockConfiguration.Object);
            var responses = bus.PublishRequest<FakeMessage1, FakeMessage2>(message, 1, null, 1000);

            // Assert
            Assert.Equal(2, responses.Count);
            Assert.True(responses.Contains(r1));
            Assert.True(responses.Contains(r2));
        }
        public void ConsumeMessageEventShouldProcessResponseMessage()
        {
            // Arrange
            var mockProducer = new Mock<IProducer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();
            _mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);

            var bus = new Bus(_mockConfiguration.Object);

            var handlerReferences = new List<HandlerReference>
            {
                new HandlerReference
                {
                    HandlerType = typeof (FakeHandler1),
                    MessageType = typeof (FakeMessage1)
                },
                new HandlerReference
                {
                    HandlerType = typeof (FakeHandler2),
                    MessageType = typeof (FakeMessage2)
                }
            };

            var headers = new Dictionary<string, object>
            {
                { "MessageType", Encoding.ASCII.GetBytes("Send") }
            };
            _mockContainer.Setup(x => x.GetHandlerTypes()).Returns(handlerReferences);
            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.IsAny<IList<string>>(), It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<IConfiguration>()));
            var mockMessageHandlerProcessor = new Mock<IMessageHandlerProcessor>();
            _mockContainer.Setup(x => x.GetInstance<IMessageHandlerProcessor>(It.Is<Dictionary<string, object>>(y => y["container"] == _mockContainer.Object))).Returns(mockMessageHandlerProcessor.Object);
            mockMessageHandlerProcessor.Setup(x => x.ProcessMessage<FakeMessage2>(It.IsAny<string>(), It.Is<IConsumeContext>(y => y.Headers == headers)));
            var mockProcessManagerProcessor = new Mock<IProcessManagerProcessor>();
            _mockContainer.Setup(x => x.GetInstance<IProcessManagerProcessor>(It.IsAny<Dictionary<string, object>>())).Returns(mockProcessManagerProcessor.Object);
            mockProcessManagerProcessor.Setup(x => x.ProcessMessage<FakeMessage2>(It.IsAny<string>(), It.Is<IConsumeContext>(y => y.Headers == headers)));

            _mockConfiguration.Setup(x => x.GetRequestConfiguration(It.Is<Guid>(y => SetCorrelationId(y)))).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var id = Guid.NewGuid();

            var message = new FakeMessage1(id)
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()));

            bus.SendRequest<FakeMessage1, FakeMessage2>(message, x => { }, null);
            bus.StartConsuming();

            headers["SourceAddress"] = Encoding.ASCII.GetBytes(_correlationId.ToString());

            var message2 = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new FakeMessage2(id)
            {
            }));

            // Act
            _fakeEventHandler(message2, typeof(FakeMessage2).AssemblyQualifiedName, headers);

            // Assert
            mockMessageHandlerProcessor.Verify(x => x.ProcessMessage<FakeMessage2>(It.Is<string>(y => ((FakeMessage2)JsonConvert.DeserializeObject(y, typeof(FakeMessage2))).CorrelationId == id), It.Is<IConsumeContext>(y => y.Headers == headers)), Times.Once);
        }
        public void ShouldSendMessageToAggregatorProcessor()
        {
            // Arrange
            
            var bus = new Bus(_mockConfiguration.Object);

            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.IsAny<IList<string>>(), It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<IConfiguration>()));
            var mockPersistor = new Mock<IAggregatorPersistor>();
            var mockProcessor = new Mock<IAggregatorProcessor>();
            var fakeAggregator = new FakeAggregator();

            _mockConfiguration.Setup(x => x.GetAggregatorPersistor()).Returns(mockPersistor.Object);
            _mockConfiguration.Setup(x => x.Threads).Returns(1);
            _mockContainer.Setup(x => x.GetInstance<IMessageHandlerProcessor>(It.IsAny<Dictionary<string, object>>())).Returns(new Mock<IMessageHandlerProcessor>().Object);
            _mockContainer.Setup(x => x.GetInstance<IProcessManagerProcessor>(It.IsAny<Dictionary<string, object>>())).Returns(new Mock<IProcessManagerProcessor>().Object);
            _mockConfiguration.Setup(x => x.GetAggregatorProcessor(It.IsAny<IAggregatorPersistor>(), It.IsAny<IBusContainer>(), It.IsAny<Type>())).Returns(mockProcessor.Object);
            _mockContainer.Setup(x => x.GetHandlerTypes()).Returns(new List<HandlerReference>
            {
                new HandlerReference
                {
                    HandlerType = typeof (FakeAggregator),
                    MessageType = typeof (FakeMessage1)
                }
            });
            _mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(fakeAggregator);
            
            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProcessor.Setup(x => x.ProcessMessage<FakeMessage1>(JsonConvert.SerializeObject(message)));
                
            bus.StartConsuming();

            // Act
            _fakeEventHandler(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), typeof(FakeMessage1).AssemblyQualifiedName, new Dictionary<string, object>
            {
                { "MessageType", Encoding.UTF8.GetBytes("Send")}
            });

            // Assert
            mockProcessor.Verify(x => x.ProcessMessage<FakeMessage1>(It.Is<string>(y => JsonConvert.DeserializeObject<FakeMessage1>(y).Username == "Tim")), Times.Once);
        }
        public void SendingRequestWithEndpointAndCallbackShouldPassCallbackToHandler()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });

            bool actionCalled = false;
            Action<FakeMessage2> action = message2 => { actionCalled = true; };

            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Callback<Action<object>>(a => a(new FakeMessage2(Guid.NewGuid()))).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()));

            // Act
            var bus = new Bus(mockConfiguration.Object);
            bus.SendRequest("test", message, action, null);

            // Assert
            mockRequestConfiguration.Verify(x => x.SetHandler(It.IsAny<Action<object>>()), Times.Once());
            Assert.True(actionCalled);
        }
        public void SendingRequestWithEndpointSynchronouslyShouldReturnResponse()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });

            Action<FakeMessage2> action = null;
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task)
                                                                                               .Callback<Action<FakeMessage2>>(r => action = r);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send("test", It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(() =>
            {
                action(new FakeMessage2(message.CorrelationId)
                {
                    DisplayName = "Tim Watson",
                    Email = "*****@*****.**"
                });
                task.Start();
            });

            // Act
            var bus = new Bus(mockConfiguration.Object);
            FakeMessage2 response = bus.SendRequest<FakeMessage1, FakeMessage2>("test", message, null, 1000);

            // Assert
            Assert.Equal("Tim Watson", response.DisplayName);
            Assert.Equal("*****@*****.**", response.Email);
            Assert.Equal(message.CorrelationId, response.CorrelationId);
        }
        public void ConsumeMessageEventShouldStopStreamIfStopMessageIsRecieved()
        {
            // Arrange
            var bus = new Bus(_mockConfiguration.Object);

            var mockStream = new Mock<IMessageBusReadStream>();
            mockStream.Setup(x => x.HandlerCount).Returns(1);
            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.IsAny<IList<string>>(), It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<IConfiguration>()));
            var mockProcessor = new Mock<IStreamProcessor>();
            _mockContainer.Setup(x => x.GetInstance<IStreamProcessor>(It.Is<Dictionary<string, object>>(y => y["container"] == _mockContainer.Object))).Returns(mockProcessor.Object);
            mockProcessor.Setup(x => x.ProcessMessage(It.IsAny<FakeMessage1>(), mockStream.Object));
            _mockConfiguration.Setup(x => x.GetMessageBusReadStream()).Returns(mockStream.Object);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            _mockProducer.Setup(x => x.Send("Source", typeof(StreamResponseMessage), It.IsAny<byte[]>(), It.Is<Dictionary<string, string>>(y => y["ResponseMessageId"] == "MessageId")));

            bus.StartConsuming();

            _fakeEventHandler(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), typeof(FakeMessage1).AssemblyQualifiedName, new Dictionary<string, object>
            {
                { "Start", "" },
                { "SequenceId", Encoding.UTF8.GetBytes("TestSequence") },
                { "SourceAddress", Encoding.UTF8.GetBytes("Source") },
                { "RequestMessageId", Encoding.UTF8.GetBytes("MessageId") },
                { "MessageType", Encoding.UTF8.GetBytes("ByteStream")},
                 
            });

            var streamMessage = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // Act
            _fakeEventHandler(streamMessage, typeof(byte[]).AssemblyQualifiedName, new Dictionary<string, object>
            {
                { "SequenceId", Encoding.UTF8.GetBytes("TestSequence") },
                { "SourceAddress", Encoding.UTF8.GetBytes("Source") },
                { "RequestMessageId", Encoding.UTF8.GetBytes("MessageId") },
                { "MessageType", Encoding.UTF8.GetBytes("ByteStream")},
                { "PacketNumber", Encoding.UTF8.GetBytes("2")},
                { "Stop", "" }
            });

            // Assert 
            mockStream.Verify(x => x.Write(It.IsAny<byte[]>(), It.IsAny<long>()), Times.Never);
            mockStream.VerifySet(x => x.LastPacketNumber = 2, Times.Once);
        }
        public void SendingRequestWithEndpointSynchronouslyShouldSendMessageToTheSpecifiedEndPoint()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send("test", typeof(FakeMessage1), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(task.Start);

            // Act
            var bus = new Bus(mockConfiguration.Object);
            FakeMessage2 response = bus.SendRequest<FakeMessage1, FakeMessage2>("test", message, null, 1000);

            // Assert
            mockProducer.Verify(x => x.Send("test", typeof(FakeMessage1), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>()), Times.Once);
        }
        public void ShouldExecuteTheCorrectHandlerWithRoutingKeyAttribute()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object);

            var message1HandlerReference = new HandlerReference
            {
                HandlerType = typeof(FakeHandlerWithAttr1),
                MessageType = typeof(FakeMessage1),
                RoutingKeys = new List<string> { "Test"}
            };

            _mockContainer.Setup(x => x.GetHandlerTypes(typeof(IMessageHandler<FakeMessage1>))).Returns(new List<HandlerReference>
            {
                message1HandlerReference
            });

            var fakeHandler = new FakeHandlerWithAttr1();
            _mockContainer.Setup(x => x.GetInstance(typeof(FakeHandlerWithAttr1))).Returns(fakeHandler);

            // Act
            var message1 = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };
            messageProcessor.ProcessMessage<FakeMessage1>(JsonConvert.SerializeObject(message1),
                new ConsumeContext {Headers = new Dictionary<string, object> {{"RoutingKey", Encoding.ASCII.GetBytes("Test") }}});

            // Assert
            Assert.Equal(message1.CorrelationId, fakeHandler.Command.CorrelationId);
            Assert.Equal(message1.Username, fakeHandler.Command.Username);
            _mockContainer.Verify(x => x.GetInstance(typeof(FakeHandlerWithAttr1)), Times.Once);
        }
        public void ShouldExecuteTheCorrectHandlers()
        {
            // Arrange
            var bus = new MessageBus.Bus(_mockConfiguration.Object);

            var message1HandlerReference = new HandlerReference
            {
                HandlerType = typeof (FakeHandler1),
                MessageType = typeof (FakeMessage1)
            };

            var handlerReferences = new List<HandlerReference>
            {
                message1HandlerReference,
                new HandlerReference
                {
                    HandlerType = typeof (FakeHandler2),
                    MessageType = typeof (FakeMessage2)
                }
            };

            _mockContainer.Setup(x => x.GetHandlerTypes()).Returns(handlerReferences);
            _mockConsumer.Setup(x => x.StartConsuming(It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<string>(), It.IsAny<string>()));
            _mockContainer.Setup(x => x.GetHandlerTypes(typeof(IMessageHandler<FakeMessage1>))).Returns(new List<HandlerReference>
            {
                message1HandlerReference
            });
            var fakeHandler = new FakeHandler1();
            _mockContainer.Setup(x => x.GetInstance(typeof (FakeHandler1))).Returns(fakeHandler);

            bus.StartConsuming();

            // Act
            var message1 = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };
            _fakeEventHandler(Encoding.UTF8.GetBytes(_serializer.Serialize(message1)));

            var message2 = new FakeMessage2(Guid.NewGuid())
            {
                DisplayName = "Tim Watson"
            };

            _fakeEventHandler(Encoding.UTF8.GetBytes(_serializer.Serialize(message2)));

            // Assert
            Assert.Equal(message1.CorrelationId, fakeHandler.Command.CorrelationId);
            Assert.Equal(message1.Username, fakeHandler.Command.Username);
            _mockContainer.Verify(x => x.GetInstance(typeof (FakeHandler2)), Times.Never);
        }