本文整理汇总了Python中mock.MagicMock.body方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.body方法的具体用法?Python MagicMock.body怎么用?Python MagicMock.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.body方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_format
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_format(self):
req = MagicMock()
resp = MagicMock()
resp.body = {"example": "JSON"}
resp.content_type = None
hook_format(req, resp)
resp.body = '{"example": "JSON"}'
resp.content_type = 'application/json'
示例2: test_parseRequestBody
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_parseRequestBody(self):
req = MagicMock()
req.body = '{"key":"value"}'
data = self.rest_app._parseRequestBody(req)
self.assertEqual(data, {'key': 'value'})
self.assertEqual(data.keys(), ['key'])
self.assertEqual(type(data.keys()[0]), str)
# test some bad data
req.body = '{aaaaaaa}'
self.assertRaises(HTTPBadRequest, self.rest_app._parseRequestBody, req)
示例3: remove_public_id
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def remove_public_id(self, last_public_id, original_id, HTTPCallbackGroup,
get_associated_privates,
get_associated_publics,
_delete_number):
# Setup
HTTPCallbackGroup.return_value = MagicMock()
on_success_handler = MagicMock()
on_failure_handler = MagicMock()
self.handler.forward_error = MagicMock()
if original_id:
sip_uri = SIP_URI
else:
sip_uri = SIP_URI2
# Test
numbers.remove_public_id(self.db_sess,
sip_uri,
on_success_handler,
on_failure_handler,
False)
# Asserts
get_associated_privates.assert_called_once_with(sip_uri, ANY)
HTTPCallbackGroup.assert_called_once_with(ANY, ANY)
# Extract inner function and can call it with response
on_get_privates_success = HTTPCallbackGroup.call_args[0][0]
response = MagicMock()
response.body = '{"public_id": "%s", "private_ids": ["%s"]}' % (sip_uri, PRIVATE_ID)
on_get_privates_success([response])
# Response should have been parsed now and a new call invoked
get_associated_publics.assert_called_once_with(PRIVATE_ID, ANY)
on_get_publics_success = HTTPCallbackGroup.call_args[0][0]
response = MagicMock()
if last_public_id:
response.body = '{"associated_public_ids": ["%s"]}' % (sip_uri)
else:
response.body = '{"associated_public_ids": ["[email protected]", "%s"]}' % (sip_uri)
on_get_publics_success([response])
if original_id and not last_public_id:
# When deleting the originally created public identity we want the request to fail
# if other public identities are associated with the private id
on_failure_handler.assert_called_once_with(response)
else:
_delete_number.assert_called_once_with(self.db_sess,
sip_uri,
PRIVATE_ID,
last_public_id,
on_success_handler,
on_failure_handler,
False)
示例4: _setup
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def _setup():
global reconnect_handler, session_manager, session_list, path, kernel_id, kernel_manager,\
individual_kernel_manager, response_id, good_msg, client, spark_events, request
# Mock kernel manager
client = MagicMock()
client.execute = MagicMock(return_value=response_id)
client.get_shell_msg = MagicMock(return_value=good_msg)
individual_kernel_manager = MagicMock()
individual_kernel_manager.client = MagicMock(return_value=client)
kernel_manager = MagicMock()
kernel_manager.get_kernel = MagicMock(return_value=individual_kernel_manager)
# Mock session manager
session_list = [create_session_dict(path, kernel_id)]
session_manager = MagicMock()
session_manager.list_sessions = MagicMock(return_value=session_list)
# Mock spark events
spark_events = MagicMock()
# Mock request
request = MagicMock()
request.body = json.dumps({"path": path, "username": username, "password": password, "endpoint": endpoint})
# Create mocked reconnect_handler
ReconnectHandler.__bases__ = (SimpleObject,)
reconnect_handler = ReconnectHandler()
reconnect_handler.spark_events = spark_events
reconnect_handler.session_manager = session_manager
reconnect_handler.kernel_manager = kernel_manager
reconnect_handler.set_status = MagicMock()
reconnect_handler.finish = MagicMock()
reconnect_handler.current_user = 'alex'
reconnect_handler.request = request
示例5: test_get_one_number
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_get_one_number(self, get_numbers,
HTTPCallbackGroup,
get_associated_privates):
self.handler.get_and_check_user_id = MagicMock(return_value=USER_ID)
get_numbers.return_value = [{"number": SIP_URI, "number_id": NUMBER_ID, "gab_listed": GAB_LISTED}]
HTTPCallbackGroup.return_value = MagicMock()
self.handler.get("foobar")
# Assert that we kick off asynchronous GET at homestead
self.handler.get_and_check_user_id.assert_called_once_with("foobar")
HTTPCallbackGroup.assert_called_once_with(ANY, # functools.partial object
self.handler._on_get_failure)
get_associated_privates.assert_called_once_with(SIP_URI,
ANY # function
# argument
)
# Simulate success of all requests.
response = MagicMock()
response.body = '{"private_ids": ["[email protected]"]}'
self.handler._on_get_success(SIP_URI, [response])
self.handler.finish.assert_called_once_with(
{
"numbers": [
{"number_id": NUMBER_ID_HEX,
"number": "5555550123",
"sip_username": "5555550123",
"domain": REALM,
"gab_listed": GAB_LISTED,
"formatted_number": "(555) 555-0123",
"sip_uri": SIP_URI,
"private_id": "[email protected]", }
]
})
示例6: test_ping_fail
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_ping_fail(self, settings, AsyncHTTPClient):
self.standard_setup(settings, AsyncHTTPClient)
homestead.ping()
self.mock_httpclient.fetch.assert_called_once_with("http://homestead/ping", ANY)
mock_response = MagicMock()
mock_response.body = "Failure"
self.mock_httpclient.fetch.call_args[0][1](mock_response)
示例7: test__validate_body_empty_body
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test__validate_body_empty_body():
request = MagicMock()
request.body = ''
with pytest.raises(exceptions.HTTPError) as exc:
_validate_body(request)
assert exc.value.status_code == 400
assert exc.value.errors == 'Body is empty string'
示例8: TestCommandParsing
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def TestCommandParsing(self):
request = MagicMock()
request.path = "/test"
request.query = "item1=value1"
request.remote_ip = "1.2.3.4"
request.method = "PUT"
request.headers = {
'User': 'test_user',
'Creation-Time': 'test_time',
'User-Agent': 'test_user_agent'
}
request.body="item2=value2&item2=value3&item2=value4"
self.command = Command(request)
self.assertEqual(self.command.command_name, 'test')
self.assertEqual(self.command.command_type, 'PUT')
self.assertEqual(self.command.has_param('item1'), True)
self.assertEqual(self.command.has_param('item2'), True)
self.assertEqual(self.command.has_param('item3'), False)
self.assertEqual(self.command.get_param('item1'), 'value1')
self.assertEqual('value2' in self.command.get_param('item2'), True)
self.assertEqual('value3' in self.command.get_param('item2'), True)
self.assertEqual('value4' in self.command.get_param('item2'), True)
data = self.command.format_trace
self.assertEqual(data['Username'], 'test_user')
self.assertEqual(data['Created'], 'test_time')
self.assertEqual(data['Source_Address'], '1.2.3.4')
self.assertEqual(data['Source_ID'], 'test_user_agent')
示例9: test__validate_body_no_body
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test__validate_body_no_body():
request = MagicMock()
request.body = None
with pytest.raises(exceptions.HTTPError) as exc:
_validate_body(request)
assert exc.value.status_code == 400
assert exc.value.errors == 'No Data in Body'
示例10: testHandleBatchSingle
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def testHandleBatchSingle(self, mockEngine, addMetricMock):
# Create mocks
metric_storer.gCustomMetrics = {}
metricMock = MagicMock()
def addMetricSideEffect(*_args, **_kwargs):
metric_storer.gCustomMetrics["test.metric"] = [metricMock, datetime.datetime.utcnow()]
addMetricMock.side_effect = addMetricSideEffect
modelSwapperMock = MagicMock()
metricStreamerMock = MagicMock()
body = '{"protocol": "plain", "data": ["test.metric 4.0 1386792175"]}'
message = MagicMock()
message.body = body
# Call the function under test
metric_storer._handleBatch(mockEngine, [message], [], metricStreamerMock, modelSwapperMock)
# Check the results
addMetricMock.assert_called_once_with(mockEngine, "test.metric")
metricStreamerMock.streamMetricData.assert_called_once()
data, _uid, modelSwapper = metricStreamerMock.streamMetricData.call_args[0]
self.assertIs(modelSwapper, modelSwapperMock)
self.assertEqual(len(data), 1)
self.assertEqual(len(data[0]), 2)
self.assertEqual(repr(data[0][0]), "datetime.datetime(2013, 12, 11, 20, 2, 55)")
self.assertAlmostEqual(data[0][1], 4.0)
示例11: test_ping_http
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_ping_http(self, settings, AsyncHTTPClient):
self.standard_setup(settings, AsyncHTTPClient)
mock_response = MagicMock()
mock_response.body = "OK"
self.mock_httpclient.fetch.return_value = mock_response
homestead.ping()
self.mock_httpclient.fetch.assert_called_once_with("http://homestead/ping", ANY)
示例12: get_two_numbers
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def get_two_numbers(self, shared_private_id, get_numbers,
HTTPCallbackGroup,
get_associated_privates):
self.handler.get_and_check_user_id = MagicMock(return_value=USER_ID)
get_numbers.return_value = [{"number": "sip:[email protected]", "number_id": NUMBER_ID, "gab_listed": 0},
{"number": "sip:[email protected]", "number_id": NUMBER_ID2, "gab_listed": 1}]
HTTPCallbackGroup.return_value = MagicMock()
self.handler.get("foobar")
# Simulate success of all requests.
response1 = MagicMock()
response1.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
response2 = MagicMock()
if shared_private_id:
response2.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
else:
response2.body = '{"public_id": "sip:[email protected]", "private_ids": ["[email protected]"]}'
self.handler._on_get_success("sip:[email protected]", [response1])
self.handler._on_get_success("sip:[email protected]", [response2])
self.handler.finish.assert_called_once_with(
{
"numbers": [
{
"number_id": NUMBER_ID_HEX,
"number": "4155551234",
"sip_username": "4155551234",
"domain": "sip.com",
"gab_listed": 0,
"formatted_number": "(415) 555-1234",
"sip_uri": "sip:[email protected]",
"private_id": "[email protected]",
},
{
"number_id": NUMBER_ID2_HEX,
"number": "4155555678",
"sip_username": "4155555678",
"domain": "sip.com",
"gab_listed": 1,
"formatted_number": "(415) 555-5678",
"sip_uri": "sip:[email protected]",
"private_id": (shared_private_id and "[email protected]" or "[email protected]"),
}
]
})
示例13: testHandleDataInvalidProtocol
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def testHandleDataInvalidProtocol(self, mockEngine, loggingMock):
"""Ensure _handleData doesn't throw an exception for unknown protocol."""
# Call the function under test
body = '{"protocol": "unknown_protocol",' ' "data": ["test.metric 4.0 1386792175"]}'
message = MagicMock()
message.body = body
metric_storer._handleBatch(mockEngine, [message], [], MagicMock(), MagicMock())
# Check the results
self.assertTrue(loggingMock.warn.called)
示例14: test_process_data
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def test_process_data(self):
"""
CoinbaseProvider.process_data() returns a correct HTTP response
"""
request = MagicMock()
request.body = json.dumps(COINBASE_REQUEST)
response = self.provider.process_data(self.payment, request)
self.assertEqual(type(response), HttpResponse)
self.assertEqual(self.payment.status, "confirmed")
示例15: phonable_task
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import body [as 别名]
def phonable_task(func, url):
number = '+12103004000' if url.endswith('abc') else '+13103004000'
reply = MagicMock()
reply.code = 200
reply.body = json.dumps({"number": number})
task = MagicMock(spec=YieldPoint)
task.get_result.return_value = reply
return task