def test_event_dispatcher(mock_container): container = mock_container container.service_name = "srcservice" service = Mock() worker_ctx = WorkerContext(container, service, DummyProvider("dispatch")) event_dispatcher = EventDispatcher(retry_policy={'max_retries': 5}).bind( container, attr_name="dispatch") event_dispatcher.setup() service.dispatch = event_dispatcher.get_dependency(worker_ctx) from mock import ANY with patch('nameko.standalone.events.producers') as mock_producers: with mock_producers[ANY].acquire() as mock_producer: service.dispatch('eventtype', 'msg') headers = event_dispatcher.get_message_headers(worker_ctx) mock_producer.publish.assert_called_once_with( 'msg', exchange=ANY, headers=headers, serializer=container.serializer, routing_key='eventtype', retry=True, retry_policy={'max_retries': 5}) _, call_kwargs = mock_producer.publish.call_args exchange = call_kwargs['exchange'] assert exchange.name == 'srcservice.events'
def test_restricted_parameters( self, mock_container, producer ): """ Verify that providing routing parameters at instantiation time has no effect. """ mock_container.config = {'AMQP_URI': 'memory://localhost'} mock_container.service_name = "service" worker_ctx = Mock() worker_ctx.context_data = {} exchange = Mock() routing_key = Mock() dispatcher = EventDispatcher( exchange=exchange, routing_key=routing_key, ).bind(mock_container, "dispatch") dispatcher.setup() dispatch = dispatcher.get_dependency(worker_ctx) event_exchange = get_event_exchange("service") event_type = "event-type" dispatch(event_type, "event-data") assert producer.publish.call_args[1]['exchange'] == event_exchange assert producer.publish.call_args[1]['routing_key'] == event_type
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config): vhost = rabbit_config['vhost'] container = Mock(spec=ServiceContainer) container.service_name = "srcservice" container.config = rabbit_config service = Mock() worker_ctx = WorkerContext(container, service, DummyProvider()) dispatcher = EventDispatcher() dispatcher.bind("dispatch", container) dispatcher.prepare() dispatcher.start() # we should have an exchange but no queues exchanges = rabbit_manager.get_exchanges(vhost) queues = rabbit_manager.get_queues(vhost) assert "srcservice.events" in [exchange['name'] for exchange in exchanges] assert queues == [] # manually add a queue to capture the events rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True) rabbit_manager.create_binding(vhost, "srcservice.events", "event-sink", rt_key=ExampleEvent.type) dispatcher.inject(worker_ctx) service.dispatch(ExampleEvent("msg")) # test event receieved on manually added queue messages = rabbit_manager.get_messages(vhost, "event-sink") assert ['msg'] == [msg['payload'] for msg in messages]
def test_restricted_parameters(self, mock_container, producer): """ Verify that providing routing parameters at instantiation time has no effect. """ mock_container.config = {'AMQP_URI': 'memory://localhost'} mock_container.service_name = "service" worker_ctx = Mock() worker_ctx.context_data = {} exchange = Mock() routing_key = Mock() dispatcher = EventDispatcher( exchange=exchange, routing_key=routing_key, ).bind(mock_container, "dispatch") dispatcher.setup() dispatch = dispatcher.get_dependency(worker_ctx) event_exchange = get_event_exchange("service", config={}) event_type = "event-type" dispatch(event_type, "event-data") assert producer.publish.call_args[1]['exchange'] == event_exchange assert producer.publish.call_args[1]['routing_key'] == event_type
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config): vhost = rabbit_config['vhost'] container = Mock(spec=ServiceContainer) container.service_name = "srcservice" container.config = rabbit_config service = Mock() worker_ctx = WorkerContext(container, service, None) dispatcher = EventDispatcher() dispatcher.bind("dispatch", container) dispatcher.prepare() dispatcher.start() # we should have an exchange but no queues exchanges = rabbit_manager.get_exchanges(vhost) queues = rabbit_manager.get_queues(vhost) assert "srcservice.events" in [exchange['name'] for exchange in exchanges] assert queues == [] # manually add a queue to capture the events rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True) rabbit_manager.create_binding(vhost, "srcservice.events", "event-sink", rt_key=ExampleEvent.type) dispatcher.inject(worker_ctx) service.dispatch(ExampleEvent("msg")) # test event receieved on manually added queue messages = rabbit_manager.get_messages(vhost, "event-sink") assert ['msg'] == [msg['payload'] for msg in messages]
def test_event_dispatcher(empty_config): container = Mock(spec=ServiceContainer) container.service_name = "srcservice" container.config = empty_config service = Mock() worker_ctx = WorkerContext(container, service, "dispatch") event_dispatcher = EventDispatcher() event_dispatcher.bind("dispatch", container) path = 'nameko.messaging.PublishProvider.prepare' with patch(path, autospec=True) as prepare: # test start method event_dispatcher.prepare() assert event_dispatcher.exchange.name == "srcservice.events" assert prepare.called evt = Mock(type="eventtype", data="msg") event_dispatcher.inject(worker_ctx) producer = Mock() with patch.object( event_dispatcher, 'get_producer', autospec=True) as get_producer: get_producer.return_value = as_context_manager(producer) # test dispatch service.dispatch(evt) headers = event_dispatcher.get_message_headers(worker_ctx) producer.publish.assert_called_once_with( evt.data, exchange=event_dispatcher.exchange, headers=headers, routing_key=evt.type)
class UsersService(UserMixin): name = "users" auth = Auth() tracer = Tracer() db_session = DatabaseSession(DeclarativeBase) event_dispatcher = EventDispatcher() @http("GET", "/healthcheck") def health_check_http(self, request): return json.dumps(self.health_check()) @rpc def health_check(self): result = {"status": "ok"} return result @rpc def check_jwt(self): try: decoded_jwt = self.auth.decode_jwt() except InvalidToken: return None try: user = self.get_user(uuid=decoded_jwt["uuid"]) except UserNotFound: return None return self.auth.encode_jwt({ "uuid": user["uuid"], "email": user["email"] })
class SubscriptionManagerService(object): name = 'subscription_manager' database = MongoDatabase(result_backend=False) dispatch = EventDispatcher() @rpc def add_subscription(self, user, subscription): _log.info(f'Adding a subscription to {user} ...') self.database.subscriptions.update_one({'user': user}, { '$set': { 'subscription': subscription, 'modification_date': datetime.datetime.utcnow() } }, upsert=True) payload = {'user': user, 'subscription': subscription} self.dispatch('user_sub', payload) @rpc def get_subscription_by_user(self, user): cursor = self.database.subscriptions.find_one({'user': user}, {'_id': 0}) return bson.json_util.dumps(cursor)
class EventRaisingService(object): name = "event_raiser" dispatch = EventDispatcher() @rpc def say_hello(self): self.dispatch('hello', self.name)
class BookingService: name = "booking_service" db = Database(Base) dispatcher = EventDispatcher() @http("POST", "/restaurants/<int:restaurant_id>") def book_table(self, request: Request, restaurant_id: int) -> Response: request_params = json.loads(request.data) command = BookTableCommand(restaurant_id=restaurant_id, persons=request_params["persons"]) booking_table_service = BookingTableApplicationService( SQLAlchemyRestaurantRepository(self.db.session), SQLAlchemyUnitOfWork(self.db.session), NamekoEventPublisher(self.dispatcher), ) booking_table_service.book_table(command) return Response(f"Restaurant: {restaurant_id} table booked") @http("GET", "/up") def up(self, request: Request) -> Response: return Response("I'm alive") @http("GET", "/restaurants") def restaurants(self, request: Request) -> Response: repo = SQLAlchemyRestaurantRepository(self.db.session) return Response( json.dumps([restaurant_serializer(r) for r in repo.all()]))
class ContactsService: name = 'contacts' session = DatabaseSession(DeclarativeBase) dispatch = EventDispatcher() auto_crud = AutoCrudWithEvents( session, dispatch, 'contact', model_cls=Contact, get_method_name='get_contact', create_method_name='create_contact', update_method_name='update_contact', list_method_name='list_contacts', count_method_name='count_contacts', create_event_name='contact_created', update_event_name='contact_updated', ) @rtm.handle_message('^create contact (?P<name>\w+)') def slack_create_contact(self, event, message, name=None): return 'Contact created on platform: {}'.format( self.create_contact({'name': name}))
class ServiceA(object): name = 'servicea' dispatch = EventDispatcher() @rpc def emit_an_event(self): self.dispatch('my_event_type', 'payload')
class PaymentService: name = "paymentService" db = Session() event_dispatcher = EventDispatcher() @rpc def pay(self, order, status): total_price = 0 for orderdetail in order['order_details']: total_price += float(orderdetail['price']) payment = Payment(order_id=order['id'],total_price=total_price,status=status) self.db.add(payment) self.db.commit() payment = schemas.PaymentSchema().dump(payment) print(payment) self.event_dispatcher('pay_success', {'payment': payment}) return payment @rpc def refund(self, order_id): trans = self.db.begin(subtransactions=True) payment = self.db.query(Payment).filter(Payment.order_id == order_id).first() if not payment: raise NotFound('Payment with order_id {} not found'.format(order_id)) payment.status = 2 trans.commit() payment = schemas.PaymentSchema().dump(payment) self.event_dispatcher('refund', {'payment': payment}) return payment
class ServiceCCC: name = "service_ccc" dispatch = EventDispatcher() @rpc def dispatching_method(self, payload): self.dispatch("event_type", payload)
class ImagePublishService: name = "image_publish_service" dispatch = EventDispatcher() @rpc def pushToQueue(self, fileinfo1,clientId): try: fileinfo = base64.b64decode(fileinfo1[22:]) imgNpArr = np.fromstring(fileinfo, np.ubyte) #print(imgNpArr.shape) img_np = cv2.imdecode(imgNpArr, 1) height, width, numberFrames = img_np.shape imageSize = img_np.size dataObject = {'clientId':clientId,'imageName': 'xyz.png', 'imgSize': str(imageSize), 'imgHeight': str(height), 'imgWidth': str(width), 'imgNoOfPlanes': str(numberFrames),'image':fileinfo1} #self.dispatch("process_hr", dataObject) self.dispatch("process_ear", dataObject) self.dispatch("process_gender",dataObject) self.dispatch("process_emotion", dataObject) #self.dispatch("process_hpos", dataObject) except Exception as exp: print('Exception occured during Image Capture due to ' + str(exp)) raise exp
class EventDispatchWithCidMixin(object): """ Example usage: MyClass(EventDispatchWithCidMixin): ... # Dispatch event self.dispatch_event("user_created", {"email": email, "uuid": uuid}) """ logger = logging.getLogger(__name__) # Nameko Config is a simple dependency provider config = Config() # Nameko event dispatcher dispatch = EventDispatcher() def dispatch_event(self, event_name: str, event_data: dict): """ Dispatch event """ self.logger.debug("Dispatching event: %s, event data: %s", event_name, json.dumps(event_data)) # Get the correlation ID if it exists, otherwise create one cid = locals.get_cid() or str(uuid4()) event_data["cid"] = cid self.dispatch(event_name, event_data)
class Command: name = COMMAND_SERVICE dispatch = EventDispatcher() @event_handler(ORDERS_SERVICE, 'order_status_changed_to_stock_confirmed') def verify_payment(self, payload): """ This service doesn't do much, it's here to complete the flow, it will by default always approve all payment methods. :param payload: :return: """ if isinstance(payload, str): payload = json.loads(payload) order_id = payload['order_id'] payment_succeeded = os.getenv('PAYMENT_SUCCEEDED', True) payload = {'order_id': order_id} if payment_succeeded: self.dispatch('order_payment_succeeded', payload) logger.info( f"{dt.utcnow()}: Payment Succeeded for order_id: {payload['order_id']}" ) else: self.dispatch('order_payment_failed', payload) logger.info( f"{dt.utcnow()}: Payment Declined for order_id: {payload['order_id']}" )
class MarketService: name = "market_service" statsd = init_statsd('simplebank-demo.market', 'statsd') dispatch = EventDispatcher() @event_handler("orders_service", "order_created") @statsd.timer('request_reservation') def place_order(self, payload): print("service {} received: {} ... placing order to exchange".format( self.name, payload)) # place order in stock exchange exchange_resp = self.__place_order_exchange(payload) # event: emit order placed event self.__create_event("order_placed", payload) return json.dumps({'exchange_response': exchange_resp}) @rpc @statsd.timer('create_event') def __create_event(self, event, payload): print("[{}] {} emiting {} event".format(payload, self.name, event)) return self.dispatch(event, payload) @statsd.timer('place_order_stock_exchange') @circuit(failure_threshold=5, expected_exception=ConnectionError) def __place_order_exchange(self, request): print("[{}] {} placing order to stock exchange".format( request, self.name)) response = requests.get('https://jsonplaceholder.typicode.com/posts/1') return json.dumps({ 'code': response.status_code, 'body': response.text })
class Service: name = 'service' db = DatabaseSession(DeclarativeBase) event_dispatcher = EventDispatcher() @rpc def get_pessoa(self, pessoa_id): pessoa = self.db.query(Pessoa)(pessoa_id) if not pessoa: raise Notfound('Pessoa com id {} não encontrada'.format(pessoa_id)) return PessoaSchema().dump(pessoa) @rpc def create_pessoa(self, pessoa): p = Pessoa( nome=pessoa['nome'], endereco=pessoa['endereco'], cpf=pessoa['cpf'] ) self.db.add(p) self.db.commit() p = PessoaSchema().dump(p) self.event_dispatcher('pessoa_criada', { 'pessoa': p, }) return pessoa @rpc def get_dividas(self, pessoa_id): dividas = self.db.query(Divida)(pessoa_id) if not dividas: raise Notfound('Dividas para pessoa com id {} não encontradas'.format(pessoa_id)) return DividaSchema().dump(dividas) @rpc def create_divida(self, divida_nova): divida = Divida( pessoa_id=divida_nova['pessoa_id'], ) self.db.add(divida) self.db.commit() divida = DividaSchema().dump(divida) self.event_dispatcher('divida_criada', { 'divida': divida, }) return divida
class Command: name = 'command_politics' dispatch = EventDispatcher() db = DatabaseSession(Base) @rpc def add_news(self, data): try: version = 1 if data.get('version'): version = (data.get('version') + 1) if data.get('id'): id = data.get('id') else: id = self.db.execute(Sequence('news_id_seq')) news = CommandNewsModel( id=id, version=version, title=data['title'], content=data['content'], author=data['author'], published_at=data.get('published_at'), tags=data['tags'], ) self.db.add(news) self.db.commit() data['id'] = news.id data['version'] = news.version self.dispatch('replicate_db_event', data) return data except Exception as e: self.db.rollback() return e
class EventDispatcher(object): name = "event_dispatcher" dispatch = EventDispatcher() @rpc def send_event(self, payload): self.dispatch(payload.get('type'), payload)
class OrdersService: name = 'orders' db = DatabaseSession(DeclarativeBase) event_dispatcher = EventDispatcher() @rpc def get_order(self, order_id): order = self.db.query(Order).get(order_id) if not order: raise NotFound('Order with id {} not found'.format(order_id)) return OrderSchema().dump(order).data @rpc def create_order(self, order_details): order = Order(order_details=[ OrderDetail(product_id=order_detail['product_id'], price=order_detail['price'], quantity=order_detail['quantity']) for order_detail in order_details ]) self.db.add(order) self.db.commit() order = OrderSchema().dump(order).data self.event_dispatcher('order_created', { 'order': order, }) return order @rpc def update_order(self, order): order_details = { order_details['id']: order_details for order_details in order['order_details'] } order = self.db.query(Order).get(order['id']) for order_detail in order.order_details: order_detail.price = order_details[order_detail.id]['price'] order_detail.quantity = order_details[order_detail.id]['quantity'] self.db.commit() return OrderSchema().dump(order).data @rpc def delete_order(self, order_id): order = self.db.query(OrderDetail).get(order_id) self.db.delete(order) self.db.commit() order = self.db.query(Order).get(order_id) self.db.delete(order) self.db.commit()
class CommandBrands: name = BRANDS_COMMAND_SERVICE dispatch = EventDispatcher() db = DatabaseSession(DeclarativeBase) def fire_replicate_db_event(self, data): """ fires off a replication event, this expose the event-sourcing pattern which will send the record to the query database from the command database """ self.dispatch(REPLICATE_EVENT, data) @rpc def add(self, payload): if isinstance(payload, str): payload = json.loads(payload) name = payload.get('name') item = ProductBrand() item.name = name self.db.add(item) self.db.commit() payload['id'] = item.id payload['updated_at'] = item.updated_at payload['created_at'] = item.created_at self.fire_replicate_db_event(payload) return payload @rpc def update(self, id, payload): brand = self.db.query(ProductBrand).get(id) if brand is None: raise NotFound() brand.name = payload.get('name') brand.updated_at = datetime.datetime.utcnow() self.db.add(brand) self.db.commit() payload['id'] = brand.id payload['created_at'] = brand.created_at payload['updated_at'] = brand.updated_at self.fire_replicate_db_event(payload) return payload @rpc def delete(self, id): product_brand = self.db.query(ProductBrand).get(id) self.db.delete(product_brand) self.db.commit()
class EventPublisherService: name = "publisher_service" dispatch = EventDispatcher() @rpc def publish(self, event_type, payload): self.dispatch(event_type, payload)
class ServiceA: """ Event dispatching service. """ name = "service_a" dispatch = EventDispatcher() @rpc def dispatching_method(self, payload): self.dispatch("event_type", payload)
class TestPublish: name = "publisher" dispatch = EventDispatcher() @rpc def send_message(self, payload): self.dispatch("event", payload)
class Dispatcher(object): name = "dispatch" dispatch = EventDispatcher() @dummy def method(self, payload): return self.dispatch("event-type", payload)
class Service(object): name = "dispatcher" dispatch = EventDispatcher(mandatory=True, use_confirms=False) @dummy def method(self, *args, **kwargs): self.dispatch(*args, **kwargs)
class Service(object): name = "dispatcher" dispatch = EventDispatcher() @dummy def method(self, *args, **kwargs): self.dispatch(*args, **kwargs)
class Listener: name = 'listener_service' dispatcher = EventDispatcher() @listener(queue='queue3') def handle(self, body): logging.info("listener_service listen via entrypoint: {}".format(body)) self.dispatcher("event_type", body.decode('utf-8'))
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config, mock_container): vhost = rabbit_config['vhost'] container = mock_container container.shared_extensions = {} container.service_name = "srcservice" container.config = rabbit_config service = Mock() worker_ctx = WorkerContext(container, service, DummyProvider()) dispatcher = EventDispatcher().bind(container, 'dispatch') dispatcher.setup() dispatcher.start() # we should have an exchange but no queues exchanges = rabbit_manager.get_exchanges(vhost) queues = rabbit_manager.get_queues(vhost) assert "srcservice.events" in [exchange['name'] for exchange in exchanges] assert queues == [] # manually add a queue to capture the events rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True) rabbit_manager.create_queue_binding(vhost, "srcservice.events", "event-sink", routing_key="eventtype") service.dispatch = dispatcher.get_dependency(worker_ctx) service.dispatch("eventtype", "msg") # test event receieved on manually added queue messages = rabbit_manager.get_messages(vhost, "event-sink") assert ['"msg"'] == [msg['payload'] for msg in messages]
class ServiceDispatch: """ Event dispatching service. """ name = "service_dispatch" dispatch = EventDispatcher() @rpc def dispatching_method(self, payload): self.dispatch("load", payload)
class ServiceA: name = "service_a" dispatch = EventDispatcher() @rpc def dispatching_method(self, payload): a = self.dispatch("event_type", payload) print(a)
class GenderService: name = "gender_service" dispatch = EventDispatcher() emotionPublishDataService = RpcProxy("emotion_data_publish_service") classifier = ImageClassifier("models/faces_graph.pb", "models/faces_graphLabels.txt") @rpc def process_gender_detection(self, img_data, clientId): fileinfo = base64.b64decode(img_data[22:]) imgNpArr = np.fromstring(fileinfo, np.ubyte) img_np = cv2.imdecode(imgNpArr, 1) height, width, numberFrames = img_np.shape imageSize = img_np.size img_np.resize(imageSize) nparr = img_np.reshape(height, width, numberFrames) answer, score = self.classifier.classifyImage(nparr, 1) genderResponse = dict() genderResponse['serviceType'] = "Gender" genderResponse['gender'] = answer genderResponse['confidence'] = score genderResponse["userId"] = clientId print(genderResponse) self.emotionPublishDataService.pushEmotionResponseToQueue( genderResponse) MongoDao.write_to_mongo(genderResponse, "gender_collection") @event_handler("image_publish_service", "process_gender") def process_gender(self, properties): img_size = int(properties.get("imgSize")), img_Height = int(properties.get("imgHeight")) img_Width = int(properties.get("imgWidth")) img_noPlanes = int(properties.get("imgNoOfPlanes")) clientId = properties.get("clientId") nparr = np.fromstring(base64.b64decode(properties.get("image")[22:]), np.ubyte) nparr = cv2.imdecode(nparr, 1) nparr.resize(img_size) nparr = nparr.reshape(img_Height, img_Width, img_noPlanes) answer, score = self.classifier.classifyImage(nparr, 1) genderResponse = dict() genderResponse['serviceType'] = "Gender" genderResponse['gender'] = answer genderResponse['confidence'] = score genderResponse["userId"] = clientId print(genderResponse) self.emotionPublishDataService.pushEmotionResponseToQueue( genderResponse) MongoDao.write_to_mongo(genderResponse, "gender_collection")
def test_event_dispatcher(mock_container, mock_producer, rabbit_config): container = mock_container container.config = rabbit_config container.service_name = "srcservice" service = Mock() worker_ctx = WorkerContext(container, service, DummyProvider("dispatch")) custom_retry_policy = {'max_retries': 5} event_dispatcher = EventDispatcher(retry_policy=custom_retry_policy).bind( container, attr_name="dispatch") event_dispatcher.setup() service.dispatch = event_dispatcher.get_dependency(worker_ctx) service.dispatch('eventtype', 'msg') headers = event_dispatcher.get_message_headers(worker_ctx) expected_args = ('msg',) expected_kwargs = { 'exchange': ANY, 'routing_key': 'eventtype', 'headers': headers, 'declare': event_dispatcher.declare, 'retry': event_dispatcher.publisher_cls.retry, 'retry_policy': custom_retry_policy, 'compression': event_dispatcher.publisher_cls.compression, 'mandatory': event_dispatcher.publisher_cls.mandatory, 'expiration': event_dispatcher.publisher_cls.expiration, 'delivery_mode': event_dispatcher.publisher_cls.delivery_mode, 'priority': event_dispatcher.publisher_cls.priority, 'serializer': event_dispatcher.serializer, } assert mock_producer.publish.call_count == 1 args, kwargs = mock_producer.publish.call_args assert args == expected_args assert kwargs == expected_kwargs assert kwargs['exchange'].name == 'srcservice.events'
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config, mock_container): vhost = rabbit_config['vhost'] container = mock_container container.shared_extensions = {} container.service_name = "srcservice" container.config = rabbit_config service = Mock() worker_ctx = WorkerContext(container, service, DummyProvider()) dispatcher = EventDispatcher().bind(container, 'dispatch') dispatcher.setup() dispatcher.start() # we should have an exchange but no queues exchanges = rabbit_manager.get_exchanges(vhost) queues = rabbit_manager.get_queues(vhost) assert "srcservice.events" in [exchange['name'] for exchange in exchanges] assert queues == [] # manually add a queue to capture the events rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True) rabbit_manager.create_queue_binding( vhost, "srcservice.events", "event-sink", routing_key="eventtype") service.dispatch = dispatcher.get_dependency(worker_ctx) service.dispatch("eventtype", "msg") # test event receieved on manually added queue messages = rabbit_manager.get_messages(vhost, "event-sink") assert ['"msg"'] == [msg['payload'] for msg in messages]
def test_headers(self, mock_container, producer): """ Headers can be provided at instantiation time, and are merged with Nameko headers. """ mock_container.config = { 'AMQP_URI': 'memory://localhost' } mock_container.service_name = "service" # use a real worker context so nameko headers are generated service = Mock() entrypoint = Mock(method_name="method") worker_ctx = WorkerContext( mock_container, service, entrypoint, data={'context': 'data'} ) nameko_headers = { 'nameko.context': 'data', 'nameko.call_id_stack': ['service.method.0'], } value = {'foo': Mock()} dispatcher = EventDispatcher( **{'headers': value} ).bind(mock_container, "dispatch") dispatcher.setup() dispatch = dispatcher.get_dependency(worker_ctx) def merge_dicts(base, *updates): merged = base.copy() [merged.update(update) for update in updates] return merged dispatch("event-type", "event-data") assert producer.publish.call_args[1]['headers'] == merge_dicts( nameko_headers, value )
def test_regular_parameters( self, parameter, mock_container, producer ): """ Verify that most parameters can be specified at instantiation time. """ mock_container.config = {'AMQP_URI': 'memory://localhost'} mock_container.service_name = "service" worker_ctx = Mock() worker_ctx.context_data = {} value = Mock() dispatcher = EventDispatcher( **{parameter: value} ).bind(mock_container, "dispatch") dispatcher.setup() dispatch = dispatcher.get_dependency(worker_ctx) dispatch("event-type", "event-data") assert producer.publish.call_args[1][parameter] == value