def __init__(self, *args, **kwargs): registered_apps = [ settings.SIM_OPERATION_CODES[opcode] for opcode in MockRouter.REGISTERED_OPCODES ] kwargs[ 'apps'] = settings.APPS_BEFORE_SIM + settings.SIM_PRE_APPS + tuple( registered_apps) + settings.APPS_AFTER_SIM BlockingRouter.__init__(self, *args, **kwargs)
class RouterBackendTest(CreateDataMixin, TestCase): """BlockingRouter backend tests.""" def setUp(self): self.router = BlockingRouter(apps=[], backends={}) def test_valid_backend_path(self): """Valid RapidSMS backend modules should load properly.""" backend = self.router.add_backend( "backend", "rapidsms.backends.base.BackendBase") self.assertEqual(1, len(self.router.backends.keys())) self.assertEqual(backend, self.router.backends["backend"]) def test_router_downcases_backend_configs(self): """Backend configuration should automatically be lowercased.""" test_backend = "rapidsms.backends.base.BackendBase" test_conf = {"a": 1, "B": 2, "Cc": 3} backend = self.router.add_backend("backend", test_backend, test_conf) self.assertEqual(len(backend._config), 3) self.assertIn("a", backend._config) self.assertIn("b", backend._config) self.assertIn("cc", backend._config) self.assertNotIn("B", backend._config) self.assertNotIn("Cc", backend._config) def test_add_backend_class(self): """Router.add_backend should also accept a class.""" self.router.add_backend("backend", BackendBase) self.assertEqual(1, len(self.router.backends.keys())) self.assertIn("backend", self.router.backends.keys()) self.assertEqual("backend", self.router.backends['backend'].name) def test_router_not_configured_with_backend(self): """ send_to_backend should raise MessageSendingError if backend hasn't been configured with the router. """ args = ("missing-backend", "1234", "hello", ["1112223333"], {}) self.assertRaises(MessageSendingError, self.router.send_to_backend, *args) def test_backend_send_raises_error(self): """ send_to_backend should capture all backend exceptions and raise the standard MessageSendingError. """ backend = self.router.add_backend("backend", RaisesBackend) args = (backend.model.name, "1234", "hello", ["1112223333"], {}) self.assertRaises(MessageSendingError, self.router.send_to_backend, *args) @mock.patch('rapidsms.router.blocking.router.logger') def test_send_captures_exception(self, mock_logger): """BlockingRouter should catch exceptions during sending.""" backend = self.router.add_backend("backend", RaisesBackend) msg = self.create_outgoing_message(backend=backend.model) # shouldn't raise an error self.router.send_outgoing(msg) # but should log an exception mock_logger.exception.assert_called_once_with( 'backend encountered an error while sending.')
class RouterBackendTest(CreateDataMixin, TestCase): """BlockingRouter backend tests.""" def setUp(self): self.router = BlockingRouter(apps=[], backends={}) def test_valid_backend_path(self): """Valid RapidSMS backend modules should load properly.""" backend = self.router.add_backend("backend", "rapidsms.backends.base.BackendBase") self.assertEqual(1, len(self.router.backends.keys())) self.assertEqual(backend, self.router.backends["backend"]) def test_router_downcases_backend_configs(self): """Backend configuration should automatically be lowercased.""" test_backend = "rapidsms.backends.base.BackendBase" test_conf = {"a": 1, "B": 2, "Cc": 3} backend = self.router.add_backend("backend", test_backend, test_conf) self.assertEqual(len(backend._config), 3) self.assertIn("a", backend._config) self.assertIn("b", backend._config) self.assertIn("cc", backend._config) self.assertNotIn("B", backend._config) self.assertNotIn("Cc", backend._config) def test_add_backend_class(self): """Router.add_backend should also accept a class.""" self.router.add_backend("backend", BackendBase) self.assertEqual(1, len(self.router.backends.keys())) self.assertIn("backend", self.router.backends.keys()) self.assertEqual("backend", self.router.backends['backend'].name) def test_router_not_configured_with_backend(self): """ send_to_backend should raise MessageSendingError if backend hasn't been configured with the router. """ args = ("missing-backend", "1234", "hello", ["1112223333"], {}) self.assertRaises(MessageSendingError, self.router.send_to_backend, *args) def test_backend_send_raises_error(self): """ send_to_backend should capture all backend exceptions and raise the standard MessageSendingError. """ backend = self.router.add_backend("backend", RaisesBackend) args = (backend.model.name, "1234", "hello", ["1112223333"], {}) self.assertRaises(MessageSendingError, self.router.send_to_backend, *args) @mock.patch('rapidsms.router.blocking.router.logger') def test_send_captures_exception(self, mock_logger): """BlockingRouter should catch exceptions during sending.""" backend = self.router.add_backend("backend", RaisesBackend) msg = self.create_outgoing_message(backend=backend.model) # shouldn't raise an error self.router.send_outgoing(msg) # but should log an exception mock_logger.exception.assert_called_once_with('backend encountered an error while sending.')
class RouterAppTest(TestCase): """BlockingRouter app tests.""" def setUp(self): self.router = BlockingRouter(apps=[], backends={}) def test_valid_app_path(self): """Valid RapidSMS app modules should load properly.""" app = self.router.add_app("rapidsms.contrib.default") self.assertTrue(app is not None) self.assertEquals(1, len(self.router.apps)) def test_invalid_app_path(self): """Invalid RapidSMS app modules shouldn't raise any errors.""" app = self.router.add_app('django.conrib.admin') self.assertTrue(app is None) def test_get_app_by_path(self): """get_app() returns loaded app matching the passed module.""" app1 = self.router.add_app("rapidsms.contrib.default") app2 = self.router.get_app("rapidsms.contrib.default") self.assertEqual(app1, app2) def test_get_invalid_app_by_path(self): """get_app() returns None when loaded app is not found.""" app = self.router.get_app("not.a.valid.app") self.assertTrue(app is None) def test_add_app_with_class(self): """add_app() should also accept a class.""" self.router.add_app(AppBase) self.assertEquals(1, len(self.router.apps))
def rapidsms_handle_message(msg, incoming=True): """Simple Celery task to process messages via BlockingRouter.""" logger = rapidsms_handle_message.get_logger() if incoming: direction_name = 'incoming' else: direction_name = 'outgoing' logger.debug('New %s message: %s' % (direction_name, msg)) router = BlockingRouter() try: router.start() if incoming: router.incoming(msg) else: router.outgoing(msg) router.stop() except Exception, e: logger.exception(e)
def setUp(self): self.router = BlockingRouter(apps=[], backends={})
# the rest of settings.py? import stock.apps as _stock_apps import equipment.apps as _equipment_apps import info.apps as _info_apps import contextual.app as _contextual_apps RAPIDSMS_APP_BASES = ( _stock_apps.StockLevel, _stock_apps.StockOut, _equipment_apps.EquipmentFailure, _equipment_apps.EquipmentRepaired, _info_apps.Help, _equipment_apps.FridgeTemperature, ) # Configure the RapidSMS router based on RAPIDSMS_APP_BASES from rapidsms.router.blocking import BlockingRouter RAPIDSMS_ROUTER = BlockingRouter() for app in RAPIDSMS_APP_BASES: RAPIDSMS_ROUTER.add_app(app) # Assign operation codes to AppBase handlers. SIM_OPERATION_CODES = { "SL": _stock_apps.StockLevel, "SE": _stock_apps.StockOut, "NF": _equipment_apps.EquipmentFailure, "RE": _equipment_apps.EquipmentRepaired, "HE": _info_apps.Help, "FT": _equipment_apps.FridgeTemperature, "FC": _contextual_apps.FacilityCode, }
class BlockingRouterTest(harness.CreateDataMixin, TestCase): """Test router phases and message classes.""" def setUp(self): self.router = BlockingRouter(apps=[], backends={}) def test_router_incoming_phases(self): """Incoming messages should trigger proper router phases.""" self.router.add_app(harness.MockApp) self.router.receive_incoming(self.create_incoming_message()) self.assertEqual(set(self.router.apps[0].calls), set(self.router.incoming_phases)) def test_router_outgoing_phases(self): """Outgoing messages should trigger proper router phases.""" self.router.add_app(harness.MockApp) self.router.add_backend("mockbackend", harness.MockBackend) backend = self.create_backend(data={'name': 'mockbackend'}) connection = self.create_connection(data={'backend': backend}) msg = self.create_outgoing_message(data={'connections': [connection]}) self.router.send_outgoing(msg) self.assertEqual(set(self.router.apps[0].calls), set(self.router.outgoing_phases)) def test_new_incoming_message(self): """BaseRouter should return a standard IncomingMessage by default.""" fields = {'foo': 'bar'} connection = self.create_connection() msg = self.router.new_incoming_message(text="foo", connections=[connection], fields=fields) self.assertTrue(isinstance(msg, IncomingMessage)) self.assertEqual("foo", msg.text) self.assertEqual(connection, msg.connections[0]) self.assertEqual(fields['foo'], msg.fields['foo']) def test_new_incoming_message_class(self): """Make sure you can customize the incoming message class.""" class TestIncomingMessage(IncomingMessage): pass connection = self.create_connection() msg = self.router.new_incoming_message(text="foo", connections=[connection], class_=TestIncomingMessage) self.assertTrue(isinstance(msg, TestIncomingMessage)) def test_new_outgoing_message(self): """BaseRouter should return a standard OutgoingMessage by default.""" fields = {'foo': 'bar'} connection = self.create_connection() incoming_message = self.create_incoming_message() msg = self.router.new_outgoing_message(text="foo", connections=[connection], fields=fields, in_response_to=incoming_message) self.assertTrue(isinstance(msg, OutgoingMessage)) self.assertEqual("foo", msg.text) self.assertEqual(connection, msg.connections[0]) self.assertEqual(fields['foo'], msg.fields['foo']) self.assertEqual(incoming_message, msg.in_response_to) def test_new_outgoing_message_class(self): """Make sure you can customize the outgoing message class.""" class TestOutgoingMessage(OutgoingMessage): pass connection = self.create_connection() msg = self.router.new_outgoing_message(text="foo", connections=[connection], class_=TestOutgoingMessage) self.assertTrue(isinstance(msg, TestOutgoingMessage))
def __init__(self, *args, **kwargs): registered_apps = [settings.SIM_OPERATION_CODES[opcode] for opcode in MockRouter.REGISTERED_OPCODES] kwargs['apps'] = settings.APPS_BEFORE_SIM + settings.SIM_PRE_APPS + tuple(registered_apps) + settings.APPS_AFTER_SIM BlockingRouter.__init__(self, *args, **kwargs)