本文整理汇总了Python中mock.MagicMock.json方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.json方法的具体用法?Python MagicMock.json怎么用?Python MagicMock.json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_mock_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def create_mock_response(url, response_type, **kwargs):
response = MagicMock()
response.request.url = url
response.request.method = kwargs.get("method", "GET")
response.request.headers = {}
response.request.body = None
if response_type == "redirect":
response.status_code = 301
response.headers = {"location": kwargs["location"]}
elif response_type == "error":
response.status_code = kwargs.get("status_code", 500)
response.reason = kwargs.get("reason", "fake reason")
response.text = '{{"reason":"{}"}}'.format(kwargs.get("reason", "fake reason"))
response.json = lambda: json.loads(response.text)
elif response_type == "stream":
response.status_code = kwargs.get("status_code", 200)
response.headers = {
"content-disposition": 'attachment; filename="fname.ext"',
"content-type": "application/octet-stream",
"content-length": len(response.text),
}
response.iter_content = lambda buffer_size: IterateContents(
kwargs["contents"], kwargs["buffer_size"], kwargs.get("partial_start", 0), kwargs.get("partial_end", None)
)
else:
response.status_code = 200
response.text = kwargs["text"]
response.json = lambda: json.loads(response.text)
response.headers = {"content-type": "application/json", "content-length": len(response.text)}
return response
示例2: test_handle_request_invalid_json_request
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_handle_request_invalid_json_request(self):
json = JSON()
request = MagicMock()
request.json = json_lib.dumps({'id': 0, 'params': []})
self.assertRaises(JSONException, json._handle_request, request)
request.json = json_lib.dumps({'method': 'some.method', 'params': []})
self.assertRaises(JSONException, json._handle_request, request)
request.json = json_lib.dumps({'method': 'some.method', 'id': 0})
self.assertRaises(JSONException, json._handle_request, request)
示例3: test_get_results
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_get_results(self):
result1 = {'item1': 6, 'item2': 2}
result2 = {'item1': 2, 'item2': 4}
component1 = MagicMock()
component1.json = MagicMock(return_value=result1)
self.engine.components['component1'].requests.get.return_value = component1
component2 = MagicMock()
component2.json = MagicMock(return_value=result2)
self.engine.components['component2'].requests.get.return_value = component2
self.assertEqual(self.engine.get_results({'key': 'value'}), {
'component1': result1, 'component2': result2
})
示例4: test_get_existing_resource
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_get_existing_resource(self, current_user_resources, id_correct_resource):
# Set up the test and its dependencies
req = MagicMock()
req.json = MagicMock(return_value=current_user_resources)
self.instance._make_request = MagicMock(return_value=req)
self.instance._update_acquire_url = MagicMock()
# Get the expected result
if id_correct_resource is not None:
expected_resource = {
'provider': store_connector.plugins.toolkit.c.user,
'name': current_user_resources[id_correct_resource]['name'],
'version': current_user_resources[id_correct_resource]['version']
}
else:
expected_resource = None
# Call the function and check the result
dataset = DATASET.copy()
dataset['private'] = True
self.assertEquals(expected_resource, self.instance._get_existing_resource(dataset))
# Update Acquire URL method is called (when the dataset is registered as resource in the Store)
if expected_resource is not None:
self.instance._update_acquire_url.assert_called_once_with(dataset, current_user_resources[id_correct_resource])
示例5: test_provider_raises_redirect_needed_on_success_captured_payment
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_provider_raises_redirect_needed_on_success_captured_payment(self):
with patch('requests.post') as mocked_post:
transaction_id = '1234'
data = MagicMock()
data.return_value = {
'id': transaction_id,
'token_type': 'test_token_type',
'access_token': 'test_access_token',
'transactions': [
{'related_resources': [
{'sale': {'links': [
{'rel': 'refund', 'href': 'http://refund.com'}]}}
]}
]}
post = MagicMock()
post.json = data
post.status_code = 200
mocked_post.return_value = post
with self.assertRaises(RedirectNeeded) as exc:
self.provider.get_form(
payment=self.payment, data=PROCESS_DATA)
self.assertEqual(exc.args[0], self.payment.get_success_url())
links = self.provider._get_links(self.payment)
self.assertEqual(self.payment.status, 'confirmed')
self.assertEqual(self.payment.captured_amount, self.payment.total)
self.assertEqual(self.payment.transaction_id, transaction_id)
self.assertTrue('refund' in links)
示例6: test_provider_raises_redirect_needed_on_success_preauth_payment
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_provider_raises_redirect_needed_on_success_preauth_payment(self):
provider = PaypalCardProvider(
secret=SECRET, client_id=CLIENT_ID, capture=False)
with patch('requests.post') as mocked_post:
transaction_id = '1234'
data = MagicMock()
data.return_value = {
'id': transaction_id,
'token_type': 'test_token_type',
'access_token': 'test_access_token',
'transactions': [
{'related_resources': [
{'authorization': {'links': [
{'rel': 'refund', 'href': 'http://refund.com'},
{'rel': 'capture', 'href': 'http://capture.com'}]}}
]}
]}
post = MagicMock()
post.json = data
post.status_code = 200
mocked_post.return_value = post
with self.assertRaises(RedirectNeeded) as exc:
provider.get_form(
payment=self.payment, data=PROCESS_DATA)
self.assertEqual(exc.args[0], self.payment.get_success_url())
links = provider._get_links(self.payment)
self.assertEqual(self.payment.status, 'preauth')
self.assertEqual(self.payment.captured_amount, Decimal('0'))
self.assertEqual(self.payment.transaction_id, transaction_id)
self.assertTrue('capture' in links)
self.assertTrue('refund' in links)
示例7: test_get_existing_product
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_get_existing_product(self, current_user_resources, id_correct_resource):
# Set up the test and its dependencies
req = MagicMock()
req.json = MagicMock(return_value=current_user_resources)
r = [current_user_resources[id_correct_resource]] if id_correct_resource is not None else {}
self.instance._get_existing_products = MagicMock(
return_value=r)
self.instance._update_acquire_url = MagicMock()
# Get the expected result
if id_correct_resource is not None:
expected_resource = {
'id': current_user_resources[id_correct_resource]['id'],
'href': current_user_resources[id_correct_resource]['href'],
'name': current_user_resources[id_correct_resource]['name'],
'version': current_user_resources[id_correct_resource]['version']
}
else:
expected_resource = None
# Call the function and check the result
dataset = DATASET.copy()
self.assertEquals(expected_resource, self.instance._get_existing_product(dataset))
# Update Acquire URL method is called (when the dataset is registered as resource in the Store)
if expected_resource is not None:
self.instance._update_acquire_url.assert_called_once_with(
dataset, current_user_resources[id_correct_resource])
示例8: test_provider_redirects_on_success_preauth_payment
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_provider_redirects_on_success_preauth_payment(
self, mocked_redirect, mocked_post):
data = MagicMock()
data.return_value = {
'token_type': 'test_token_type',
'access_token': 'test_access_token',
'payer': {'payer_info': 'test123'},
'transactions': [
{'related_resources': [{
'sale': {'links': ''},
'authorization': {'links': ''}}]}
]}
post = MagicMock()
post.json = data
post.status_code = 200
mocked_post.return_value = post
request = MagicMock()
request.GET = {'token': 'test', 'PayerID': '1234'}
provider = PaypalProvider(
secret=SECRET, client_id=CLIENT_ID, capture=False)
provider.process_data(self.payment, request)
self.assertEqual(self.payment.status, 'preauth')
self.assertEqual(self.payment.captured_amount, Decimal('0'))
示例9: test_integer_price
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_integer_price(self, mock_get):
mock_response = MagicMock()
mock_response.json = {'item': {'name': 'maple logs', 'current': {'price': 12345}}}
mock_get.return_value = mock_response
self.assertEqual(fetcher.fetch_price(1517), ('maple logs', '12345'))
mock_get.assert_called_once_with(
'http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1517')
示例10: _call_api
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def _call_api(self, _url, _params=None):
if self._page_idx >= len(self._page_results):
raise requests.exceptions.HTTPError
response = MagicMock()
response.json = MagicMock(return_value=self._page_results[self._page_idx])
self._page_idx += 1
return response
示例11: test_k_at_end
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_k_at_end(self, mock_get):
mock_response = MagicMock()
mock_response.json = {'item': {'name': 'frost dragon bones', 'current': {'price': '123k'}}}
mock_get.return_value = mock_response
self.assertEqual(fetcher.fetch_price(1337), ('frost dragon bones', '123k'))
mock_get.assert_called_once_with(
'http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1337')
示例12: test_comma_in_price
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_comma_in_price(self, mock_get):
mock_response = MagicMock()
mock_response.json = {'item': {'name': 'fire rune', 'current': {'price': '345,821'}}}
mock_get.return_value = mock_response
self.assertEqual(fetcher.fetch_price(554), ('fire rune', '345,821'))
mock_get.assert_called_once_with(
'http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=554')
示例13: test_floating_point_price
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_floating_point_price(self, mock_get):
mock_response = MagicMock()
mock_response.json = {'item': {'name': 'pickle', 'current': {'price': 1423.543}}}
mock_get.return_value = mock_response
self.assertEqual(fetcher.fetch_price(1234), ('pickle', '1423.543'))
mock_get.assert_called_once_with(
'http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1234')
示例14: test_handle_request_invalid_method
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
def test_handle_request_invalid_method(self):
json = JSON()
request = MagicMock()
json_data = {'method': 'no-existing-module.test', 'id': 0, 'params': []}
request.json = json_lib.dumps(json_data)
request_id, result, error = json._handle_request(request)
self.assertEqual(error, {'message': 'Unknown method', 'code': 2})
示例15: TestRequestsHTTPTransportParseResponse
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import json [as 别名]
class TestRequestsHTTPTransportParseResponse(unittest.TestCase):
def setUp(self):
self._transport = RequestsTransport()
self._requests_response = MagicMock(spec=Response())
def test_parse_response_success(self):
transport_response = self._transport._parse_response(self._requests_response)
self.assertIsInstance(transport_response, APIResponse)
self.assertEqual(self._requests_response.json(), transport_response.data)
self.assertEqual(self._requests_response.headers, transport_response.headers)
self.assertEqual(self._requests_response.status_code, transport_response.status_code)
def test_parse_response_json_success(self):
transport_response = self._transport._parse_response(self._requests_response)
self.assertIsInstance(transport_response, APIResponse)
self._requests_response.json.assert_called_once()
self.assertNotEqual(self._requests_response.text, transport_response.data)
self.assertEqual(self._requests_response.json(), transport_response.data)
self.assertEqual(self._requests_response.headers, transport_response.headers)
self.assertEqual(self._requests_response.status_code, transport_response.status_code)
def test_parse_response_text_success(self):
self._requests_response.json.side_effect = ValueError()
transport_response = self._transport._parse_response(self._requests_response)
self.assertIsInstance(transport_response, APIResponse)
with self.assertRaises(ValueError):
self._requests_response.json()
self.assertEqual(self._requests_response.text, transport_response.data)
self.assertEqual(self._requests_response.headers, transport_response.headers)
self.assertEqual(self._requests_response.status_code, transport_response.status_code)
def test_parse_response_400_failure(self):
self._requests_response.raise_for_status.side_effect = HTTPError()
self._requests_response.status_code = 400
transport_response = self._transport._parse_response(self._requests_response)
self.assertIsInstance(transport_response, APIErrorResponse)
self.assertEqual(self._requests_response.json(), transport_response.data)
self.assertEqual(self._requests_response.headers, transport_response.headers)
self.assertEqual(self._requests_response.status_code, transport_response.status_code)
def test_parse_response_500_failure(self):
self._requests_response.raise_for_status.side_effect = HTTPError()
self._requests_response.status_code = 500
with self.assertRaises(HTTPError):
self._transport._parse_response(self._requests_response)