Ejemplo n.º 1
0
        public void ShouldFindTheAggregatorForTheMessageType()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();
            var mockLogger = new Mock <ILogger>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes(typeof(Aggregator <FakeMessage1>))).Returns(new List <HandlerReference> {
                handlerRef
            });
            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(new FakeAggregator
            {
                Time = new TimeSpan(0, 0, 0, 1)
            });
            mockAggregatorPersistor.Setup(x => x.InsertData(It.IsAny <Message>(), It.IsAny <string>()));


            var aggregator = new AggregatorProcessor(mockAggregatorPersistor.Object, mockContainer.Object, typeof(FakeAggregator), mockLogger.Object);

            // Act
            aggregator.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(new FakeMessage1(Guid.NewGuid())));

            // Assert
            mockContainer.Verify(x => x.GetInstance(typeof(FakeAggregator)), Times.Once());
        }
Ejemplo n.º 2
0
        public void IfTimerIsNotSetAndBatchSizeIsNotSetThenBatchSizeIsSetTo10()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();
            var mockLogger = new Mock <ILogger>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes(typeof(Aggregator <FakeMessage1>))).Returns(new List <HandlerReference> {
                handlerRef
            });
            var aggregator = new FakeAggregator();

            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(aggregator);
            mockAggregatorPersistor.Setup(x => x.InsertData(It.IsAny <Message>(), It.IsAny <string>()));

            mockAggregatorPersistor.Setup(x => x.Count(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(10);
            mockAggregatorPersistor.Setup(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(new List <object>());

            var aggregatorProcessor = new AggregatorProcessor(mockAggregatorPersistor.Object, mockContainer.Object, typeof(FakeAggregator), mockLogger.Object);

            // Act
            aggregatorProcessor.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(new FakeMessage1(Guid.NewGuid())));

            // Assert
            // Only calls this if batchsize is equal to number of messages in persistance store.
            mockAggregatorPersistor.Verify(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName), Times.Once);
        }
Ejemplo n.º 3
0
        public void ShouldNotExecuteAggregatorIfBatchSizeHasntBeenSet()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();
            var mockLogger = new Mock <ILogger>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes(typeof(Aggregator <FakeMessage1>))).Returns(new List <HandlerReference> {
                handlerRef
            });
            var fakeAggregator = new FakeAggregator
            {
                Time = new TimeSpan(0, 0, 0, 1)
            };

            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(fakeAggregator);
            mockAggregatorPersistor.Setup(x => x.InsertData(It.IsAny <Message>(), It.IsAny <string>()));


            var aggregator = new AggregatorProcessor(mockAggregatorPersistor.Object, mockContainer.Object, typeof(FakeAggregator), mockLogger.Object);

            // Act
            aggregator.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(new FakeMessage1(Guid.NewGuid())));

            // Assert
            mockAggregatorPersistor.Verify(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName), Times.Never);
            Assert.False(fakeAggregator.Executed);
        }
Ejemplo n.º 4
0
        public void ShouldUseBatchSizeFromAggregator()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();
            var mockLogger = new Mock <ILogger>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes(typeof(Aggregator <FakeMessage1>))).Returns(new List <HandlerReference> {
                handlerRef
            });
            var aggregator = new FakeAggregator
            {
                Batch = 20
            };

            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(aggregator);
            mockAggregatorPersistor.Setup(x => x.InsertData(It.IsAny <Message>(), It.IsAny <string>()));

            mockAggregatorPersistor.Setup(x => x.Count(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(20);
            mockAggregatorPersistor.Setup(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(new List <object>());

            var aggregatorProcessor = new AggregatorProcessor(mockAggregatorPersistor.Object, mockContainer.Object, typeof(FakeAggregator), mockLogger.Object);

            // Act
            aggregatorProcessor.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(new FakeMessage1(Guid.NewGuid())));

            // Assert
            mockAggregatorPersistor.Verify(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName), Times.Once);
        }
Ejemplo n.º 5
0
        public void ShouldExecuteTheCorrectBaseMessageHandlers()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object);

            var message1HandlerReference = new HandlerReference
            {
                HandlerType = typeof(FakeBaseMessageHandler1),
                MessageType = typeof(FakeBaseMessage1)
            };

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

            var fakeHandler = new FakeBaseMessageHandler1();

            _mockContainer.Setup(x => x.GetInstance(typeof(FakeBaseMessageHandler1))).Returns(fakeHandler);

            // Act
            var message = new FakeDerivedMessage1(Guid.NewGuid())
            {
                Status = "Test"
            };

            messageProcessor.ProcessMessage <FakeDerivedMessage1>(JsonConvert.SerializeObject(message), null);

            // Assert
            Assert.Equal(message.CorrelationId, fakeHandler.Command.CorrelationId);
            Assert.Equal(message.Username, fakeHandler.Command.Username);
            _mockContainer.Verify(x => x.GetInstance(typeof(FakeBaseMessageHandler1)), Times.Once);
        }
        public void ShouldExecuteAsyncHandler()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object, _mockLogger.Object);

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

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

            var fakeHandler = new FakeAsyncHandler();

            _mockContainer.Setup(x => x.GetInstance(typeof(FakeAsyncHandler))).Returns(fakeHandler);

            // Act
            var message1 = new FakeMessage1(Guid.NewGuid());

            messageProcessor.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(message1),
                                                           new ConsumeContext {
                Headers = new Dictionary <string, object>()
            }).GetAwaiter().GetResult();;

            // Assert
            Assert.Equal(true, fakeHandler.Executed);
        }
        public void ShouldExecuteHandlerWithMessagesIfMessageCountIsEqualToOrGreaterThanBatchSize()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes(typeof(Aggregator <FakeMessage1>))).Returns(new List <HandlerReference> {
                handlerRef
            });
            var aggregator = new FakeAggregator();

            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(aggregator);
            mockAggregatorPersistor.Setup(x => x.InsertData(It.IsAny <object>(), It.IsAny <string>()));

            mockAggregatorPersistor.Setup(x => x.Count(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(10);
            mockAggregatorPersistor.Setup(x => x.GetData(typeof(FakeMessage1).AssemblyQualifiedName)).Returns(new List <object>()
            {
                new FakeMessage1(Guid.NewGuid())
            });

            var aggregatorProcessor = new AggregatorProcessor(mockAggregatorPersistor.Object, mockContainer.Object, typeof(FakeAggregator));

            // Act
            aggregatorProcessor.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(new FakeMessage1(Guid.NewGuid())));

            // Assert
            mockAggregatorPersistor.Verify(x => x.RemoveData(typeof(FakeMessage1).AssemblyQualifiedName, It.IsAny <Guid>()), Times.Once);
        }
Ejemplo n.º 8
0
        public static long AddEventHandler(T instance, string eventMemberName, Delegate handler)
        {
            instance.AssertNotNull(nameof(instance));
            eventMemberName.AssertNotBlank(nameof(eventMemberName));
            handler.AssertNotNull(nameof(handler));

            var key         = DateTime.UtcNow.Ticks;
            var eventMember = Events[eventMemberName];
            var reference   = new HandlerReference(new WeakReference <T>(instance), eventMember, handler);

            eventMember.Add(instance !, handler);
            EventHandlers.Add(key, reference);
            return(key);
        }
Ejemplo n.º 9
0
        public void ShouldExecuteTheCorrectHandlerWithMultipleRoutingKeyAttributes()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object);

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

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

            var fakeHandler = new FakeHandlerWithAttr2();

            _mockContainer.Setup(x => x.GetInstance(typeof(FakeHandlerWithAttr2))).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("Test2") }
                }
            });

            // Assert
            Assert.Equal(message1.CorrelationId, fakeHandler.Command.CorrelationId);
            Assert.Equal(message1.Username, fakeHandler.Command.Username);
            _mockContainer.Verify(x => x.GetInstance(typeof(FakeHandlerWithAttr2)), Times.Once);
        }
        public void ShouldExecuteTheCorrectHandlerWithCatchAllRoutingKeyAttribute()
        {
            // Arrange
            var messageProcessor = new MessageHandlerProcessor(_mockContainer.Object, _mockLogger.Object);

            var message1HandlerReference = new HandlerReference
            {
                HandlerType = typeof(FakeHandlerWithAttr1),
                MessageType = typeof(FakeMessage1),
                RoutingKeys = new List <string> {
                    "#"
                }                                      // matches any routing key
            };

            _mockContainer.Setup(x => x.GetHandlerTypes(typeof(IMessageHandler <FakeMessage1>), typeof(IAsyncMessageHandler <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("SomeRandomRoutingKey") }
                }
            }).GetAwaiter().GetResult();;

            // 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 messageProcessor = new MessageHandlerProcessor(_mockContainer.Object, _mockLogger.Object);

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

            _mockContainer.Setup(x => x.GetHandlerTypes(typeof(IMessageHandler <FakeMessage1>), typeof(IAsyncMessageHandler <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).GetAwaiter().GetResult();;

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

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

            // 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 ShouldStartAggregatorTimerIfAggregatorTimeoutIsSet()
        {
            // Arrange
            var mockContainer           = new Mock <IBusContainer>();
            var mockAggregatorPersistor = new Mock <IAggregatorPersistor>();
            var mockAggregatorProcessor = new Mock <IAggregatorProcessor>();
            var mockConfiguration       = new Mock <IConfiguration>();
            var mockConsumer            = new Mock <IConsumer>();

            var handlerRef = new HandlerReference()
            {
                HandlerType = typeof(FakeAggregator),
                MessageType = typeof(FakeMessage1)
            };

            mockContainer.Setup(x => x.GetHandlerTypes()).Returns(new List <HandlerReference> {
                handlerRef
            });
            var timeout = new TimeSpan(0, 0, 0, 1);

            mockContainer.Setup(x => x.GetInstance(typeof(FakeAggregator))).Returns(new FakeAggregator
            {
                Time = timeout
            });
            mockConfiguration.Setup(x => x.GetAggregatorProcessor(It.IsAny <IAggregatorPersistor>(), mockContainer.Object, typeof(FakeAggregator))).Returns(mockAggregatorProcessor.Object);
            mockConfiguration.Setup(x => x.GetAggregatorPersistor()).Returns(mockAggregatorPersistor.Object);
            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.AutoStartConsuming).Returns(true);
            mockConfiguration.Setup(x => x.TransportSettings).Returns(new TransportSettings());
            mockConfiguration.Setup(x => x.GetConsumer()).Returns(mockConsumer.Object);

            // Act
            new Bus(mockConfiguration.Object);

            // Assert
            mockAggregatorProcessor.Verify(x => x.StartTimer <FakeMessage1>(timeout), Times.Once);
        }
Ejemplo n.º 13
0
 /// <inheritdoc/>
 public void Dispose()
 {
     HandlerReference.Dispose();
     GC.SuppressFinalize(this);
 }
Ejemplo n.º 14
0
        private PathItem HandlerPathItem(HandlerReference handlerRef)
        {
            var messageType = Type.GetType(handlerRef.MessageType.AssemblyQualifiedName);
            var routingKeys = handlerRef.RoutingKeys;

            if (null == messageType)
            {
                var err = string.Format("Unable to load the type {0}", handlerRef.MessageType.AssemblyQualifiedName);
                Logger.Error(err);
                throw new Exception(err);
            }

            Logger.DebugFormat("messageType.Name: {0}.", messageType.Name);

            var msgProperties = new Dictionary <string, Schema>();
            var props         = messageType.GetProperties();

            foreach (var prop in props)
            {
                string typeName = prop.PropertyType.Name.ToLower();
                if (typeName == "guid")
                {
                    typeName = "string";
                }

                msgProperties.Add(prop.Name, new Schema {
                    Type = typeName
                });
            }

            var x = new PathItem();

            x.Post = new Operation
            {
                Tags        = new[] { handlerRef.HandlerType.Name },
                OperationId = handlerRef.HandlerType.Name,
                Consumes    = new[] { "application/json" },
                Produces    = new[] { "application/json", "text/json", "application/xml", "text/xml" },
                Parameters  = new List <IParameter>
                {
                    new BodyParameter
                    {
                        Name        = "message",
                        @In         = "body",
                        Required    = true,
                        Description = messageType.Name,
                        Schema      = new Schema
                        {
                            Type       = "object",
                            Properties = msgProperties
                        }
                    },
                    new NonBodyParameter
                    {
                        Name     = "msg-full-type-name",
                        @In      = "header",
                        Required = true,
                        Default  = messageType.AssemblyQualifiedName
                    }
                }
            };

            if (null != routingKeys && routingKeys.Any())
            {
                var rkStr = String.Join(",", routingKeys.ToArray());
                x.Post.Parameters.Add(new NonBodyParameter
                {
                    Name        = "routing-key",
                    @In         = "header",
                    Required    = true,
                    Default     = routingKeys.First(),
                    Description = $"warning: message will be published to every \"{messageType.Name}\" handler decorated with the routing key supplied. (possible value(s): {rkStr})"
                });
            }

            if (Generator.Bus.Configuration.BeforeConsumingFilters.Any(f => f.Name == "TokenDecryptFilter"))
            {
                x.Post.Parameters.Add(new NonBodyParameter
                {
                    Name     = "token",
                    @In      = "header",
                    Required = true,
                    Default  = string.Empty
                });
            }

            x.Post.Responses = new Dictionary <string, Response>();
            x.Post.Responses.Add("200", new Response {
                Description = "OK", Schema = new Schema {
                    Type = "string"
                }
            });
            return(x);
        }