Пример #1
0
def run():
    message_store = FakeMessageStore()
    message_mapper_registry = MessageMapperRegistry()
    message_mapper_registry.register(HelloWorldCommand,
                                     map_hellworldcommand_to_message)
    connection = Connection("amqp://*****:*****@localhost:5672//",
                            "paramore.brightside.exchange",
                            is_durable=True)
    producer = ArameProducer(connection)

    command_processor = CommandProcessor(
        message_mapper_registry=message_mapper_registry,
        message_store=message_store,
        producer=producer)

    try:
        loop = 0
        while True:
            message = "Hello " + str(loop)
            hello = HelloWorldCommand(message)
            print("Sending message: {}".format(message))
            command_processor.post(hello)
            loop += 1

            if loop % 100 == 0:
                time.sleep(5)
    except KeyboardInterrupt:
        sys.exit(1)
Пример #2
0
    def setUp(self):
        self._messageMapperRegistry = MessageMapperRegistry()
        self._messageMapperRegistry.register(MyCommand,
                                             map_mycommand_to_message)

        self._message_store = FakeMessageStore()
        self._producer = FakeProducer()
        self._commandProcessor = CommandProcessor(
            message_mapper_registry=self._messageMapperRegistry,
            message_store=self._message_store,
            producer=self._producer)
Пример #3
0
def run():

    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="the name to send a greeting to")
    args = parser.parse_args()

    registry = Registry()
    registry.register(HelloWorldCommand, lambda: HelloWorldCommandHandler())

    command_processor = CommandProcessor(registry)

    hello = HelloWorldCommand(args.name)
    command_processor.send(hello)
Пример #4
0
def command_processor_factory(channel_name: str):
    handler = LongRunningCommandHandler()

    subscriber_registry = Registry()
    subscriber_registry.register(LongRunningCommand, lambda: handler)

    command_processor = CommandProcessor(registry=subscriber_registry)
    return command_processor
Пример #5
0
def run():
    message_store = FakeMessageStore()
    message_mapper_registry = MessageMapperRegistry()
    message_mapper_registry.register(LongRunningCommand,
                                     map_longrunningcommand_to_message)
    connection = Connection("amqp://*****:*****@localhost:5672//",
                            "paramore.brightside.exchange",
                            is_durable=True)
    producer = ArameProducer(connection)

    command_processor = CommandProcessor(
        message_mapper_registry=message_mapper_registry,
        message_store=message_store,
        producer=producer)

    job = LongRunningCommand(60)
    command_processor.post(job)
Пример #6
0
    def test_missing_message_producer(self):
        """given that we have no me message producer configured for the commandprocessor
            when we post a command
            it should raise a confiugration error
        """
        self._commandProcessor = CommandProcessor(
            message_mapper_registry=self._messageMapperRegistry,
            message_store=self._message_store,
            producer=None)

        was_exception_thrown = False
        try:
            request = MyCommand()
            self._commandProcessor.post(request)
        except ConfigurationException:
            was_exception_thrown = True

        self.assertTrue(was_exception_thrown)
Пример #7
0
def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="the name to send a greeting to")
    args = parser.parse_args()

    message_store = FakeMessageStore()
    message_mapper_registry = MessageMapperRegistry()
    message_mapper_registry.register(HelloWorldCommand, map_hellworldcommand_to_message)
    connection = Connection("amqp://*****:*****@localhost:5672//", "paramore.brightside.exchange", is_durable=True)
    producer = ArameProducer(connection)

    command_processor = CommandProcessor(
        message_mapper_registry=message_mapper_registry,
        message_store=message_store,
        producer=producer
    )

    hello = HelloWorldCommand(args.name)
    command_processor.post(hello)
Пример #8
0
def command_processor_factory(channel_name: str):

    engine = create_engine(config[os.getenv('WORKER_CONFIG')
                                  or 'default'].SQLALCHEMY_DATABASE_URI)

    uow = sessionmaker(bind=engine)

    handler = ToDoCreatedEventHandler(uow)

    subscriber_registry = Registry()
    subscriber_registry.register(ToDoCreated, lambda: handler)

    command_processor = CommandProcessor(registry=subscriber_registry)
    return command_processor
Пример #9
0
class LoggingAndMonitoringFixture(unittest.TestCase):
    def setUp(self):
        self._subscriber_registry = Registry()
        self._commandProcessor = CommandProcessor(
            registry=self._subscriber_registry)

    def test_logging_a_handler(self):
        """s
        Given that I have a handler decorated for logging
        When I call that handler
        Then I should receive logs indicating the call and return of the handler
        * N.b. This is an example of using decorators to extend the Brightside pipeline
        """
        handler = MyCommandHandler()
        request = MyCommand()
        self._subscriber_registry.register(MyCommand, lambda: handler)
        logger = logging.getLogger("tests.handlers_testdoubles")
        with patch.object(logger, 'log') as mock_log:
            self._commandProcessor.send(request)

        mock_log.assert_has_calls([
            call(logging.DEBUG, "Entering handle " + str(request)),
            call(logging.DEBUG, "Exiting handle " + str(request))
        ])
 def setUp(self):
     self._subscriber_registry = Registry()
     self._commandProcessor = CommandProcessor(
         registry=self._subscriber_registry)
class PipelineTests(unittest.TestCase):
    """Tests of decorators on handlers.
        It is worth noting that whereas Brighter has to create a mechanism to allow decorators on the target handler, Python
        already has a decorator syntax. As this maps well to the attributes used by Brighter to signal the decorators
        used to meet orthogonal concerns it is natural to just use Python's own decorator syntax in Brightside, over
        rolling up a bespoke mechanism. Indeed, the use of attributes and decorator classes in Brighter mirrors functionality avaailable
        to Pythoh via its decorator syntax
        This test suite is really about proving we can provide equivalent functionality
        We use Benjamin Hodgoson's Poll library, which is itself inspired by Polly, the library used by Brighter
    """
    def setUp(self):
        self._subscriber_registry = Registry()
        self._commandProcessor = CommandProcessor(
            registry=self._subscriber_registry)

    def test_handle_retry_on_command(self):
        """ given that we have a retry plocy for a command, when we raise an exception, then we should retry n times or until succeeds """
        handler = MyHandlerSupportingRetry()
        request = MyCommand()
        self._subscriber_registry.register(MyCommand, lambda: handler)
        self._commandProcessor.send(request)

        self.assertTrue(
            handler.called,
            "Expected the handle method on the handler to be called with the message"
        )
        self.assertTrue(handler.call_count == 3,
                        "Expected two retries of the pipeline")

    def test_exceed_retry_on_command(self):
        """ given that we have a retry policy for a command, when we raise an exception, then we should bubble the exception out after n retries"""
        handler = MyHandlerBreakingAfterRetry()
        request = MyCommand()
        self._subscriber_registry.register(MyCommand, lambda: handler)

        exception_raised = False
        try:
            self._commandProcessor.send(request)
        except RuntimeError:
            exception_raised = True

        self.assertTrue(
            exception_raised,
            "Exepcted the exception to bubble out, when we run out of retries")
        self.assertFalse(
            handler.called,
            "Did not expect the handle method on the handler to be called with the message"
        )
        self.assertTrue(handler.call_count == 3,
                        "Expected two retries of the pipeline")

    def test_handle_circuit_breaker_on_command(self):
        """ given that we have a circuit breaker policy for a command, when we raise an exception, then we should break the circuit after n retries"""
        handler = MyHandlerBreakingCircuitAfterThreeFailures()
        request = MyCommand()
        self._subscriber_registry.register(MyCommand, lambda: handler)

        exception_raised = False
        try:
            self._commandProcessor.send(request)
        except RuntimeError:
            exception_raised = True

        # Now see if the circuit is broken following the failed call
        circuit_broken = False
        try:
            self._commandProcessor.send(request)
        except CircuitBrokenError:
            circuit_broken = True

        self.assertTrue(
            exception_raised,
            "Exepcted an exception to be raised, when we run out of retries")
        self.assertTrue(circuit_broken,
                        "Expected the circuit to be broken to further calls")
        self.assertFalse(
            handler.called,
            "Did not expect the handle method on the handler to be called with the message"
        )
        self.assertTrue(handler.call_count == 3,
                        "Expected two retries of the pipeline")
Пример #12
0
class CommandProcessorFixture(unittest.TestCase):
    """ Command Processor tests """
    def setUp(self):
        self._subscriber_registry = Registry()
        self._commandProcessor = CommandProcessor(
            registry=self._subscriber_registry)

    def test_handle_command(self):
        """ given that we have a handler registered for a command, when we send a command, it should call the handler"""
        handler = MyCommandHandler()
        request = MyCommand()
        self._subscriber_registry.register(MyCommand, lambda: handler)
        self._commandProcessor.send(request)

        self.assertTrue(
            handler.called,
            "Expected the handle method on the handler to be called with the message"
        )

    def test_handle_event(self):
        """ Given that we have many handlers registered of an event, when we raise an event, it should call all the handlers"""

        handler = MyEventHandler()
        other_handler = MyEventHandler()
        request = MyEvent()
        self._subscriber_registry.register(MyEvent, lambda: handler)
        self._subscriber_registry.register(MyEvent, lambda: other_handler)
        self._commandProcessor.publish(request)

        self.assertTrue(handler.called,
                        "The first handler should be called with the message")
        self.assertTrue(
            (other_handler,
             "The second handler should also be called with the message"))

    def test_missing_command_handler_registration(self):
        """Given that we are missing a handler for a command, when we send a command, it should throw an exception"""

        handler = MyCommandHandler()
        request = MyCommand()

        exception_thrown = False
        try:
            self._commandProcessor.send(request)
        except:
            exception_thrown = True

        self.assertTrue(
            exception_thrown,
            "Expected an exception to be thrown when no handler is registered for a command"
        )

    def test_missing_event_handler_registration(self):
        """Given that we have no handlers register for an event, when we raise an event, it should not error """

        handler = MyEventHandler()
        other_handler = MyEventHandler()
        request = MyEvent()

        exception_thrown = False
        try:
            self._commandProcessor.publish(request)
        except:
            exception_thrown = True

        self.assertFalse(
            exception_thrown,
            "Did not expect an exception to be thrown where there are no handlers for an event"
        )
Пример #13
0
class PostTests(unittest.TestCase):
    def setUp(self):
        self._messageMapperRegistry = MessageMapperRegistry()
        self._messageMapperRegistry.register(MyCommand,
                                             map_mycommand_to_message)

        self._message_store = FakeMessageStore()
        self._producer = FakeProducer()
        self._commandProcessor = CommandProcessor(
            message_mapper_registry=self._messageMapperRegistry,
            message_store=self._message_store,
            producer=self._producer)

    def test_handle_command(self):
        """ given that we have a message mapper and producer registered for a commnd,
            when we post a command,
            it should send via the producer
        """
        request = MyCommand()
        self._commandProcessor.post(request)

        self.assertTrue(self._message_store.message_was_added,
                        "Expected a message to be added")
        self.assertTrue(self._message_store.get_message(request.id),
                        "Expected the command to be converted into a message")
        self.assertTrue(self._producer.was_sent_message,
                        "Expected a message to be sent via the producer")
        self.assertTrue(str(self._message_store.get_message(request.id).body),
                        "")

    def test_missing_message_mapper(self):
        """given that we have no message mapper registered for a command
            when we post a command
            it should raise an error
        """
        request = MyOtherCommand()

        was_exception_thrown = False
        try:
            self._commandProcessor.post(request)
        except ConfigurationException:
            was_exception_thrown = True

        # it looks as though we should use self_assertRaises...
        self.assertTrue(was_exception_thrown, "")

    def test_missing_message_producer(self):
        """given that we have no me message producer configured for the commandprocessor
            when we post a command
            it should raise a confiugration error
        """
        self._commandProcessor = CommandProcessor(
            message_mapper_registry=self._messageMapperRegistry,
            message_store=self._message_store,
            producer=None)

        was_exception_thrown = False
        try:
            request = MyCommand()
            self._commandProcessor.post(request)
        except ConfigurationException:
            was_exception_thrown = True

        self.assertTrue(was_exception_thrown)

    def test_missing_message_mapper_registry(self):
        """ given that we have no message mapper registry for the commandprocessor
            when we post a command
            it should raise a configuration error
        """
        self._commandProcessor = CommandProcessor(
            message_mapper_registry=None,
            message_store=self._message_store,
            producer=self._producer)

        was_exception_thrown = False
        try:
            request = MyCommand()
            self._commandProcessor.post(request)
        except ConfigurationException:
            was_exception_thrown = True

        self.assertTrue(was_exception_thrown)