public void Parse_EventIdFieldIsNotGuid_ErrorShouldBeReturned()
        {
            //prepare
            var bookingCreatedEvent = new IntergrationEventWithNonGuidEventId <BookingCreated>()
            {
                EventId           = 123,
                CorrelationId     = Guid.NewGuid(),
                EventCreationDate = DateTime.UtcNow,
                EventType         = "bookingCreated",
                Version           = "0.1",
                Content           = new BookingCreated()
                {
                    BookingName = "bookingName"
                }
            };

            //act
            IntergrationEventParsingResult result =
                DefaultIntergrationEventParser.Parse(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bookingCreatedEvent)));

            //check
            result.Success.Should().BeFalse();
            result.IntegrationEvent.Should().BeNull();
            result.Errors.First().Should().Be("EventId is not GUID");
        }
        public void Parse_CorrelationIdFieldIsMissedEventCreationDateIsNotDateTime_ErrorShouldBeReturned()
        {
            //prepare
            var bookingCreatedEvent =
                new IntergrationEventWithoutCorrelationIdAndWrongEventCreationDate <BookingCreated>()
            {
                EventId           = Guid.NewGuid(),
                EventCreationDate = 13,
                EventType         = "bookingcreated",
                Version           = "0.1",
                Content           = new BookingCreated()
                {
                    BookingName = "bookingName"
                }
            };

            //act
            IntergrationEventParsingResult result =
                DefaultIntergrationEventParser.Parse(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bookingCreatedEvent)));

            //check
            result.Success.Should().BeFalse();
            result.IntegrationEvent.Should().BeNull();
            result.Errors.Count.Should().Be(2);
            result.Errors[0].Should().Be("CorrelationId token is missed");
            result.Errors[1].Should().Be("EventCreationDate is not DateTime");
        }
        public void Parse_CorrelationIdFieldIsEmpty_SuccessShouldBeReturned()
        {
            //prepare
            var bookingCreatedEvent = new IntegrationEvent <BookingCreated>()
            {
                EventId           = Guid.NewGuid(),
                CorrelationId     = null,
                EventCreationDate = DateTime.UtcNow,
                EventType         = "bookingCreated",
                Version           = "0.1",
                Content           = new BookingCreated()
                {
                    BookingName = "bookingName"
                }
            };

            //act
            IntergrationEventParsingResult result =
                DefaultIntergrationEventParser.Parse(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bookingCreatedEvent)));

            //check
            result.Success.Should().BeTrue();
            result.IntegrationEvent.ShouldBeEquivalentTo(bookingCreatedEvent);
            result.Errors.Count.Should().Be(0);
        }
Пример #4
0
        public void Subscribe(IDictionary <string, ISubscription> subscriptions)
        {
            lock (_threadguard)
            {
                if (_alreadyDisposed)
                {
                    throw new
                          ObjectDisposedException("EasyNetQSubscriber",
                                                  "Called Subscribe Method on Disposed object");
                }

                if (_subscribed == false)
                {
                    _subscriptions      = new ConcurrentDictionary <string, ISubscription>(subscriptions);
                    _consumerDisposable = _bus.Consume(_queue, async(body, properties, info) =>
                    {
                        MessageExecutionContext messageExecutionContext = new MessageExecutionContext(body, properties, info);
                        try
                        {
                            messageExecutionContext.IntergrationEventParsingResult = DefaultIntergrationEventParser.Parse(body);
                            if (messageExecutionContext.IntergrationEventParsingResult.Success)
                            {
                                using (LogContext.PushProperty("CorrelationId", messageExecutionContext.IntergrationEventParsingResult.IntegrationEvent.CorrelationId))
                                {
                                    messageExecutionContext.Subscription = _subscriptionSelector.Select(_subscriptions,
                                                                                                        messageExecutionContext.IntergrationEventParsingResult.IntegrationEvent.EventType);

                                    if (messageExecutionContext.Subscription != null)
                                    {
                                        messageExecutionContext.SerializedMessage = Encoding.UTF8.GetString(body);
                                        _logger.Debug("Subscriber received message: {@body}", messageExecutionContext.SerializedMessage);
                                        await messageExecutionContext.Subscription.InvokeAsync(messageExecutionContext.SerializedMessage);
                                        await _successHandlingStrategy.HandleSuccessAsync(
                                            messageExecutionContext.IntergrationEventParsingResult.IntegrationEvent);
                                    }
                                    else
                                    {
                                        throw new DiscardEventException(
                                            $"The consumer for {messageExecutionContext.IntergrationEventParsingResult.IntegrationEvent.EventType} event type is not matched");
                                    }
                                }
                            }
                            else
                            {
                                throw new MalformedEventException(messageExecutionContext.IntergrationEventParsingResult.Errors);
                            }
                        }
                        catch (Exception e)
                        {
                            messageExecutionContext.Exception = e;
                            await _errorHandlingStrategy.HandleErrorAsync(messageExecutionContext);
                        }
                    }, configuration => configuration.WithPrefetchCount(_prefetchcount));
                    _subscribed = true;
                }
                else
                {
                    foreach (var subscription in subscriptions)
                    {
                        _subscriptions.AddOrUpdate(
                            subscription.Key, subscription.Value,
                            (key, oldValue) => subscription.Value);
                    }
                }
            }
        }
Пример #5
0
        public async void Subscribe_CorrectlyFormedEvent_ProcessingWithoutErrors_NoExceptionsShouldBeThrown()
        {
            //prepare
            IntegrationEvent <BookingCreated> integrationEvent =
                new IntegrationEvent <BookingCreated>()
            {
                CorrelationId     = Guid.NewGuid(),
                EventCreationDate = DateTime.UtcNow,
                EventId           = Guid.NewGuid(),
                EventType         = _bookingEventType,
                Version           = _version,
                Content           = new BookingCreated
                {
                    BookingName = _bookingName
                }
            };

            var messagebytes = SerializeEvent(integrationEvent);

            EventEmulator eventEmulator = null;

            _mockBus.Setup(x => x.Consume(_mockQueue.Object,
                                          It.IsAny <Func <byte[], MessageProperties, MessageReceivedInfo, Task> >(), It.IsAny <Action <IConsumerConfiguration> >()))
            .Returns((IQueue queue, Func <byte[],
                                          MessageProperties, MessageReceivedInfo, Task> func, Action <IConsumerConfiguration> configure) =>
            {
                eventEmulator = new EventEmulator(func);
                return(_consumerDisposable.Object);
            });

            var mockSubscription = new Mock <ISubscription>();

            mockSubscription.Setup(x => x.InvokeAsync(Encoding.UTF8.GetString(messagebytes))).Returns(Task.FromResult(true));


            Dictionary <string, ISubscription> subscriptions = new Dictionary <string, ISubscription> {
                { "bookingcreated", mockSubscription.Object }
            };

            _subsciptionSelector.Setup(x => x.Select(subscriptions, "bookingcreated"))
            .Returns((IDictionary <string, ISubscription> subs, string eventType) => mockSubscription.Object);

            _easyNetQSubscriber.Subscribe(subscriptions);

            //Act
            MessageProperties messageProperties = new MessageProperties();
            await eventEmulator.Execute(messagebytes, messageProperties, null);

            //check
            eventEmulator.RaisedException.Should().BeNull();
            mockSubscription.Verify(x => x.InvokeAsync(Encoding.UTF8.GetString(messagebytes)), Times.Once);
            mockSubscription.Verify(x => x.NotifyAboutDeadLetterAsync(It.IsAny <string>(), It.IsAny <Exception>()), Times.Never);

            var parsedMessage = DefaultIntergrationEventParser.Parse(messagebytes);

            var expectedEvent = parsedMessage.IntegrationEvent
                                .AsSource()
                                .OfLikeness <IntegrationEvent>()
                                .CreateProxy();

            _successHandlingStrategy.Verify(x => x.HandleSuccessAsync(expectedEvent));
        }
Пример #6
0
        public async void Subscribe_DiscardEventException_WhenProcessed_ExceptionShouldBeThrown()
        {
            //prepare
            var content = new BookingCreated()
            {
                BookingName = _bookingName
            };
            IntegrationEvent <BookingCreated> integrationEvent =
                new IntegrationEvent <BookingCreated>
            {
                CorrelationId     = Guid.NewGuid(),
                EventCreationDate = DateTime.UtcNow,
                EventId           = Guid.NewGuid(),
                EventType         = _bookingEventType,
                Version           = _version,
                Content           = content
            };

            var messagebytes = SerializeEvent(integrationEvent);

            EventEmulator eventEmulator = null;

            _mockBus.Setup(x => x.Consume(_mockQueue.Object,
                                          It.IsAny <Func <byte[], MessageProperties, MessageReceivedInfo, Task> >(),
                                          It.IsAny <Action <IConsumerConfiguration> >()))
            .Returns((IQueue queue, Func <byte[],
                                          MessageProperties, MessageReceivedInfo, Task> func,
                      Action <IConsumerConfiguration> configure) =>
            {
                eventEmulator = new EventEmulator(func);
                return(_consumerDisposable.Object);
            });


            DiscardEventException discardEventException = new DiscardEventException();
            var mockSubscription = new Mock <ISubscription>();

            mockSubscription.Setup(x => x.InvokeAsync(Encoding.UTF8.GetString(messagebytes)))
            .Returns <string>(
                (serilizedmessage) =>
            {
                return(Task.FromException <DiscardEventException>(discardEventException));
            });


            Dictionary <string, ISubscription> subscriptions = new Dictionary <string, ISubscription> {
                { "bookingcreated", mockSubscription.Object }
            };

            _subsciptionSelector.Setup(x => x.Select(subscriptions, "bookingcreated"))
            .Returns((IDictionary <string, ISubscription> subs, string eventType) => mockSubscription.Object);

            MessageProperties       messageProperties             = new MessageProperties();
            MessageExecutionContext actualMessageExecutionContext = null;

            _errorHandlingStrategy.Setup(x => x.HandleErrorAsync(It.IsAny <MessageExecutionContext>()))
            .Returns <MessageExecutionContext>(
                (messageExecutionContext) =>
            {
                actualMessageExecutionContext = messageExecutionContext;
                return(Task.FromException <DiscardEventException>(messageExecutionContext.Exception));
            });

            _easyNetQSubscriber.Subscribe(subscriptions);

            //Act

            await eventEmulator.Execute(messagebytes, messageProperties, null);

            //check
            eventEmulator.RaisedException.GetType().Should().Be(typeof(DiscardEventException));

            _successHandlingStrategy.Verify(x => x.HandleSuccessAsync(It.IsAny <IntegrationEvent>()), Times.Never);
            _errorHandlingStrategy.Verify(x => x.HandleErrorAsync(It.IsAny <MessageExecutionContext>()), Times.Once);
            actualMessageExecutionContext.BodyBytes.ShouldBeEquivalentTo(messagebytes);
            actualMessageExecutionContext.Exception.Should().Be(eventEmulator.RaisedException);
            actualMessageExecutionContext.MessageProperties.Should().Be(messageProperties);
            actualMessageExecutionContext.IntergrationEventParsingResult.ShouldBeEquivalentTo(DefaultIntergrationEventParser.Parse(messagebytes));
            actualMessageExecutionContext.SerializedMessage.Should().Be(Encoding.UTF8.GetString(messagebytes));
            actualMessageExecutionContext.DeadLetterIntegrationEvent.Should().BeNull();
            actualMessageExecutionContext.Subscription.Should().Be(mockSubscription.Object);
        }
Пример #7
0
        public async void Subscribe_MalformedEvent_ExceptionShouldBeThrown()
        {
            //prepare
            var messagebytes = Encoding.UTF8.GetBytes(@"{
                                                            ""Version"": ""0.1""
                                                        }");

            EventEmulator eventEmulator = null;

            _mockBus.Setup(x => x.Consume(_mockQueue.Object,
                                          It.IsAny <Func <byte[], MessageProperties, MessageReceivedInfo, Task> >(),
                                          It.IsAny <Action <IConsumerConfiguration> >()))
            .Returns((IQueue queue, Func <byte[],
                                          MessageProperties, MessageReceivedInfo, Task> func,
                      Action <IConsumerConfiguration> configure) =>
            {
                eventEmulator = new EventEmulator(func);
                return(_consumerDisposable.Object);
            });


            Dictionary <string, ISubscription> subscriptions = new Dictionary <string, ISubscription>();

            MessageProperties messageProperties = new MessageProperties();

            MessageExecutionContext actualMessageExecutionContext = null;

            _errorHandlingStrategy.Setup(x => x.HandleErrorAsync(
                                             It.IsAny <MessageExecutionContext>()))
            .Returns <MessageExecutionContext>(
                (executionContext) =>
            {
                actualMessageExecutionContext = executionContext;
                return(Task.FromException <MalformedEventException>(executionContext.Exception));
            });

            _easyNetQSubscriber.Subscribe(subscriptions);

            //Act
            await eventEmulator.Execute(messagebytes, messageProperties, null);

            //check
            ((MalformedEventException)eventEmulator.RaisedException).
            Errors.First().ShouldBeEquivalentTo("EventId token is missed");

            _successHandlingStrategy.Verify(x => x.HandleSuccessAsync(It.IsAny <IntegrationEvent>()), Times.Never);
            _errorHandlingStrategy.Verify(x => x.HandleErrorAsync(It.IsAny <MessageExecutionContext>()), Times.Once);
            actualMessageExecutionContext.BodyBytes.ShouldBeEquivalentTo(messagebytes);
            actualMessageExecutionContext.Exception.Should().Be(eventEmulator.RaisedException);
            actualMessageExecutionContext.MessageProperties.Should().Be(messageProperties);
            actualMessageExecutionContext.IntergrationEventParsingResult.ShouldBeEquivalentTo(DefaultIntergrationEventParser.Parse(messagebytes));
            actualMessageExecutionContext.SerializedMessage.Should().BeNull();
            actualMessageExecutionContext.DeadLetterIntegrationEvent.Should().BeNull();
            actualMessageExecutionContext.Subscription.Should().BeNull();
        }
Пример #8
0
        public async void Subscribe_CorrectlyFormedEvent_NoConsumerForEventTypeMatched()
        {
            //prepare
            IntegrationEvent <BookingCreated> integrationEvent =
                new IntegrationEvent <BookingCreated>()
            {
                CorrelationId     = Guid.NewGuid(),
                EventCreationDate = DateTime.UtcNow,
                EventId           = Guid.NewGuid(),
                EventType         = _bookingEventType,
                Version           = _version,
                Content           = new BookingCreated
                {
                    BookingName = _bookingName
                }
            };

            var messagebytes = SerializeEvent(integrationEvent);

            EventEmulator eventEmulator = null;

            _mockBus.Setup(x => x.Consume(_mockQueue.Object,
                                          It.IsAny <Func <byte[], MessageProperties, MessageReceivedInfo, Task> >(),
                                          It.IsAny <Action <IConsumerConfiguration> >()))
            .Returns((IQueue queue, Func <byte[],
                                          MessageProperties, MessageReceivedInfo, Task> func, Action <IConsumerConfiguration> configure) =>
            {
                eventEmulator = new EventEmulator(func);
                return(_consumerDisposable.Object);
            });



            Dictionary <string, ISubscription> subscriptions = new Dictionary <string, ISubscription>();

            _subsciptionSelector.Setup(x => x.Select(subscriptions, _bookingEventType))
            .Returns((IDictionary <string, ISubscription> subs, string eventType) => null);

            MessageProperties messageProperties = new MessageProperties();

            MessageExecutionContext actualMessageExecutionContext = null;

            _errorHandlingStrategy.Setup(x => x.HandleErrorAsync(It.IsAny <MessageExecutionContext>()))
            .Returns <MessageExecutionContext>(
                (messageExecutionContext) =>
            {
                actualMessageExecutionContext = messageExecutionContext;
                return(Task.FromException <DiscardEventException>(messageExecutionContext.Exception));
            });



            _easyNetQSubscriber.Subscribe(subscriptions);


            //Act

            await eventEmulator.Execute(messagebytes, messageProperties, null);

            //check
            _successHandlingStrategy.Verify(x => x.HandleSuccessAsync(It.IsAny <IntegrationEvent>()), Times.Never);
            _errorHandlingStrategy.Verify(x => x.HandleErrorAsync(It.IsAny <MessageExecutionContext>()), Times.Once);
            actualMessageExecutionContext.BodyBytes.ShouldBeEquivalentTo(messagebytes);
            actualMessageExecutionContext.Exception.Should().Be(eventEmulator.RaisedException);
            actualMessageExecutionContext.MessageProperties.Should().Be(messageProperties);
            actualMessageExecutionContext.IntergrationEventParsingResult.ShouldBeEquivalentTo(DefaultIntergrationEventParser.Parse(messagebytes));
            actualMessageExecutionContext.SerializedMessage.Should().BeNull();
            actualMessageExecutionContext.DeadLetterIntegrationEvent.Should().BeNull();
            actualMessageExecutionContext.Subscription.Should().BeNull();

            eventEmulator.RaisedException.Should().BeOfType <DiscardEventException>().Which.Message
            .ShouldBeEquivalentTo("The consumer for bookingcreated event type is not matched");
        }