本文整理汇总了Python中mock.Mock.config方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.config方法的具体用法?Python Mock.config怎么用?Python Mock.config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_publish_to_queue
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_publish_to_queue(empty_config, maybe_declare, patch_publisher):
container = Mock(spec=ServiceContainer)
container.shared_extensions = {}
container.service_name = "srcservice"
container.config = empty_config
ctx_data = {"language": "en"}
service = Mock()
worker_ctx = WorkerContext(container, service, DummyProvider("publish"), data=ctx_data)
publisher = Publisher(queue=foobar_queue).bind(container, "publish")
producer = Mock()
connection = Mock()
get_connection, get_producer = patch_publisher(publisher)
get_connection.return_value = as_context_manager(connection)
get_producer.return_value = as_context_manager(producer)
# test declarations
publisher.setup()
maybe_declare.assert_called_once_with(foobar_queue, connection)
# test publish
msg = "msg"
headers = {"nameko.language": "en", "nameko.call_id_stack": ["srcservice.publish.0"]}
service.publish = publisher.get_dependency(worker_ctx)
service.publish(msg, publish_kwarg="value")
producer.publish.assert_called_once_with(
msg, headers=headers, exchange=foobar_ex, retry=True, retry_policy=DEFAULT_RETRY_POLICY, publish_kwarg="value"
)
示例2: test_responder_worker_exc
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_responder_worker_exc(mock_publish):
message = Mock()
message.properties = {"reply_to": ""}
container = Mock()
container.config = {AMQP_URI_CONFIG_KEY: ""}
responder = Responder(message)
# serialisable exception
worker_exc = Exception("error")
result, exc_info = responder.send_response(container, None, (Exception, worker_exc, "tb"))
assert result is None
assert exc_info == (Exception, worker_exc, "tb")
expected_msg = {
"result": None,
"error": {
"exc_path": "exceptions.Exception",
"value": "error",
"exc_type": "Exception",
"exc_args": ("error",),
},
}
(msg,), _ = mock_publish.call_args
assert msg == expected_msg
示例3: test_responder_unserializable_exc
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_responder_unserializable_exc(mock_publish):
message = Mock()
message.properties = {"reply_to": ""}
container = Mock()
container.config = {AMQP_URI_CONFIG_KEY: ""}
responder = Responder(message)
# unserialisable exception
worker_exc = Exception(object())
result, exc_info = responder.send_response(container, True, (Exception, worker_exc, "tb"))
# responder will return the TypeError from json.dumps
assert result is None
assert exc_info == (TypeError, ANY, ANY)
assert exc_info[1].message == ("{} is not JSON " "serializable".format(worker_exc.args[0]))
# and publish a dictionary-serialized UnserializableValueError
# (where the unserialisable value is a dictionary-serialized worker_exc)
serialized_exc = serialize(worker_exc)
expected_msg = {
"result": None,
"error": {
"exc_path": "nameko.exceptions.UnserializableValueError",
"value": "Unserializable value: `{}`".format(serialized_exc),
"exc_type": "UnserializableValueError",
"exc_args": (),
},
}
(msg,), _ = mock_publish.call_args
assert msg == expected_msg
示例4: test_dispatch_to_rabbit
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
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]
示例5: test_publish_to_exchange
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_publish_to_exchange(empty_config, maybe_declare, patch_publisher):
container = Mock(spec=ServiceContainer)
container.service_name = "srcservice"
container.config = empty_config
service = Mock()
worker_ctx = WorkerContext(container, service, DummyProvider("publish"))
publisher = PublishProvider(exchange=foobar_ex)
publisher.bind("publish", container)
producer = Mock()
connection = Mock()
get_connection, get_producer = patch_publisher(publisher)
get_connection.return_value = as_context_manager(connection)
get_producer.return_value = as_context_manager(producer)
# test declarations
publisher.prepare()
maybe_declare.assert_called_once_with(foobar_ex, connection)
# test publish
msg = "msg"
publisher.inject(worker_ctx)
service.publish(msg, publish_kwarg="value")
headers = {
'nameko.call_id_stack': ['srcservice.publish.0']
}
producer.publish.assert_called_once_with(
msg, headers=headers, exchange=foobar_ex, retry=True,
retry_policy=DEFAULT_RETRY_POLICY, publish_kwarg="value")
示例6: test_event_dispatcher
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
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)
示例7: test_get_vm_uuid_not_vm
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_get_vm_uuid_not_vm(self):
vm = Mock()
vm.config = Mock()
vm.config.uuid = 'this is the uuid'
self.pv_service.find_vm_by_name = Mock(return_value=vm)
self.assertRaises(ValueError, self.vm_loader.load_vm_uuid_by_name, self.si, self.vc_model, 'path')
示例8: test_update_cluster_with_same_discovery
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_update_cluster_with_same_discovery(self):
riak_discovery = Mock()
riak_discovery.name = "riak"
dns_discovery = Mock()
dns_discovery.name = "dns"
cluster = Mock()
cluster.name = "app"
cluster.discovery = "riak"
cluster.config = {"discovery": "riak"}
writer = Writer("/etc/configs")
writer.add_configurable(Cluster, "app", cluster)
writer.add_configurable(Discovery, "riak", riak_discovery)
writer.add_configurable(Discovery, "dns", dns_discovery)
writer.update_configurable(
Cluster, cluster.name, {"discovery": "riak"}
)
self.assertEqual(writer.nodes_updated.is_set(), True)
self.assertEqual(riak_discovery.stop_watching.called, False)
self.assertEqual(dns_discovery.start_watching.called, False)
示例9: test_unserialisable_headers
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_unserialisable_headers(rabbit_manager, rabbit_config):
vhost = rabbit_config["vhost"]
container = Mock(spec=ServiceContainer)
container.service_name = "service"
container.config = rabbit_config
container.spawn_managed_thread = eventlet.spawn
ctx_data = {"language": "en", "customheader": None}
service = Mock()
worker_ctx = CustomWorkerContext(container, service, DummyProvider("method"), data=ctx_data)
publisher = Publisher(exchange=foobar_ex, queue=foobar_queue).bind(container, "publish")
publisher.setup()
publisher.start()
service.publish = publisher.get_dependency(worker_ctx)
service.publish("msg")
messages = rabbit_manager.get_messages(vhost, foobar_queue.name)
assert messages[0]["properties"]["headers"] == {
"nameko.language": "en",
"nameko.call_id_stack": ["service.method.0"],
# no `customheader`
}
示例10: sagemaker_session
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def sagemaker_session():
boto_mock = Mock(name='boto_session', region_name=REGION)
sms = Mock(name='sagemaker_session', boto_session=boto_mock)
sms.boto_region_name = REGION
sms.default_bucket = Mock(name='default_bucket', return_value=BUCKET_NAME)
sms.config = None
return sms
示例11: test_consume_from_rabbit
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_consume_from_rabbit(rabbit_manager, rabbit_config):
vhost = rabbit_config['vhost']
container = Mock(spec=ServiceContainer)
container.worker_ctx_cls = CustomWorkerContext
container.service_name = "service"
container.config = rabbit_config
container.max_workers = 10
def spawn_thread(method, protected):
return eventlet.spawn(method)
container.spawn_managed_thread = spawn_thread
worker_ctx = CustomWorkerContext(container, None, None)
factory = DependencyFactory(
ConsumeProvider, queue=foobar_queue, requeue_on_error=False)
consumer = factory.create_and_bind_instance("injection_name", container)
# prepare and start dependencies
consumer.prepare()
consumer.queue_consumer.prepare()
consumer.start()
consumer.queue_consumer.start()
# test queue, exchange and binding created in rabbit
exchanges = rabbit_manager.get_exchanges(vhost)
queues = rabbit_manager.get_queues(vhost)
bindings = rabbit_manager.get_queue_bindings(vhost, foobar_queue.name)
assert "foobar_ex" in [exchange['name'] for exchange in exchanges]
assert "foobar_queue" in [queue['name'] for queue in queues]
assert "foobar_ex" in [binding['source'] for binding in bindings]
# test message consumed from queue
container.spawn_worker.return_value = worker_ctx
headers = {'nameko.language': 'en', 'nameko.customheader': 'customvalue'}
rabbit_manager.publish(
vhost, foobar_ex.name, '', 'msg', properties=dict(headers=headers))
ctx_data = {
'language': 'en',
'customheader': 'customvalue',
}
with wait_for_call(CONSUME_TIMEOUT, container.spawn_worker) as method:
method.assert_called_once_with(
consumer, ('msg', ), {},
context_data=ctx_data,
handle_result=ANY_PARTIAL)
handle_result = method.call_args[1]['handle_result']
# ack message
handle_result(worker_ctx, 'result')
# stop will hang if the consumer hasn't acked or requeued messages
with eventlet.timeout.Timeout(CONSUME_TIMEOUT):
consumer.stop()
示例12: test_nova_responder
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_nova_responder(mock_publish):
container = Mock()
container.config = {AMQP_URI_CONFIG_KEY: ''}
responder = NovaResponder("msgid")
# serialisable result
result, exc_info = responder.send_response(container, True, None)
assert result is True
assert exc_info is None
assert mock_publish.call_count == 2
data_call, marker_call = mock_publish.call_args_list
(data_msg,), _ = data_call
(marker_msg,), _ = marker_call
assert data_msg == {
'failure': None,
'result': True,
'ending': False
}
assert marker_msg == {
'failure': None,
'result': None,
'ending': True
}
示例13: test_nova_responder_cannot_str_exc
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_nova_responder_cannot_str_exc(mock_publish):
container = Mock()
container.config = {AMQP_URI_CONFIG_KEY: ''}
responder = NovaResponder("msgid")
class BadException(Exception):
def __str__(self):
raise Exception('boom')
# un-str-able exception
exc = BadException()
result, exc_info = responder.send_response(
container, True, (BadException, exc, "tb"))
assert result is True
assert exc_info == (BadException, exc, "tb")
assert mock_publish.call_count == 2
data_call, _ = mock_publish.call_args_list
(data_msg,), _ = data_call
assert data_msg == {
'failure': ('BadException', "[__str__ failed]"),
'result': True,
'ending': False
}
示例14: test_vm_get_network_by_name_1
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_vm_get_network_by_name_1(self):
# Arrange
pv_service = pyVmomiService(None, None, Mock())
pv_service.wait_for_task = Mock()
network = Mock()
network.name = 'main_network'
backing = Mock()
backing.network = network
virtual_card = create_autospec(vim.vm.device.VirtualEthernetCard)
virtual_card.macAddress = 'AA-BB'
virtual_card.backing = backing
hardware = Mock()
hardware.device = [virtual_card]
config = Mock()
config.hardware = hardware
vm = Mock()
vm.config = config
# Act
actual_network = pv_service.get_network_by_mac_address(vm, 'BB-CC')
# Assert
self.assertIsNone(actual_network)
示例15: test_reconnect_on_socket_error
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import config [as 别名]
def test_reconnect_on_socket_error(rabbit_config):
container = Mock(spec=ServiceContainer)
container.shared_extensions = {}
container.config = rabbit_config
container.max_workers = 1
container.spawn_managed_thread = spawn_thread
connection_revived = Mock()
queue_consumer = QueueConsumer().bind(container)
queue_consumer.setup()
queue_consumer.on_connection_revived = connection_revived
handler = MessageHandler()
queue_consumer.register_provider(handler)
queue_consumer.start()
with patch.object(
Connection, 'drain_events', autospec=True) as drain_events:
drain_events.side_effect = socket.error('test-error')
def check_reconnected():
assert connection_revived.call_count > 1
assert_stops_raising(check_reconnected)
queue_consumer.unregister_provider(handler)
queue_consumer.stop()