def testPublishAndPurgeOnMultipleQueues(self):
        """ Test that queues are properly purged"""
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName1 = "testQueue1"
        queueName2 = "testQueue2"
        routingKey1 = "testKey1"
        routingKey2 = "testKey2"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName1)
        self.client.declareQueue(queueName2)
        self.client.bindQueue(queueName1, exchangeName, routingKey1)
        self.client.bindQueue(queueName2, exchangeName, routingKey2)

        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d-queue1" % (i)),
                                exchangeName, routingKey1)
        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d-queue2" % (i)),
                                exchangeName, routingKey2)

        self._verifyQueue(queueName1, testMessageCount=_NUM_TEST_MESSAGES)
        self._verifyQueue(queueName2, testMessageCount=_NUM_TEST_MESSAGES)
        self.client.purgeQueue(queueName1)
        self._verifyQueue(queueName1, testMessageCount=0)
        self._verifyQueue(queueName2, testMessageCount=_NUM_TEST_MESSAGES)
        self.client.purgeQueue(queueName2)
        self._verifyQueue(queueName2, testMessageCount=0)
    def testPublishMandatoryMessage(self):
        """
    Tests sending an unroutable message after enabling publisher
    acknowledgements.
    """
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        self.client.enablePublisherAcks()

        self.assertRaises(UnroutableError,
                          self.client.publish,
                          Message("test-msg"),
                          exchangeName,
                          "fakeKey",
                          mandatory=True)

        self.client.publish(Message("test-msg"),
                            exchangeName,
                            routingKey,
                            mandatory=True)
    def testConsumerGetNextEvent(self):
        """ Tests getting messages using a consumer and getNextEvent(). """
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d" % (i)), exchangeName,
                                routingKey)
        self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)

        consumer = self.client.createConsumer(queueName)

        for i in range(0, _NUM_TEST_MESSAGES):
            message = self.client.getNextEvent()
            self.assertEqual(message.body, "test-msg-%d" % (i))
            self.assertEqual(message.properties, BasicProperties())
            self.assertEqual(
                message.methodInfo,
                MessageDeliveryInfo(consumerTag=consumer.tag,
                                    deliveryTag=(i + 1),
                                    redelivered=False,
                                    exchange=exchangeName,
                                    routingKey=routingKey))
    def testEnablePublisherAcksAfterUnroutableMessage(self):
        """
    Tests enabling publisher acknowledgements after an unroutable message has
    already been sent.
    """
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        self.client.publish(Message("test-msg"),
                            exchangeName,
                            "fakeKey",
                            mandatory=True)

        with self.assertRaises(UnroutableError) as cm:
            self.client.enablePublisherAcks()

        self.assertEqual(
            cm.exception.messages[0],
            ReturnedMessage(body="test-msg",
                            properties=BasicProperties(),
                            methodInfo=MessageReturnInfo(
                                replyCode=312,
                                replyText="NO_ROUTE",
                                exchange=exchangeName,
                                routingKey="fakeKey")))
    def testGetOneMessage(self):
        """ Tests getting messages using getOneMessage. """
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d" % (i)), exchangeName,
                                routingKey)
        self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)

        for i in range(0, _NUM_TEST_MESSAGES):
            message = self.client.getOneMessage(queueName)
            _LOGGER.info("getOneMessage() = %s", message.__repr__())
            self.assertEqual(message.body, "test-msg-%d" % (i))
            self.assertEqual(message.properties, BasicProperties())
            self.assertEqual(
                message.methodInfo,
                MessageGetInfo(deliveryTag=(i + 1),
                               redelivered=False,
                               exchange=exchangeName,
                               routingKey=routingKey,
                               messageCount=(_NUM_TEST_MESSAGES - 1 - i)))
    def testAckAllMessages(self):
        """ Tests acking all messages"""
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d" % (i)), exchangeName,
                                routingKey)
        self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)

        self._verifyReadyMessages(queueName)

        self.client.createConsumer(queueName)
        self._verifyUnacknowledgedMessages(queueName)

        self.client.ackAll()
        self._verifyAcknowledgedMessages(queueName)
  def testNackingMessages(self):
    """Tests nacking messages """
    self._connectToClient()
    exchangeName = "testExchange"
    exchangeType = "direct"
    queueName = "testQueue"
    routingKey = "testKey"

    self.client.declareExchange(exchangeName, exchangeType)
    self.client.declareQueue(queueName)
    self.client.bindQueue(queueName, exchangeName, routingKey)

    for i in range(0, _NUM_TEST_MESSAGES):
      # Test random numbers of messages sent to the queue
      self.client.publish(Message("test-msg-%d" % (i)),
                          exchangeName,
                          routingKey)
    self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)

    self.client.createConsumer(queueName)
    self._hasEvent()

    self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES,
                      testConsumerCount=1)

    for i in range(0, _NUM_TEST_MESSAGES):
      self.client.getNextEvent().nack()

    self._verifyQueue(queueName, testMessageCount=0, testConsumerCount=1)

    @_RETRY_ON_ASSERTION_ERROR
    def _verifyNackedMessages():
      """
      Verifies that messages are unacknowledged on server in nested function to
      use the _RETRY_ON_ASSERTION_ERROR decorator.
      """
      queue = requests.get(
          url="http://%s:%s/api/queues/%s/%s" % (
              self.connParams.host,
              self.connParams.port,
              self.connParams.vhost,
              queueName),
          auth=(self.connParams.username, self.connParams.password)
      ).json()
      self.assertEqual(queue["messages"], 0)
      self.assertEqual(queue["messages_unacknowledged"], 0)
    _verifyNackedMessages()
    def testPublishMessage(self):
        """ Test that published messages reach their specified queues"""
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        # Test message publishing
        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d" % (i)), exchangeName,
                                routingKey)

        self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)
    def testRecoverUnackedMessages(self):
        """ Tests the recover method to re-queue unacked messages. """
        self._connectToClient()
        exchangeName = "testExchange"
        exchangeType = "direct"
        queueName = "testQueue"
        routingKey = "testKey"

        self.client.declareExchange(exchangeName, exchangeType)
        self.client.declareQueue(queueName)
        self.client.bindQueue(queueName, exchangeName, routingKey)

        for i in range(0, _NUM_TEST_MESSAGES):
            # Test random numbers of messages sent to the queue
            self.client.publish(Message("test-msg-%d" % (i)), exchangeName,
                                routingKey)
        self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)

        consumer = self.client.createConsumer(queueName)

        for i in range(0, _NUM_TEST_MESSAGES):
            message = self.client.getNextEvent()
            self.assertEqual(message.body, "test-msg-%d" % (i))
            self.assertEqual(message.properties, BasicProperties())
            self.assertEqual(
                message.methodInfo,
                MessageDeliveryInfo(consumerTag=consumer.tag,
                                    deliveryTag=(i + 1),
                                    redelivered=False,
                                    exchange=exchangeName,
                                    routingKey=routingKey))

        self._verifyUnacknowledgedMessages(queueName)

        self.client.recover(requeue=True)

        @_RETRY_ON_ASSERTION_ERROR
        def _verifyRecoveredMessages():
            """
      Verifies that messages are unacknowledged on server in nested function to
      use the _RETRY_ON_ASSERTION_ERROR decorator.
      """
            queue = requests.get(url="http://%s:%s/api/queues/%s/%s" %
                                 (self.connParams.host, self.connParams.port,
                                  self.connParams.vhost, queueName),
                                 auth=(self.connParams.username,
                                       self.connParams.password)).json()
            self.assertIn("redeliver", queue["message_stats"])
            self.assertEqual(queue["message_stats"]["redeliver"],
                             _NUM_TEST_MESSAGES)

        _verifyRecoveredMessages()

        for i in range(0, _NUM_TEST_MESSAGES):
            message = self.client.getNextEvent()
            self.assertEqual(message.body, "test-msg-%d" % (i))
            self.assertEqual(message.properties, BasicProperties())
            self.assertEqual(
                message.methodInfo,
                MessageDeliveryInfo(consumerTag=consumer.tag,
                                    deliveryTag=(_NUM_TEST_MESSAGES + i + 1),
                                    redelivered=True,
                                    exchange=exchangeName,
                                    routingKey=routingKey))