本文整理匯總了Python中mock.Mock方法的典型用法代碼示例。如果您正苦於以下問題:Python mock.Mock方法的具體用法?Python mock.Mock怎麽用?Python mock.Mock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mock
的用法示例。
在下文中一共展示了mock.Mock方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_calc_route_info_with_ignored
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_calc_route_info_with_ignored(self):
with requests_mock.mock() as m:
lat = [47.49, 47.612, 47.645]
lon = [19.04, 18.99, 18.82]
bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
length = [400, 5000, 500]
time = [40, 300, 50]
address_to_coords_response = [
'[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
'[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
]
m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
route = wrc.WazeRouteCalculator("", "")
route_mock = mock.Mock(return_value={"results": [
{"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
{"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
{"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
]})
route.get_route = route_mock
time, dist = route.calc_route_info(stop_at_bounds=True)
assert route_mock.called
assert time == 5.00
assert dist == 5.00
示例2: test_calc_route_info_with_ignored_and_nort
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_calc_route_info_with_ignored_and_nort(self):
with requests_mock.mock() as m:
lat = [47.49, 47.612, 47.645]
lon = [19.04, 18.99, 18.82]
bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
length = [400, 5000, 500]
time = [40, 360, 60]
nort_time = [40, 300, 50]
address_to_coords_response = [
'[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
'[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
]
m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
route = wrc.WazeRouteCalculator("", "")
route_mock = mock.Mock(return_value={"results": [
{"length": length[0], "crossTime": time[0], "crossTimeWithoutRealTime": nort_time[0], "path": {"x": lon[0], "y": lat[0]}},
{"length": length[1], "crossTime": time[1], "crossTimeWithoutRealTime": nort_time[1], "path": {"x": lon[1], "y": lat[1]}},
{"length": length[2], "crossTime": time[2], "crossTimeWithoutRealTime": nort_time[2], "path": {"x": lon[2], "y": lat[2]}}
]})
route.get_route = route_mock
time, dist = route.calc_route_info(stop_at_bounds=True, real_time=False)
assert route_mock.called
assert time == 5.00
assert dist == 5.00
示例3: test_calc_route_info_stopatbounds_missing_bounds
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_calc_route_info_stopatbounds_missing_bounds(self):
with requests_mock.mock() as m:
lat = [47.49, 47.612, 47.645]
lon = [19.04, 18.99, 18.82]
bounds = [None, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
length = [400, 5000, 500]
time = [45, 300, 60]
address_to_coords_response = [
'[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":null}]' % (lat[0], lon[0]),
'[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
]
m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
route = wrc.WazeRouteCalculator("", "")
route_mock = mock.Mock(return_value={"results": [
{"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
{"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
{"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
]})
route.get_route = route_mock
time, dist = route.calc_route_info(stop_at_bounds=True)
assert route_mock.called
assert time == 5.75
assert dist == 5.40
示例4: mock_requestsGithub
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def mock_requestsGithub(uri, headers={}, params={}):
if uri.endswith('contents'):
return_value = Mock(ok=True)
return_value.json.return_value = mock_files
return return_value
else:
targetFile = uri.replace('https://raw.githubusercontent.com/fakeuser/fakerepo/master/', path.join(base_url, ''))
if path.exists(targetFile):
f = open(targetFile, 'r')
lines = f.readlines()
text = ''.join(lines)
return_value = Mock(status_code=200)
return_value.text = text
return return_value
else:
return_value = Mock(status_code=404)
return return_value
示例5: test_get_enumeration
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_get_enumeration(self, mock_get):
mock_get.return_value = Mock(ok=True)
mock_get.return_value.json.return_value = {
'results': {
'bindings': [
{'o1': {'value': 'v1'}},
{'o1': {'value': 'v2'}}
]
}
}
rq, _ = self.loader.getTextForName('test-rq')
metadata = {'enumerate': 'o1'}
enumeration = gquery.get_enumeration(rq, 'o1', 'http://mock-endpoint/sparql', metadata)
self.assertIsInstance(enumeration, list, 'Should return a list of values')
self.assertEqual(len(enumeration), 2, 'Should have two elements')
示例6: test_interactor_error_caught
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_interactor_error_caught(
self, container, interactor_function, error_handler, request_data, validators):
error_instance = LogicError('foo')
interactor_mock = mock.Mock(side_effect=error_instance)
interactor = interactor_function(*validators)(interactor_mock)(container)
interactor(request_data)
validators[0].assert_called_once_with(request_data)
validators[1].assert_called_once_with(request_data)
interactor_mock.assert_called_once_with(request_data)
error_handler.assert_called_once_with(
error=error_instance,
function_name='mock.mock.validated_by.<locals>.decorator.<locals>.decorated',
args=(request_data,),
kwargs={}
)
示例7: test_multiple_error_class
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_multiple_error_class(
self, container, error_handler, request_data, validators):
error_instance = ValueError()
interactor_mock = mock.Mock(side_effect=error_instance)
interactor_function = interactor_factory(
error_class=(LogicError, ValueError),
error_handler=error_handler
)
interactor = interactor_function(*validators)(interactor_mock)(container)
interactor(request_data)
validators[0].assert_called_once_with(request_data)
validators[1].assert_called_once_with(request_data)
interactor_mock.assert_called_once_with(request_data)
error_handler.assert_called_once_with(
error=error_instance,
function_name='mock.mock.validated_by.<locals>.decorator.<locals>.decorated',
args=(request_data,),
kwargs={}
)
示例8: test_injectable_function
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_injectable_function(self, container, context):
mock_dependency = mock.Mock()
container.register_by_name("dependency", lambda *args: mock_dependency)
@container_supplier
@inject
def f(dependency=Inject(name="dependency"), **kwargs):
# noinspection PyCallingNonCallable
dependency(**kwargs)
return 42
f_closure = f(container, context)
result = f_closure(foo='bar')
mock_dependency.assert_called_once_with(foo='bar')
assert result == 42
示例9: test_api_call
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_api_call(m_http_lib, client):
get_request_mock = Mock(return_value={
'access_token': '1234', 'expires_in': 1000, 'scope': '1'
})
request_mock = Mock(get=get_request_mock)
m_http_lib.return_value = request_mock
args = (1, 2, 3)
kwargs = {'a': 1, 'b': 2}
client._api_call('get', '/test', *args, **kwargs)
get_request_mock.assert_called_with(*(('/test',) + args), **kwargs)
assert client.API_CALLS_MADE == 1
limit = 4
client = MarketoClient('123-FDY-456', 'randomclientid', 'supersecret', limit)
with pytest.raises(Exception) as excinfo:
for i in xrange(limit):
client._api_call('get', '/test', *args, **kwargs)
assert excinfo.value == {
'message': 'API Calls exceeded the limit : %s' % limit,
'code': '416'
}
示例10: test_build_default_mask_rcnn_box_predictor
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_build_default_mask_rcnn_box_predictor(self):
box_predictor_proto = box_predictor_pb2.BoxPredictor()
box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = (
hyperparams_pb2.Hyperparams.FC)
box_predictor = box_predictor_builder.build(
argscope_fn=mock.Mock(return_value='arg_scope'),
box_predictor_config=box_predictor_proto,
is_training=True,
num_classes=90)
self.assertFalse(box_predictor._use_dropout)
self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.5)
self.assertEqual(box_predictor.num_classes, 90)
self.assertTrue(box_predictor._is_training)
self.assertEqual(box_predictor._box_code_size, 4)
self.assertFalse(box_predictor._predict_instance_masks)
self.assertFalse(box_predictor._predict_keypoints)
示例11: test_voice_recording_view
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_voice_recording_view(self):
http_client = Mock()
http_client.request.return_value = '{"data":[{"id":"12345678-9012-3456-7890-123456789012","format":"wav","legId":"87654321-0987-6543-2109-876543210987","status":"done","duration":32,"type":"transfer","createdAt":"2018-01-01T00:00:01Z","updatedAt":"2018-01-01T00:00:05Z","deletedAt":null}],"_links":{"file":"/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012.wav","self":"/calls/12345678-9012-3456-7890-123456789012/legs/12348765-4321-0987-6543-210987654321/recordings/12345678-9012-3456-7890-123456789012"},"pagination":{"totalCount":0,"pageCount":0,"currentPage":0,"perPage":0}}'
voice_recording = Client('', http_client).voice_recording_view(
'12348765-4321-0987-6543-210987654321',
'87654321-0987-6543-2109-876543210987',
'12345678-9012-3456-7890-123456789012'
)
http_client.request.assert_called_once_with(
'https://voice.messagebird.com/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012',
'GET', None)
self.assertEqual('12345678-9012-3456-7890-123456789012', voice_recording.id)
self.assertEqual('done', voice_recording.status)
self.assertEqual('wav', voice_recording.format)
self.assertEqual(datetime(2018, 1, 1, 0, 0, 1, tzinfo=tzutc()), voice_recording.createdAt)
self.assertEqual(datetime(2018, 1, 1, 0, 0, 5, tzinfo=tzutc()), voice_recording.updatedAt)
self.assertEqual(2, len(voice_recording._links))
self.assertIsInstance(str(voice_recording), str)
示例12: test_create_message
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_create_message(self):
http_client = Mock()
http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}'
data = {
'channelId': 1234,
'type': 'text',
'content': {
'text': 'this is a message'
},
}
msg = Client('', http_client).conversation_create_message('conversation-id', data)
self.assertEqual(datetime(2019, 4, 2, 11, 57, 53, tzinfo=tzutc()), msg.updatedDatetime)
self.assertEqual(datetime(2019, 4, 2, 11, 57, 52, tzinfo=tzutc()), msg.createdDatetime)
http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data)
示例13: test_voice_create_webhook
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_voice_create_webhook(self):
http_client = Mock()
http_client.request.return_value = '''{
"data": [
{
"id": "534e1848-235f-482d-983d-e3e11a04f58a",
"url": "https://example.com/",
"token": "foobar",
"createdAt": "2017-03-15T14:10:07Z",
"updatedAt": "2017-03-15T14:10:07Z"
}
],
"_links": {
"self": "/webhooks/534e1848-235f-482d-983d-e3e11a04f58a"
}
}'''
create_webhook_request = VoiceCreateWebhookRequest(url="https://example.com/", title="FooBar", token="foobar")
created_webhook = Client('', http_client).voice_create_webhook(create_webhook_request)
http_client.request.assert_called_once_with(VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH, 'POST',
create_webhook_request.__dict__())
self.assertEqual(create_webhook_request.url, created_webhook.url)
self.assertEqual(create_webhook_request.token, created_webhook.token)
示例14: test_voice_update_webhook
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_voice_update_webhook(self):
http_client = Mock()
http_client.request.return_value = '''{
"data": [
{
"id": "534e1848-235f-482d-983d-e3e11a04f58a",
"url": "https://example.com/baz",
"token": "foobar",
"createdAt": "2017-03-15T13:27:02Z",
"updatedAt": "2017-03-15T13:28:01Z"
}
],
"_links": {
"self": "/webhooks/534e1848-235f-482d-983d-e3e11a04f58a"
}
}'''
webhook_id = '534e1848-235f-482d-983d-e3e11a04f58a'
update_webhook_request = VoiceUpdateWebhookRequest(title="FooBar", token="foobar")
updated_webhook = Client('', http_client).voice_update_webhook(webhook_id, update_webhook_request)
http_client.request.assert_called_once_with(
VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '/' + webhook_id, 'PUT', update_webhook_request.__dict__())
self.assertEqual(update_webhook_request.token, updated_webhook.token)
示例15: test_voicemessages_list
# 需要導入模塊: import mock [as 別名]
# 或者: from mock import Mock [as 別名]
def test_voicemessages_list(self):
http_client = Mock()
http_client.request.return_value = '{ "offset": 0, "limit": 10, "count": 2, "totalCount": 2, "links": { "first": "https://rest.messagebird.com/voicemessages/?offset=0&limit=30", "previous": null, "next": null, "last": "https://rest.messagebird.com/voicemessages/?offset=0&limit=30" }, "items": [ { "id": "12345678-9012-3456-7890-123456789012", "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789012", "originator": null, "body": "This is a test message.", "reference": null, "language": "en-gb", "voice": "male", "repeat": 1, "ifMachine": "continue", "machineTimeout": 7000, "scheduledDatetime": null, "createdDatetime": "2020-02-04T15:15:30+00:00", "recipients": { "totalCount": 1, "totalSentCount": 1, "totalDeliveredCount": 1, "totalDeliveryFailedCount": 0, "items": [ { "recipient": 31612345678, "originator": null, "status": "answered", "statusDatetime": "2020-02-04T15:15:57+00:00" } ] } }, { "id": "12345678-9012-3456-7890-123456789013", "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789013", "originator": null, "body": "The voice message to be sent", "reference": null, "language": "en-gb", "voice": "female", "repeat": 1, "ifMachine": "delay", "machineTimeout": 7000, "scheduledDatetime": null, "createdDatetime": "2020-02-04T12:26:44+00:00", "recipients": { "totalCount": 1, "totalSentCount": 1, "totalDeliveredCount": 1, "totalDeliveryFailedCount": 0, "items": [ { "recipient": 31612345678, "originator": null, "status": "answered", "statusDatetime": "2020-02-04T12:27:32+00:00" } ] } } ] }'
voice_messages = Client('', http_client).voice_message_list()
http_client.request.assert_called_once_with(
'voicemessages?limit=10&offset=0', 'GET', None)
voice_messages_check = {
'12345678-9012-3456-7890-123456789012': {
"id": '12345678-9012-3456-7890-123456789012',
"href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789012"
},
'12345678-9012-3456-7890-123456789013': {
"id": '12345678-9012-3456-7890-123456789013',
"href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789013"
}
}
for item in voice_messages.items:
message_specific = voice_messages_check.get(item.id)
self.assertEqual(message_specific['id'], item.id)
self.assertEqual(message_specific['href'], item.href)
self.assertIsInstance(str(voice_messages), str)