public void TestCreateProducer()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                testPeer.ExpectBegin();

                testPeer.ExpectSenderAttach();

                var producer = context.CreateProducer();

                testPeer.ExpectDetach(true, true, true);
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                producer.Close();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Example #2
0
        public void TestCloseSession()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                testPeer.ExpectBegin();
                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                Assert.NotNull(session, "Session should not be null");
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                session.Close();

                // Should send nothing and throw no error.
                session.Close();

                connection.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Example #3
0
        public void TestCloseSender()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = base.EstablishNMSContext(testPeer);
                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                IQueue queue    = context.GetQueue("myQueue");
                var    producer = context.CreateProducer();

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                producer.Close();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestCreateConsumer()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                var consumer = context.CreateConsumer(context.GetQueue("myQueue"));

                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestRecoveredMessageShouldNotBeMutated()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer, acknowledgementMode: AcknowledgementMode.ClientAcknowledge);
                context.Start();

                testPeer.ExpectBegin();
                IQueue destination     = context.GetQueue("myQueue");
                string originalPayload = "testMessage";

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: new Amqp.Message {
                    BodySection = new AmqpValue()
                    {
                        Value = originalPayload
                    }
                }, count: 1);

                var            consumer = context.CreateConsumer(destination);
                NmsTextMessage message  = consumer.Receive() as NmsTextMessage;
                Assert.NotNull(message);
                message.IsReadOnlyBody = false;
                message.Text           = message.Text + "Received";
                context.Recover();

                ITextMessage recoveredMessage = consumer.Receive() as ITextMessage;
                Assert.IsNotNull(recoveredMessage);
                Assert.AreNotEqual(message.Text, recoveredMessage.Text);
                Assert.AreEqual(originalPayload, recoveredMessage.Text);
                Assert.AreNotSame(message, recoveredMessage);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }
        public void TestSessionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                Assert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");


                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }
        public async Task TestCreateConsumer()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                await context.StartAsync();

                testPeer.ExpectBegin();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                var consumer = await context.CreateConsumerAsync(await context.GetQueueAsync("myQueue"));

                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestCreateProducerInOnMessage()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                IQueue outbound    = context.GetQueue("ForwardDest");

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);

                testPeer.ExpectSenderAttach();
                testPeer.ExpectTransfer(messageMatcher: Assert.NotNull);
                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                var consumer = context.CreateConsumer(destination);

                consumer.Listener += message =>
                {
                    var producer = context.CreateProducer();
                    producer.Send(outbound, message);
                    producer.Close();
                };

                testPeer.WaitForAllMatchersToComplete(10_000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }
        public async Task TestSendingMessageNonPersistentSetsBatchableFalse()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                await context.StartAsync();

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                IQueue destination = await context.GetQueueAsync("myQueue");

                var producer = await context.CreateProducerAsync();

                testPeer.ExpectTransfer(messageMatcher: Assert.IsNotNull,
                                        stateMatcher: Assert.IsNull,
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true,
                                        batchable: false);

                IMessage message = await context.CreateMessageAsync();

                producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                producer.Priority     = MsgPriority.Normal;
                producer.TimeToLive   = NMSConstants.defaultTimeToLive;
                await producer.SendAsync(destination, message);

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestReceiveBodyNoWait <T>(T inputValue)
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);

                ManualResetEvent beforeFlow = new ManualResetEvent(false);
                testPeer.ExpectBegin();
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(CreateMessageWithValueContent(inputValue), 1, false, false, false, false,
                                                           (credit) => { beforeFlow.WaitOne(); }, 1);
                testPeer.ExpectDisposition(true, _ => { });

                IQueue destination = context.GetQueue("myQueue");
                var    consumer    = context.CreateConsumer(destination);

                T initialBody = consumer.ReceiveBodyNoWait <T>();
                // Assert initially its null
                Assert.AreEqual(default(T), initialBody);

                // Release and allow link to flow
                beforeFlow.Set();
                // Give short time to arrive
                Thread.Sleep(100);

                T body = consumer.ReceiveBodyNoWait <T>();
                Assert.AreEqual(inputValue, body);
                Assert.AreNotSame(inputValue, body);


                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }
Example #11
0
        public void TestSendingMessageSetsNMSMessageId()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                IQueue destination = context.GetQueue("myQueue");
                var    producer    = context.CreateProducer();

                string text            = "myMessage";
                string actualMessageId = null;
                testPeer.ExpectTransfer(m =>
                {
                    Assert.IsTrue(m.Header.Durable);
                    Assert.IsNotEmpty(m.Properties.MessageId);
                    actualMessageId = m.Properties.MessageId;
                });
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                ITextMessage message = context.CreateTextMessage(text);
                Assert.IsNull(message.NMSMessageId, "NMSMessageId should not yet be set");

                producer.Send(destination, message);

                Assert.IsNotNull(message.NMSMessageId);
                Assert.IsNotEmpty(message.NMSMessageId, "NMSMessageId should be set");
                Assert.IsTrue(message.NMSMessageId.StartsWith("ID:"), "MMS 'ID:' prefix not found");

                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
                // Get the value that was actually transmitted/received, verify it is a string, compare to what we have locally
                Assert.AreEqual(message.NMSMessageId, actualMessageId, "Expected NMSMessageId value to be present in AMQP message");
            }
        }
Example #12
0
        public void TestSendingMessageSetsNMSTimestamp()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                IQueue destination = context.GetQueue("myQueue");
                var    producer    = context.CreateProducer();

                // Create matcher to expect the absolute-expiry-time field of the properties section to
                // be set to a value greater than 'now'+ttl, within a delta.

                DateTime creationLower = DateTime.UtcNow;
                DateTime creationUpper = creationLower + TimeSpan.FromMilliseconds(3000);

                var text = "myMessage";
                testPeer.ExpectTransfer(m =>
                {
                    Assert.IsTrue(m.Header.Durable);
                    Assert.That(m.Properties.CreationTime.Ticks, Is.GreaterThanOrEqualTo(creationLower.Ticks).Within(TICKS_PER_MILLISECOND));
                    Assert.That(m.Properties.CreationTime.Ticks, Is.LessThanOrEqualTo(creationUpper.Ticks).Within(TICKS_PER_MILLISECOND));
                    Assert.AreEqual(text, (m.BodySection as AmqpValue).Value);
                });

                ITextMessage message = context.CreateTextMessage(text);
                producer.Send(destination, message);

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestCreateTemporaryTopic()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);

                testPeer.ExpectBegin();

                string dynamicAddress = "myTempTopicAddress";
                testPeer.ExpectTempTopicCreationAttach(dynamicAddress);

                ITemporaryTopic temporaryTopic = context.CreateTemporaryTopic();
                Assert.NotNull(temporaryTopic, "TemporaryTopic object was null");
                Assert.NotNull(temporaryTopic.TopicName, "TemporaryTopic name was null");
                Assert.AreEqual(dynamicAddress, temporaryTopic.TopicName, "TemporaryTopic name not as expected");

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public async Task TestCreateProducer()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                testPeer.ExpectBegin();

                testPeer.ExpectSenderAttach();

                var producer = await context.CreateProducerAsync();

                testPeer.ExpectDetach(true, true, true);
                testPeer.ExpectEnd();
                testPeer.ExpectClose();

                await producer.CloseAsync();

                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Example #15
0
        public async Task TestReceiveMessageWithReceiveZeroTimeout()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                await context.StartAsync();

                testPeer.ExpectBegin();

                IQueue queue = await context.GetQueueAsync("myQueue");

                testPeer.ExpectReceiverAttach();

                testPeer.ExpectLinkFlowRespondWithTransfer(message: new Amqp.Message()
                {
                    BodySection = new AmqpValue()
                    {
                        Value = null
                    }
                }, count: 1);
                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                var consumer = await context.CreateConsumerAsync(queue);

                IMessage message = await consumer.ReceiveAsync();

                Assert.NotNull(message, "A message should have been received");

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(10000);
            }
        }
Example #16
0
        public async Task TestCloseConsumer()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();

                IQueue queue = await context.GetQueueAsync("myQueue");

                var consumer = await context.CreateConsumerAsync(queue);

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                await consumer.CloseAsync();

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public async Task TestCreateTemporaryQueue()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);

                testPeer.ExpectBegin();

                string dynamicAddress = "myTempQueueAddress";
                testPeer.ExpectTempQueueCreationAttach(dynamicAddress);

                ITemporaryQueue temporaryQueue = await context.CreateTemporaryQueueAsync();

                Assert.NotNull(temporaryQueue, "TemporaryQueue object was null");
                Assert.NotNull(temporaryQueue.QueueName, "TemporaryQueue queue name was null");
                Assert.AreEqual(dynamicAddress, temporaryQueue.QueueName, "TemporaryQueue name not as expected");

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Example #18
0
        public void TestTempDestinationRecreatedAfterConnectionFailsOver()
        {
            using (TestAmqpPeer originalPeer = new TestAmqpPeer())
                using (TestAmqpPeer finalPeer = new TestAmqpPeer())
                {
                    ManualResetEvent originalConnected = new ManualResetEvent(false);
                    ManualResetEvent finalConnected    = new ManualResetEvent(false);

                    // Create a peer to connect to, then one to reconnect to
                    var originalUri = CreatePeerUri(originalPeer);
                    var finalUri    = CreatePeerUri(finalPeer);

                    originalPeer.ExpectSaslAnonymous();
                    originalPeer.ExpectOpen();
                    originalPeer.ExpectBegin();
                    originalPeer.ExpectBegin();
                    string dynamicAddress1 = "myTempTopicAddress";
                    originalPeer.ExpectTempTopicCreationAttach(dynamicAddress1);
                    originalPeer.DropAfterLastMatcher();

                    NmsConnection connection = EstablishAnonymousConnection(originalPeer, finalPeer);

                    Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>();

                    connectionListener
                    .Setup(listener => listener.OnConnectionEstablished(It.Is <Uri>(uri => originalUri == uri.ToString())))
                    .Callback(() => { originalConnected.Set(); });

                    connectionListener
                    .Setup(listener => listener.OnConnectionRestored(It.Is <Uri>(uri => finalUri == uri.ToString())))
                    .Callback(() => { finalConnected.Set(); });

                    connection.AddConnectionListener(connectionListener.Object);

                    connection.Start();

                    Assert.True(originalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to original peer");

                    // Post Failover Expectations of FinalPeer
                    finalPeer.ExpectSaslAnonymous();
                    finalPeer.ExpectOpen();
                    finalPeer.ExpectBegin();
                    String dynamicAddress2 = "myTempTopicAddress2";
                    finalPeer.ExpectTempTopicCreationAttach(dynamicAddress2);

                    // Session is recreated after previous temporary destinations are recreated on failover.
                    finalPeer.ExpectBegin();

                    ISession        session        = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                    ITemporaryTopic temporaryTopic = session.CreateTemporaryTopic();

                    Assert.True(finalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to final peer");

                    // Delete the temporary Topic and close the session.
                    finalPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                    finalPeer.ExpectEnd();

                    temporaryTopic.Delete();

                    session.Close();

                    // Shut it down
                    finalPeer.ExpectClose();
                    connection.Close();

                    originalPeer.WaitForAllMatchersToComplete(2000);
                    finalPeer.WaitForAllMatchersToComplete(1000);
                }
        }
        private async Task DoSendingMessageNonPersistentTestImpl(bool setPriority)
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                //Add capability to indicate support for ANONYMOUS-RELAY
                Symbol[] serverCapabilities = { SymbolUtil.OPEN_CAPABILITY_ANONYMOUS_RELAY };
                var      context            = await EstablishNMSContextAsync(testPeer, serverCapabilities : serverCapabilities);

                testPeer.ExpectBegin();

                string          queueName     = "myQueue";
                Action <object> targetMatcher = t =>
                {
                    var target = t as Target;
                    Assert.IsNotNull(target);
                };


                testPeer.ExpectSenderAttach(targetMatcher: targetMatcher, sourceMatcher: Assert.NotNull, senderSettled: false);

                IQueue queue = await context.GetQueueAsync(queueName);

                INMSProducer producer = await context.CreateProducerAsync();

                byte   priority = 5;
                String text     = "myMessage";
                testPeer.ExpectTransfer(messageMatcher: message =>
                {
                    if (setPriority)
                    {
                        Assert.IsFalse(message.Header.Durable);
                        Assert.AreEqual(priority, message.Header.Priority);
                    }

                    Assert.AreEqual(text, (message.BodySection as AmqpValue).Value);
                }, stateMatcher: Assert.IsNull,
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true);

                ITextMessage textMessage = await context.CreateTextMessageAsync(text);

                producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                if (setPriority)
                {
                    producer.Priority = (MsgPriority)priority;
                }

                await producer.SendAsync(queue, textMessage);

                Assert.AreEqual(MsgDeliveryMode.NonPersistent, textMessage.NMSDeliveryMode, "Should have NonPersistent delivery mode set");

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestRecoverOrderingWithAsyncConsumer()
        {
            ManualResetEvent latch      = new ManualResetEvent(false);
            Exception        asyncError = null;

            int    recoverCount      = 5;
            int    messageCount      = 8;
            int    testPayloadLength = 255;
            string payload           = Encoding.UTF8.GetString(new byte[testPayloadLength]);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer, acknowledgementMode: AcknowledgementMode.ClientAcknowledge);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(
                    message: new Amqp.Message()
                {
                    BodySection = new AmqpValue()
                    {
                        Value = payload
                    }
                },
                    count: messageCount,
                    drain: false,
                    nextIncomingId: 1,
                    addMessageNumberProperty: true,
                    sendDrainFlowResponse: false,
                    sendSettled: false,
                    creditMatcher: credit => Assert.Greater(credit, messageCount)
                    );

                var consumer = context.CreateConsumer(destination);

                bool complete      = false;
                int  messageSeen   = 0;
                int  expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    try
                    {
                        int actualIndex = message.Properties.GetInt(TestAmqpPeer.MESSAGE_NUMBER);
                        Assert.AreEqual(expectedIndex, actualIndex, "Received Message Out Of Order");

                        // don't ack the message until we receive it X times
                        if (messageSeen < recoverCount)
                        {
                            context.Recover();
                            messageSeen++;
                        }
                        else
                        {
                            messageSeen = 0;
                            expectedIndex++;

                            // Have the peer expect the accept the disposition (1-based, hence pre-incremented).
                            testPeer.ExpectDisposition(settled: true,
                                                       stateMatcher: state => Assert.AreEqual(state.Descriptor.Code, MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code
                                                                                              ));

                            message.Acknowledge();

                            if (expectedIndex == messageCount)
                            {
                                complete = true;
                                latch.Set();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        complete   = true;
                        asyncError = e;
                        latch.Set();
                    }
                };

                Assert.True(latch.WaitOne(TimeSpan.FromSeconds(15)), "Messages not received within given timeout.");
                Assert.IsNull(asyncError, "Unexpected exception");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }