/// <summary>Initializes a new instance of the <see cref="CachedChannelInvocationHandler"/> class.</summary>
 /// <param name="target">The target.</param>
 /// <param name="channelList">The channel list.</param>
 /// <param name="transactional">if set to <c>true</c> [transactional].</param>
 /// <param name="outer">The outer.</param>
 public CachedChannelInvocationHandler(IModel target, LinkedList <IChannelProxy> channelList, bool transactional, CachingConnectionFactory outer)
 {
     this.target        = target;
     this.channelList   = channelList;
     this.transactional = transactional;
     this.outer         = outer;
 }
        public void CachedChannel()
        {
            TestConnectionFactory testConnectionFactory = new TestConnectionFactory();

            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(testConnectionFactory, "localhost:" + RabbitUtils.DEFAULT_PORT);

            IConnection con1 = cachingConnectionFactory.CreateConnection();
            Assert.AreEqual(1, testConnectionFactory.CreateConnectionCount);

            IModel model1 = con1.CreateModel();
            TestModel testModel = GetTestModel(model1);
            Assert.AreEqual(1, testModel.CreatedCount);
            Assert.AreEqual(0, testModel.CloseCount);
            Assert.AreEqual(1, testConnectionFactory.CreateConnectionCount);

            model1.Close();  // won't close, will put in channel cache.
            Assert.AreEqual(0, testModel.CloseCount);

            IModel model2 = con1.CreateModel();
            TestModel testModel2 = GetTestModel(model2);

            Assert.AreSame(testModel, testModel2);

            Assert.AreEqual(1, testModel.CreatedCount);
            Assert.AreEqual(0, testModel.CloseCount);
            Assert.AreEqual(1, testConnectionFactory.CreateConnectionCount);
        }
 public CachedModel(IModel targetModel, LinkedList<IModel> modelList, CachingConnectionFactory ccf)
 {
     target = targetModel;
     this.modelList = modelList;
     this.modelCacheSize = ccf.ChannelCacheSize;
     this.ccf = ccf;
 }
        public void TestWithConnectionFactoryDefaults()
        {
            var mockConnectionFactory = new Mock<ConnectionFactory>();
            var mockConnection = new Mock<IConnection>();
            var mockChannel = new Mock<IModel>();

            mockConnectionFactory.Setup(factory => factory.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(connection => connection.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup(chan => chan.IsOpen).Returns(true);
            mockConnection.Setup(conn => conn.IsOpen).Returns(true);

            var ccf = new CachingConnectionFactory(mockConnectionFactory.Object);
            var con = ccf.CreateConnection();

            var channel = con.CreateChannel(false);
            channel.Close(); // should be ignored, and placed into channel cache.
            con.Close(); // should be ignored

            var con2 = ccf.CreateConnection();

            /*
             * will retrieve same channel object that was just put into channel cache
             */
            var channel2 = con2.CreateChannel(false);
            channel2.Close(); // should be ignored
            con2.Close(); // should be ignored

            Assert.AreSame(con, con2);
            Assert.AreSame(channel, channel2);
            mockConnection.Verify(conn => conn.Close(), Times.Never());
            mockChannel.Verify(chan => chan.Close(), Times.Never());
        }
 public void CreateConnectionFactory()
 {
     this.brokerIsRunning = BrokerRunning.IsRunningWithEmptyQueues(queue);
     var connectionFactory = new CachingConnectionFactory();
     connectionFactory.ChannelCacheSize = concurrentConsumers;
     connectionFactory.Port = BrokerTestUtils.GetPort();
     template.ConnectionFactory = connectionFactory;
 }
        public void TestCacheSizeExceeded()
        {
            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>();
            var mockChannel3 = new Mock<IModel>();

            mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(c => c.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object, mockChannel3.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);
            mockChannel3.Setup(c => c.IsOpen).Returns(true);

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

            var con = ccf.CreateConnection();

            var channel1 = con.CreateChannel(false);

            // cache size is 1, but the other connection is not released yet so this creates a new one
            var channel2 = con.CreateChannel(false);
            Assert.AreNotSame(channel1, channel2);

            // should be ignored, and added last into channel cache.
            channel1.Close();

            // should be physically closed
            channel2.Close();

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

            // create a new channel
            var ch2 = con.CreateChannel(false);

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

            ch1.Close();
            ch2.Close();

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

            con.Close(); // should be ignored

            mockConnection.Verify(c => c.Close(), Times.Never());
            mockChannel1.Verify(c => c.Close(), Times.Never());
            mockChannel2.Verify(c => c.Close(), Times.AtLeastOnce());
            mockChannel3.Verify(c => c.Close(), Times.AtLeastOnce());
        }
        public void FixtureSetup()
        {
            IConnectionFactory connectionFactory = new CachingConnectionFactory();

            template = new RabbitTemplate();
            template.ConnectionFactory = connectionFactory;
            template.ChannelTransacted = true;
            template.AfterPropertiesSet();
        }
 public void Init()
 {
     var connectionFactory = new CachingConnectionFactory();
     this.template = new RabbitTemplate(connectionFactory);
     this.template.IsChannelTransacted = true;
     var transactionManager = new RabbitTransactionManager(connectionFactory);
     this.transactionTemplate = new TransactionTemplate(transactionManager);
     this.transactionTemplate.TransactionIsolationLevel = IsolationLevel.Unspecified;
 }
 public void DeclareQueue()
 {
     /*if (repeat.isInitialized()) {
         // Important to prevent concurrent re-initialization
         return;
     }*/
     this.connectionFactory = new CachingConnectionFactory();
     this.connectionFactory.ChannelCacheSize = 4;
     this.connectionFactory.Port = BrokerTestUtils.GetPort();
     this.template.ConnectionFactory = this.connectionFactory;
 }
        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));
        }
        private static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                var helloWorldQueue = new Queue("hello.world.queue");

                amqpAdmin.DeclareQueue(helloWorldQueue);

                //Each queue is automatically bound to the default direct exchange.

                Console.WriteLine("Queue [hello.world.queue] has been declared.");
                Console.WriteLine("Press 'enter' to exit");
                Console.ReadLine();
            }
        }
        public static void Configure()
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                //Each queue is automatically bound to the default direct exchange.
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_REQUEST_QUEUE_NAME"]));
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_RESPONSE_QUEUE_NAME"]));

                //handled by the java server app on startup
                //TopicExchange mktDataExchange = new TopicExchange(ConfigurationManager.AppSettings["MARKET_DATA_EXCHANGE_NAME"], false, false);
                //amqpAdmin.DeclareExchange(mktDataExchange);

                var mktDataQueue = new Queue(ConfigurationManager.AppSettings["MARKET_DATA_QUEUE_NAME"]);
                amqpAdmin.DeclareQueue(mktDataQueue);
            }
        }
        protected RabbitTemplate InitializeAndCreateTemplate()
        {
            connectionFactory = new CachingConnectionFactory();

            RabbitTemplate template = new RabbitTemplate();
            template.ConnectionFactory = connectionFactory;
            template.ChannelTransacted = true;
            template.AfterPropertiesSet();

            //Declare queue and bind to a specific exchange.
            template.Execute<object>(delegate(IModel model)
                                         {
                                             model.QueueDeclare(TestConstants.QUEUE_NAME);

                                             model.QueueBind(TestConstants.QUEUE_NAME, TestConstants.EXCHANGE_NAME, TestConstants.ROUTING_KEY, false, null);
                                             return null;
                                         });
            return template;
        }
        static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                //Each queue is automatically bound to the default direct exchange.
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_REQUEST_QUEUE_NAME"]));
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_RESPONSE_QUEUE_NAME"]));

                TopicExchange mktDataExchange = new TopicExchange(ConfigurationManager.AppSettings["MARKET_DATA_EXCHANGE_NAME"], false, false);
                amqpAdmin.DeclareExchange(mktDataExchange);
                Queue mktDataQueue = new Queue(ConfigurationManager.AppSettings["MARKET_DATA_QUEUE_NAME"]);
                amqpAdmin.DeclareQueue(mktDataQueue);

                Console.WriteLine("Queues and exchanges have been declared.");
                Console.WriteLine("Press 'enter' to exit");
                Console.ReadLine();
            }
        }
        public void CachedModelTwoRequests()
        {
            TestConnectionFactory testConnectionFactory = new TestConnectionFactory();

            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(testConnectionFactory, "localhost:" + RabbitUtils.DEFAULT_PORT);

            //Create a session
            IConnection con1 = cachingConnectionFactory.CreateConnection();
            Assert.AreEqual(1, testConnectionFactory.CreateConnectionCount);

            //Create a model
            IModel model1 = con1.CreateModel();
            TestModel testModel1 = GetTestModel(model1);
            Assert.AreEqual(1, testModel1.CreatedCount);
            Assert.AreEqual(0, testModel1.CloseCount);

            //will create a new model, not taken from the cache since cache size is 1.
            IModel model2 = con1.CreateModel();
            TestModel testModel2 = GetTestModel(model2);
            Assert.AreEqual(1, testModel2.CreatedCount);
            Assert.AreEqual(0, testModel2.CloseCount);

            Assert.AreNotSame(testModel1, testModel2);
            Assert.AreNotSame(model1, model2);

            model1.Close(); // will put the model in the cache

            // now get a new model, will be taken from the cache
            IModel model3 = con1.CreateModel();
            TestModel testModel3 = GetTestModel(model3);
            Assert.AreSame(testModel1, testModel3);
            Assert.AreSame(model1, model3);
            Assert.AreEqual(1, testModel1.CreatedCount);
            Assert.AreEqual(0, testModel1.CloseCount);

            Assert.AreEqual(1, testConnectionFactory.CreateConnectionCount);
        }
        public void TestWithConnectionFactoryCacheSize()
        {
            var mocker = new AutoMoqer();

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

            mockConnectionFactory.Setup(a => a.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(a => a.IsOpen).Returns(true);
            mockConnection.Setup(a => a.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object);
            mockChannel1.Setup(a => a.BasicGet("foo", false)).Returns(new BasicGetResult(0, false, null, null, 1, null, null));
            mockChannel2.Setup(a => a.BasicGet("bar", false)).Returns(new BasicGetResult(0, false, null, null, 1, null, null));
            mockChannel1.Setup(a => a.IsOpen).Returns(true);
            mockChannel2.Setup(a => a.IsOpen).Returns(true);

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

            var con = ccf.CreateConnection();

            var channel1 = con.CreateChannel(false);
            var channel2 = con.CreateChannel(false);

            channel1.BasicGet("foo", true);
            channel2.BasicGet("bar", true);

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

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

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

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

            ch1.Close();
            ch2.Close();

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

            con.Close(); // should be ignored

            mockConnection.Verify(c => c.Close(), Times.Never());
            mockChannel1.Verify(c => c.Close(), Times.Never());
            mockChannel2.Verify(c => c.Close(), Times.Never());
        }
        public void TestTransactionalAndNonTransactionalChannelsSegregated()
        {
            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>();

            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 = 1;

            var con = ccf.CreateConnection();

            var channel1 = con.CreateChannel(true);
            channel1.TxSelect();
            channel1.Close(); // should be ignored, and add last into channel cache.

            /*
             * When a channel is created as non-transactional we should create a new one.
             */
            var channel2 = con.CreateChannel(false);
            channel2.Close(); // should be ignored, and add last into channel cache.
            Assert.AreNotSame(channel1, channel2);

            var ch1 = con.CreateChannel(true); // remove first entry in cache (channel1)
            var ch2 = con.CreateChannel(false); // create new channel

            Assert.AreNotSame(ch1, ch2);
            Assert.AreSame(ch1, channel1); // The non-transactional one
            Assert.AreSame(ch2, channel2);

            ch1.Close();
            ch2.Close();

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

            con.Close(); // should be ignored

            mockConnection.Verify(c => c.Close(), Times.Never());
            mockChannel1.Verify(c => c.Close(), Times.Never());
            mockChannel2.Verify(c => c.Close(), Times.Never());

            var notxlist = (LinkedList<IChannelProxy>)ReflectionUtils.GetInstanceFieldValue(ccf, "cachedChannelsNonTransactional");
            Assert.AreEqual(1, notxlist.Count);

            var txlist = (LinkedList<IChannelProxy>)ReflectionUtils.GetInstanceFieldValue(ccf, "cachedChannelsTransactional");
            Assert.AreEqual(1, txlist.Count);
        }
        private RabbitTemplate CreateTemplate(int concurrentConsumers)
        {
            var template = new RabbitTemplate();

            // SingleConnectionFactory connectionFactory = new SingleConnectionFactory();
            var connectionFactory = new CachingConnectionFactory();
            connectionFactory.ChannelCacheSize = concurrentConsumers;
            connectionFactory.Port = BrokerTestUtils.GetPort();
            template.ConnectionFactory = connectionFactory;
            return template;
        }
 /// <summary>Initializes a new instance of the <see cref="ChannelCachingConnectionProxy"/> class.</summary>
 /// <param name="target">The target.</param>
 /// <param name="outer">The outer.</param>
 public ChannelCachingConnectionProxy(IConnection target, CachingConnectionFactory outer)
 {
     this.target = target;
     this.outer = outer;
 }
 /// <summary>Initializes a new instance of the <see cref="CachedChannelInvocationHandler"/> class.</summary>
 /// <param name="target">The target.</param>
 /// <param name="channelList">The channel list.</param>
 /// <param name="transactional">if set to <c>true</c> [transactional].</param>
 /// <param name="outer">The outer.</param>
 public CachedChannelInvocationHandler(IModel target, LinkedList<IChannelProxy> channelList, bool transactional, CachingConnectionFactory outer)
 {
     this.target = target;
     this.channelList = channelList;
     this.transactional = transactional;
     this.outer = outer;
 }
 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();
     }
 }
        /// <summary>
        /// Does the test.
        /// </summary>
        /// <param name="concurrentConsumers">The concurrent consumers.</param>
        /// <param name="configurer">The configurer.</param>
        /// <remarks></remarks>
        private void DoTest(int concurrentConsumers, IContainerConfigurer configurer)
        {
            var messageCount = 10;
            var template = new RabbitTemplate();
            var connectionFactory = new CachingConnectionFactory();
            connectionFactory.ChannelCacheSize = concurrentConsumers;
            connectionFactory.Port = BrokerTestUtils.GetPort();
            template.ConnectionFactory = connectionFactory;
            var messageConverter = new SimpleMessageConverter();
            messageConverter.CreateMessageIds = true;
            template.MessageConverter = messageConverter;
            for (var i = 0; i < messageCount; i++)
            {
                template.ConvertAndSend(queue1.Name, i.ToString());
                template.ConvertAndSend(queue2.Name, i.ToString());
            }

            var container = new SimpleMessageListenerContainer(connectionFactory);
            var latch = new CountdownEvent(messageCount * 2);
            var listener = new MultiplePocoListener(latch);
            container.MessageListener = new MessageListenerAdapter(listener);
            container.AcknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.AUTO;
            container.IsChannelTransacted = true;
            container.ConcurrentConsumers = concurrentConsumers;
            configurer.Configure(container);
            container.AfterPropertiesSet();
            container.Start();
            try
            {
                var timeout = Math.Min((1 + messageCount) / concurrentConsumers, 30);
                var waited = latch.Wait(timeout * 1000);
                logger.Info("All messages recovered: " + waited);
                Assert.AreEqual(concurrentConsumers, container.ActiveConsumerCount);
                Assert.True(waited, "Timed out waiting for messages");
            }
            catch (ThreadInterruptedException e)
            {
                Thread.CurrentThread.Interrupt();
                throw new ThreadStateException("unexpected interruption");
            }
            finally
            {
                container.Shutdown();
                Assert.AreEqual(0, container.ActiveConsumerCount);
            }
            Assert.Null(template.ReceiveAndConvert(queue1.Name));
            Assert.Null(template.ReceiveAndConvert(queue2.Name));
        }
 /// <summary>
 /// Creates the connection factory.
 /// </summary>
 /// <returns>The connection factory.</returns>
 protected virtual IConnectionFactory CreateConnectionFactory()
 {
     var connectionFactory = new CachingConnectionFactory();
     connectionFactory.ChannelCacheSize = this.concurrentConsumers;
     connectionFactory.Port = BrokerTestUtils.GetPort();
     return connectionFactory;
 }
 public void SetUp()
 {
     this.connectionFactory = new CachingConnectionFactory();
     this.brokerIsRunning = BrokerRunning.IsRunning();
     this.connectionFactory.Port = BrokerTestUtils.GetPort();
 }
        /// <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>
 /// Initializes a new instance of the <see cref="RabbitAdminIntegrationTests"/> class. 
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 /// <remarks>
 /// </remarks>
 public RabbitAdminIntegrationTests()
 {
     this.connectionFactory = new CachingConnectionFactory();
     this.connectionFactory.Port = BrokerTestUtils.GetPort();
     this.brokerIsRunning = BrokerRunning.IsRunning();
 }
        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>Initializes a new instance of the <see cref="ChannelCachingConnectionProxy"/> class.</summary>
 /// <param name="target">The target.</param>
 /// <param name="outer">The outer.</param>
 public ChannelCachingConnectionProxy(IConnection target, CachingConnectionFactory outer)
 {
     this.target = target;
     this.outer  = outer;
 }
        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));
        }
        /// <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 CreateConnectionFactory()
 {
     if (environment.IsActive())
     {
         var connectionFactory = new CachingConnectionFactory();
         connectionFactory.ChannelCacheSize = this.concurrentConsumers;
         connectionFactory.Port = BrokerTestUtils.GetAdminPort();
         this.connectionFactory = connectionFactory;
         this.brokerIsRunning = BrokerRunning.IsRunningWithEmptyQueues(this.queue);
         this.brokerIsRunning.Apply();
     }
 }
 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();
 }