def test_open_connection_successfully(self):
        # When
        connection_handler = ConnectionHandler(common.BROKER_URL_TEST)

        # Then
        connection = connection_handler.get_current_connection()
        assert connection.is_open is True
示例#2
0
    def init_app(self, app, queues, on_message_callback):
        """ Init the Broker by using the given configuration instead
        default settings.

        :param app: Current application context
        :param list queues: Queues which the message will be post
        :param callback on_message_callback: callback to execute when new
        message is pulled to RabbitMQ
        """
        if not hasattr(app, 'extensions'):
            app.extensions = {}

        if 'broker_rabbit' not in app.extensions:
            app.extensions['broker_rabbit'] = self
        else:
            # Raise an exception if extension already initialized as
            # potentially new configuration would not be loaded.
            raise RuntimeError('Extension already initialized')

        self.url = app.config.get('RABBIT_MQ_URL', DEFAULT_URL)
        self.exchange_name = app.config.get('EXCHANGE_NAME', DEFAULT_EXCHANGE_NAME)
        self.application_id = app.config.get('APPLICATION_ID', DEFAULT_APPLICATION_ID)
        self.delivery_mode = app.config.get('DELIVERY_MODE', DEFAULT_DELIVERY_MODE)
        self.queues = queues
        self.on_message_callback = on_message_callback

        # Open Connection to RabbitMQ
        self.connection_handler = ConnectionHandler(self.url)
        connection = self.connection_handler.get_current_connection()

        # Setup default producer for broker_rabbit
        self.producer = Producer(
            connection, self.exchange_name,
            self.application_id, self.delivery_mode)
        self.producer.bootstrap(self.queues)
示例#3
0
    def init_app(self, app, queues, on_message_callback):
        """ Init the Broker by using the given configuration instead
        default settings.

        :param app: Current application context
        :param list queues: Queues which the message will be post
        :param callback on_message_callback: callback to execute when new
        message is pulled to RabbitMQ
        """
        self.url = app.config.get('RABBIT_MQ_URL', DEFAULT_URL)
        self.exchange_name = app.config.get('EXCHANGE_NAME', DEFAULT_EXCHANGE)
        self.application_id = app.config.get('APPLICATION_ID', DEFAULT_APP)
        self.delivery_mode = app.config.get('DELIVERY_MODE', DEFAULT_DELIVERY)
        self.queues = queues
        self.on_message_callback = on_message_callback

        # Open Connection to RabbitMQ
        self.connection_handler = ConnectionHandler(self.url)
        connection = self.connection_handler.get_current_connection()

        # Setup default producer for broker_rabbit
        channel = ProducerChannel(connection, self.application_id,
                                  self.delivery_mode)
        self.producer = Producer(channel, self.exchange_name)
        self.producer.bootstrap(self.queues)
    def test_initialize_new_connection(self):
        # When
        connection_handler = ConnectionHandler(common.BROKER_URL_TEST)

        # Then
        connection = connection_handler.get_current_connection()
        assert connection.is_open
        assert isinstance(connection, BlockingConnection)
示例#5
0
class TestChannelHandler(RabbitBrokerTest):
    def setup_method(self, method):
        self.connection = ConnectionHandler(common.BROKER_URL_TEST)
        current_connection = self.connection.get_current_connection()
        self.channel_handler = ChannelHandler(current_connection)

    def test_should_raise_when_connection_is_not_defined(self):
        # Given
        connection = None
        channel_handler = ChannelHandler(connection)

        # When
        with pytest.raises(ConnectionNotOpenedError) as error:
            channel_handler.open()

        # Then
        assert 'The connection is not opened' == error.value.args[0][0]

    def test_should_raise_when_connection_is_closed(self):
        # Given
        self.connection.close_connection()

        # When
        with pytest.raises(ConnectionIsClosedError) as error:
            self.channel_handler.open()

        # Then
        assert 'The connection is closed' == error.value.args[0][0]

    def test_should_open_channel(self):
        # When
        self.channel_handler.open()

        # Then
        assert self.channel_handler.get_channel().is_open is True

    def test_should_close_channel(self):
        # Given
        self.channel_handler.open()

        # When
        self.channel_handler.close()

        # Then
        assert self.channel_handler.get_channel().is_closed is True

    def test_should_raise_when_channel_is_not_defined(self):
        # Given
        self.channel_handler._channel = None

        # When
        with pytest.raises(ChannelUndefinedError) as error:
            self.channel_handler.get_channel()

        # Then
        assert 'The channel does not exist yet' == error.value.args[0][0]
示例#6
0
 def setup(self):
     connection = ConnectionHandler(common.BROKER_URL_TEST)
     current_connection = connection.get_current_connection()
     self.exchange_name = 'TEST-EXCHANGE-NAME'
     self.application_id = 'TEST-APPLICATION-ID'
     self.delivery_mode = 2
     channel_handler = ProducerChannel(
         current_connection, self.application_id, self.delivery_mode)
     channel_handler.open()
     self.channel = channel_handler.get_channel()
     self.channel = Mock(ProducerChannel)
     self.message = "TEST-CONTENT-MESSAGE"
    def test_raises_when_trying_to_open_connection_with_bad_credentials(self):
        # Given
        rabbit_url = "amqp://*****:*****@localhost:5672/%2F"

        # When and Then is expecting an exception to be raised
        with pytest.raises(ProbableAuthenticationError):
            ConnectionHandler(rabbit_url)
    def test_raise_when_trying_to_open_connection_with_bad_port(self):
        # Given
        rabbit_url = "amqp://*****:*****@localhost:8225/%2F"

        # When and Then is expecting an exception to be raised
        with pytest.raises(ConnectionClosed):
            ConnectionHandler(rabbit_url)
示例#9
0
 def setup_method(self):
     self.connection = ConnectionHandler(common.BROKER_URL_TEST)
     current_connection = self.connection.get_current_connection()
     self.channel_handler = ChannelHandler(current_connection)
示例#10
0
class BrokerRabbitMQ:
    """Message Broker based on RabbitMQ middleware"""

    def __init__(self, app=None, queues=None):
        """
        Create a new instance of Broker Rabbit by using
        the given parameters to connect to RabbitMQ.
        """
        self.app = app
        self.queues = queues
        self.connection_handler = None
        self.producer = None
        self.url = None
        self.exchange_name = None
        self.application_id = None
        self.delivery_mode = None
        self.on_message_callback = None

        if self.app is not None:
            self.init_app(self.app, self.queues)

    def init_app(self, app, queues, on_message_callback):
        """ Init the Broker by using the given configuration instead
        default settings.

        :param app: Current application context
        :param list queues: Queues which the message will be post
        :param callback on_message_callback: callback to execute when new
        message is pulled to RabbitMQ
        """
        if not hasattr(app, 'extensions'):
            app.extensions = {}

        if 'broker_rabbit' not in app.extensions:
            app.extensions['broker_rabbit'] = self
        else:
            # Raise an exception if extension already initialized as
            # potentially new configuration would not be loaded.
            raise RuntimeError('Extension already initialized')

        self.url = app.config.get('RABBIT_MQ_URL', DEFAULT_URL)
        self.exchange_name = app.config.get('EXCHANGE_NAME', DEFAULT_EXCHANGE_NAME)
        self.application_id = app.config.get('APPLICATION_ID', DEFAULT_APPLICATION_ID)
        self.delivery_mode = app.config.get('DELIVERY_MODE', DEFAULT_DELIVERY_MODE)
        self.queues = queues
        self.on_message_callback = on_message_callback

        # Open Connection to RabbitMQ
        self.connection_handler = ConnectionHandler(self.url)
        connection = self.connection_handler.get_current_connection()

        # Setup default producer for broker_rabbit
        self.producer = Producer(
            connection, self.exchange_name,
            self.application_id, self.delivery_mode)
        self.producer.bootstrap(self.queues)

    def send(self, queue, context={}):
        """Post the message to the correct queue with the given context

        :param str queue: queue which to post the message
        :param dict context: content of the message to post to RabbitMQ server
        """
        if queue not in self.queues:
            message = 'Queue ‘{name}‘ is not registered'.format(name=queue)
            raise UnknownQueueError(message)

        message = {
            'created_at': datetime.utcnow().isoformat(),
            'queue': queue,
            'context': context
        }

        return self.producer.publish(queue, message)
示例#11
0
class BrokerRabbitMQ:
    """Message Broker based on RabbitMQ middleware"""
    def __init__(self, app=None):
        """
        Create a new instance of Broker Rabbit by using
        the given parameters to connect to RabbitMQ.
        """
        self.app = app
        self.connection_handler = None
        self.producer = None
        self.url = None
        self.exchange_name = None
        self.application_id = None
        self.delivery_mode = None
        self.queues = None
        self.on_message_callback = None

    def init_app(self, app, queues, on_message_callback):
        """ Init the Broker by using the given configuration instead
        default settings.

        :param app: Current application context
        :param list queues: Queues which the message will be post
        :param callback on_message_callback: callback to execute when new
        message is pulled to RabbitMQ
        """
        self.url = app.config.get('RABBIT_MQ_URL', DEFAULT_URL)
        self.exchange_name = app.config.get('EXCHANGE_NAME', DEFAULT_EXCHANGE)
        self.application_id = app.config.get('APPLICATION_ID', DEFAULT_APP)
        self.delivery_mode = app.config.get('DELIVERY_MODE', DEFAULT_DELIVERY)
        self.queues = queues
        self.on_message_callback = on_message_callback

        # Open Connection to RabbitMQ
        self.connection_handler = ConnectionHandler(self.url)
        connection = self.connection_handler.get_current_connection()

        # Setup default producer for broker_rabbit
        channel = ProducerChannel(connection, self.application_id,
                                  self.delivery_mode)
        self.producer = Producer(channel, self.exchange_name)
        self.producer.bootstrap(self.queues)

    def send(self, queue, context={}):
        """Post the message to the correct queue with the given context

        :param str queue: queue which to post the message
        :param dict context: content of the message to post to RabbitMQ server
        """
        if queue not in self.queues:
            error_msg = f'Queue ‘{queue}‘ is not registered'
            raise UnknownQueueError(error_msg)

        message = {
            'created_at': datetime.utcnow().isoformat(),
            'queue': queue,
            'context': context
        }

        return self.producer.publish(queue, message)

    def list_queues(self):
        """List all available queue in the app"""
        for queue in self.queues:
            print('Queue name : `%s`' % queue)

    def start(self, queue):
        """Start worker on a given queue
        :param queue: the queue which you consume message for
        """
        if queue not in self.queues:
            raise RuntimeError(f'Queue with name`{queue}` not found')

        worker = Worker(connection_handler=self.connection_handler,
                        message_callback=self.on_message_callback,
                        queue=queue)
        print(f'Start consuming message on the queue `{queue}`')
        worker.consume_message()