public void TestTransactionalLowLevel()
        {
            var template = new RabbitTemplate();
            var connectionFactory = new CachingConnectionFactory();
            connectionFactory.Port = BrokerTestUtils.GetPort();
            template.ConnectionFactory = connectionFactory;

            var blockingQueueConsumer = new BlockingQueueConsumer(connectionFactory, new DefaultMessagePropertiesConverter(), new ActiveObjectCounter<BlockingQueueConsumer>(), AcknowledgeModeUtils.AcknowledgeMode.Auto, true, 1, queue.Name);
            blockingQueueConsumer.Start();
            connectionFactory.Dispose();

            // TODO: make this into a proper assertion. An exception can be thrown here by the Rabbit client and printed to
            // stderr without being rethrown (so hard to make a test fail).
            blockingQueueConsumer.Stop();
            Assert.IsNull(template.ReceiveAndConvert(queue.Name));
        }
        public void TestWithListener()
        {
            var mocker = new AutoMoqer();

            var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>();
            var mockConnection = mocker.GetMock<RabbitMQ.Client.IConnection>();

            mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object);

            var called = new AtomicInteger(0);
            var connectionFactory = new CachingConnectionFactory(mockConnectionFactory.Object);

            var mockConnectionListener = new Mock<IConnectionListener>();
            mockConnectionListener.Setup(m => m.OnCreate(It.IsAny<IConnection>())).Callback((IConnection conn) => called.IncrementValueAndReturn());
            mockConnectionListener.Setup(m => m.OnClose(It.IsAny<IConnection>())).Callback((IConnection conn) => called.DecrementValueAndReturn());

            connectionFactory.ConnectionListeners = new List<IConnectionListener>() { mockConnectionListener.Object };

            var con = connectionFactory.CreateConnection();
            Assert.AreEqual(1, called.Value);

            con.Close();
            Assert.AreEqual(1, called.Value);
            mockConnection.Verify(c => c.Close(), Times.Never());

            connectionFactory.CreateConnection();
            Assert.AreEqual(1, called.Value);

            connectionFactory.Dispose();
            Assert.AreEqual(0, called.Value);
            mockConnection.Verify(c => c.Close(), Times.AtLeastOnce());

            mockConnectionFactory.Verify(c => c.CreateConnection(), Times.Exactly(1));
        }
        public void TestWithConnectionFactoryDestroy()
        {
            var mocker = new AutoMoqer();

            var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>();
            var mockConnection = mocker.GetMock<RabbitMQ.Client.IConnection>();
            var mockChannel1 = new Mock<IModel>();
            var mockChannel2 = new Mock<IModel>();

            Assert.AreNotSame(mockChannel1, mockChannel2);

            mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(c => c.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object);
            mockConnection.Setup(c => c.IsOpen).Returns(true);

            // Called during physical close
            mockChannel1.Setup(c => c.IsOpen).Returns(true);
            mockChannel2.Setup(c => c.IsOpen).Returns(true);

            var ccf = new CachingConnectionFactory(mockConnectionFactory.Object);
            ccf.ChannelCacheSize = 2;

            var con = ccf.CreateConnection();

            // This will return a proxy that surpresses calls to close
            var channel1 = con.CreateChannel(false);
            var channel2 = con.CreateChannel(false);

            // Should be ignored, and add last into channel cache.
            channel1.Close();
            channel2.Close();

            // remove first entry in cache (channel1)
            var ch1 = con.CreateChannel(false);

            // remove first entry in cache (channel2)
            var ch2 = con.CreateChannel(false);

            Assert.AreSame(ch1, channel1);
            Assert.AreSame(ch2, channel2);

            var target1 = ((IChannelProxy)ch1).GetTargetChannel();
            var target2 = ((IChannelProxy)ch2).GetTargetChannel();

            // make sure mokito returned different mocks for the channel
            Assert.AreNotSame(target1, target2);

            ch1.Close();
            ch2.Close();
            con.Close(); // should be ignored

            ccf.Dispose(); // should call close on connection and channels in cache

            mockConnection.Verify(c => c.CreateModel(), Times.Exactly(2));

            mockConnection.Verify(c => c.Close(), Times.Exactly(1));

            // verify(mockChannel1).close();
            mockChannel2.Verify(c => c.Close(), Times.Exactly(1));

            // After destroy we can get a new connection
            var con1 = ccf.CreateConnection();
            Assert.AreNotSame(con, con1);

            // This will return a proxy that surpresses calls to close
            var channel3 = con.CreateChannel(false);
            Assert.AreNotSame(channel3, channel1);
            Assert.AreNotSame(channel3, channel2);
        }
        /// <summary>The apply.</summary>
        /// <returns>The System.Boolean.</returns>
        public bool Apply()
        {
            // Check at the beginning, so this can be used as a static field
            if (this.assumeOnline)
            {
                Assume.That(BrokerOnline.Get(this.port));
            }
            else
            {
                Assume.That(BrokerOffline.Get(this.port));
            }

            var connectionFactory = new CachingConnectionFactory();

            try
            {
                connectionFactory.Port = this.port;
                if (!string.IsNullOrWhiteSpace(this.hostName))
                {
                    connectionFactory.Host = this.hostName;
                }

                var admin = new RabbitAdmin(connectionFactory);
                var exchange = new FederatedExchange("fedDirectRuleTest");
                exchange.BackingType = "direct";
                exchange.UpstreamSet = "upstream-set";
                admin.DeclareExchange(exchange);
                admin.DeleteExchange("fedDirectRuleTest");

                BrokerOffline.AddOrUpdate(this.port, false);

                if (!this.assumeOnline)
                {
                    Assume.That(BrokerOffline.Get(this.port));
                }
            }
            catch (Exception e)
            {
                Logger.Warn(m => m("Not executing tests because federated connectivity test failed"), e);
                BrokerOnline.AddOrUpdate(this.port, false);
                if (this.assumeOnline)
                {
                    Assume.That(e == null, "An exception occurred.");
                    return false;
                }
            }
            finally
            {
                connectionFactory.Dispose();
            }

            return true;

            // return super.apply(base, method, target);
        }
 public void TestDoubleDeclarationOfExclusiveQueue()
 {
     // Expect exception because the queue is locked when it is declared a second time.
     var connectionFactory1 = new CachingConnectionFactory();
     connectionFactory1.Port = BrokerTestUtils.GetPort();
     var connectionFactory2 = new CachingConnectionFactory();
     connectionFactory2.Port = BrokerTestUtils.GetPort();
     var queue = new Queue("test.queue", false, true, true);
     this.rabbitAdmin.DeleteQueue(queue.Name);
     new RabbitAdmin(connectionFactory1).DeclareQueue(queue);
     try
     {
         new RabbitAdmin(connectionFactory2).DeclareQueue(queue);
     }
     catch (Exception ex)
     {
         Assert.True(ex is AmqpIOException, "Expecting an AmqpIOException");
     }
     finally
     {
         // Need to release the connection so the exclusive queue is deleted
         connectionFactory1.Dispose();
     }
 }
 public void TestDoubleDeclarationOfAutodeleteQueue()
 {
     // No error expected here: the queue is autodeleted when the last consumer is cancelled, but this one never has
     // any consumers.
     var connectionFactory1 = new CachingConnectionFactory();
     connectionFactory1.Port = BrokerTestUtils.GetPort();
     var connectionFactory2 = new CachingConnectionFactory();
     connectionFactory2.Port = BrokerTestUtils.GetPort();
     var queue = new Queue("test.queue", false, false, true);
     new RabbitAdmin(connectionFactory1).DeclareQueue(queue);
     new RabbitAdmin(connectionFactory2).DeclareQueue(queue);
     connectionFactory1.Dispose();
     connectionFactory2.Dispose();
 }
        /// <summary>
        /// Applies this instance.
        /// </summary>
        /// <returns>Something here.</returns>
        /// <remarks></remarks>
        public bool Apply()
        {
            // Check at the beginning, so this can be used as a static field
            if (this.assumeOnline)
            {
                Assume.That(brokerOnline[this.port] == true);
            }
            else
            {
                Assume.That(brokerOffline[this.port] == true);
            }

            var connectionFactory = new CachingConnectionFactory();

            try
            {
                connectionFactory.Port = this.port;
                if (StringUtils.HasText(this.hostName))
                {
                    connectionFactory.Host = this.hostName;
                }

                var admin = new RabbitAdmin(connectionFactory);

                foreach (var queue in this.queues)
                {
                    var queueName = queue.Name;

                    if (this.purge)
                    {
                        logger.Debug("Deleting queue: " + queueName);

                        // Delete completely - gets rid of consumers and bindings as well
                        admin.DeleteQueue(queueName);
                    }

                    if (this.IsDefaultQueue(queueName))
                    {
                        // Just for test probe.
                        admin.DeleteQueue(queueName);
                    }
                    else
                    {
                        admin.DeclareQueue(queue);
                    }
                }

                if (brokerOffline.ContainsKey(this.port))
                {
                    brokerOffline[this.port] = false;
                }
                else
                {
                    brokerOffline.Add(this.port, false);
                }

                if (!this.assumeOnline)
                {
                    Assume.That(brokerOffline[this.port] == true);
                }

            }
            catch (Exception e)
            {
                logger.Warn("Not executing tests because basic connectivity test failed", e);
                if (brokerOnline.ContainsKey(this.port))
                {
                    brokerOnline[this.port] = false;
                }
                else
                {
                    brokerOnline.Add(this.port, false);
                }

                if (this.assumeOnline)
                {
                    // Assume.That(!(e is Exception));
                }
            }
            finally
            {
                connectionFactory.Dispose();
            }

            return true;

            // return base.Apply(base, method, target);
        }
        /// <summary>
        /// Applies this instance.
        /// </summary>
        /// <returns>Something here.</returns>
        public bool Apply()
        {
            // Check at the beginning, so this can be used as a static field
            if (this.assumeOnline)
            {
                Assume.That(brokerOnline[this.port]);
            }
            else
            {
                Assume.That(brokerOffline[this.port]);
            }

            var connectionFactory = new CachingConnectionFactory();

            try
            {
                connectionFactory.Port = this.port;
                if (!string.IsNullOrWhiteSpace(this.hostName))
                {
                    connectionFactory.Host = this.hostName;
                }

                var admin = new RabbitAdmin(connectionFactory);

                foreach (var queue in this.queues)
                {
                    var queueName = queue.Name;

                    if (this.purge)
                    {
                        Logger.Debug("Deleting queue: " + queueName);

                        // Delete completely - gets rid of consumers and bindings as well
                        try
                        {
                            admin.DeleteQueue(queueName);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn("Could not delete queue. Assuming it didn't exist.", ex);
                        }
                    }

                    if (this.IsDefaultQueue(queueName))
                    {
                        // Just for test probe.
                        try
                        {
                            admin.DeleteQueue(queueName);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn("Could not delete queue. Assuming it didn't exist.", ex);
                        }
                    }
                    else
                    {
                        admin.DeclareQueue(queue);
                    }
                }

                brokerOffline.AddOrUpdate(this.port, false);

                if (!this.assumeOnline)
                {
                    Assume.That(brokerOffline[this.port]);
                }
            }
            catch (Exception e)
            {
                Logger.Warn("Not executing tests because basic connectivity test failed", e);

                brokerOnline.AddOrUpdate(this.port, false);

                if (this.assumeOnline)
                {
                    return false;

                    // Assume.That(!(e is Exception));
                }
            }
            finally
            {
                connectionFactory.Dispose();
            }

            return true;

            // return base.Apply(base, method, target);
        }