本文整理汇总了Python中mock.MagicMock.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.status_code方法的具体用法?Python MagicMock.status_code怎么用?Python MagicMock.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.status_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _invalid_billing
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def _invalid_billing(self):
valid_response = MagicMock()
valid_response.status_code = 200
valid_response.json.side_effect = [OFFERING]
invalid_response = MagicMock()
invalid_response.status_code = 400
ordering_management.requests.get.side_effect = [valid_response, invalid_response]
示例2: test_handle_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_handle_response(self):
connection = Connection('store.mybigcommerce.com', ('user', 'abcdef'))
# A normal, 200-ok response
data = {
'name': 'Shirt'
}
res = MagicMock()
res.headers = {'Content-Type': 'application/json'}
res.status_code = 200
res.content = json.dumps(data)
res.json.return_value = data
self.assertEqual(connection._handle_response('products/1', res), data)
res.status_code = 500
self.assertRaisesHttpException(ServerException,
lambda: connection._handle_response('products/1', res),
# Test all of the properties of a HttpException
500,
{'Content-Type': 'application/json'},
json.dumps(data))
res.status_code = 404
self.assertRaisesHttpException(ClientRequestException,
lambda: connection._handle_response('products/1', res), 404)
res.status_code = 301
self.assertRaisesHttpException(RedirectionException,
lambda: connection._handle_response('products/1', res), 301)
示例3: test_handle_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_handle_response(self):
connection = Connection("store.mybigcommerce.com", ("user", "abcdef"))
# A normal, 200-ok response
data = {"name": "Shirt"}
res = MagicMock()
res.headers = {"Content-Type": "application/json"}
res.status_code = 200
res.content = json.dumps(data)
res.json.return_value = data
self.assertEqual(connection._handle_response("products/1", res), data)
res.status_code = 500
self.assertRaisesHttpException(
ServerException,
lambda: connection._handle_response("products/1", res),
# Test all of the properties of a HttpException
500,
{"Content-Type": "application/json"},
json.dumps(data),
)
res.status_code = 404
self.assertRaisesHttpException(
ClientRequestException, lambda: connection._handle_response("products/1", res), 404
)
res.status_code = 301
self.assertRaisesHttpException(
RedirectionException, lambda: connection._handle_response("products/1", res), 301
)
示例4: create_mock_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [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
示例5: test_put_observation
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_put_observation(self, mock_conn, caps_mock):
caps_mock.get_service_host.return_value = 'some.host.com'
caps_mock.return_value.get_access_url.return_value =\
'http://serviceurl/caom2repo/pub'
collection = 'cfht'
observation_id = '7000000o'
service = 'caom2repo'
service_url = 'www.cadc.nrc.ca'
obs = SimpleObservation(collection, observation_id)
subject = auth.Subject(certificate='somefile.pem')
level = logging.DEBUG
visitor = CAOM2RepoClient(subject, level, host=service_url)
response = MagicMock()
response.status = 200
mock_conn.return_value = response
iobuffer = BytesIO()
ObservationWriter().write(obs, iobuffer)
obsxml = iobuffer.getvalue()
response.content = obsxml
visitor.put_observation(obs)
self.assertEqual('PUT', mock_conn.call_args[0][0].method)
self.assertEqual(
'/{}/pub/{}/{}'.format(service, collection, observation_id),
mock_conn.call_args[0][0].path_url)
self.assertEqual('application/xml',
mock_conn.call_args[0][0].headers['Content-Type'])
self.assertEqual(obsxml, mock_conn.call_args[0][0].body)
# signal problems
http_error = requests.HTTPError()
response.status_code = 500
http_error.response = response
response.raise_for_status.side_effect = [http_error]
with self.assertRaises(exceptions.InternalServerException):
visitor.create(obs)
# temporary transient errors
http_error = requests.HTTPError()
response.status_code = 503
http_error.response = response
response.raise_for_status.side_effect = [http_error, None]
visitor.put_observation(obs)
# permanent transient errors
http_error = requests.HTTPError()
response.status_code = 503
http_error.response = response
def raise_error(): raise http_error
response.raise_for_status.side_effect = raise_error
with self.assertRaises(exceptions.HttpException):
visitor.put_observation(obs)
示例6: test_data_for
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_data_for(self):
mock_data = {"test": "test"}
mock_response = MagicMock(spec=Response)
mock_response.data = mock_data
mock_response.status_code = 200
data = HtmlCommunityView.data_for(CommunityMock, mock_response)
self.assertEqual(data, mock_data)
mock_response.status_code = 300
data = HtmlCommunityView.data_for(CommunityMock, mock_response)
self.assertEqual(data, mock_data)
mock_response.status_code = 500 # or any other status
data = HtmlCommunityView.data_for(CommunityMock, mock_response)
self.assertIsNone(data)
data = HtmlCommunityView.data_for(CommunityMock, None)
self.assertIsNone(data)
示例7: test_provider_raises_redirect_needed_on_success_preauth_payment
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [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)
示例8: init_mock
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def init_mock(self, json_data_file):
fake_response = MagicMock()
fake_response.status_code = 200
with open(json_data_file) as json_data:
response_data = json.load(json_data)
fake_response.json.return_value = response_data
return fake_response
示例9: test_provider_raises_redirect_needed_on_success_captured_payment
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [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)
示例10: test_getContextForCollectionMappings_contextRecieved
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_getContextForCollectionMappings_contextRecieved(self, mock_get):
mappingResponse = MagicMock(spec=Response)
collection = ["Some Results"]
mappingResponse.json.return_value = collection
mappingResponse.status_code = 200
mappingResponse.headers = []
mock_get.return_value = mappingResponse
collectionMappingsView = views.CollectionMappingsView()
collectionMappingsView.request = FakeRequest()
hash = {'collection': 'test', 'org': 'org1'}
collectionMappingsView.kwargs = hash
context = collectionMappingsView.get_context_data()
self.assertEquals(context['url_params'], {})
self.assertEquals(context['kwargs'], hash)
self.assertEquals(context['selected_tab'], 'Mappings')
self.assertEquals(context['results'], collection)
self.assertEquals(context['pagination_url'], '/foobar')
self.assertEquals(context['search_query'], '')
self.assertIsInstance(context['search_filters'], SearchFilterList)
# TODO: Revise sort assertion to work with new sort option definitions
# self.assertEquals(context['search_sort_options'], ['Best Match', 'Last Update (Desc)', 'Last Update (Asc)', 'Name (Asc)', 'Name (Desc)'])
self.assertEquals(context['search_sort'], '')
self.assertEquals(context['search_facets_json'], None)
示例11: test__request_retries_login
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test__request_retries_login(self, mock_login):
initial_xreply = {"return_code": 1, "content": "login_required"}
pre_login_response = MagicMock(spec=requests.Response())
pre_login_response.status_code = 200
pre_login_response.content = json.dumps(initial_xreply)
final_xreply = {"return_code": 0, "content": "success"}
post_login_response = MagicMock(spec=requests.Response())
post_login_response.status_code = 200
post_login_response.content = json.dumps(final_xreply)
side_effect = [pre_login_response, post_login_response]
self.client.session.request = MagicMock(side_effect=side_effect)
self.assertEquals((True, "success"),
self.client._request("http://example.com"))
示例12: _mock_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def _mock_response(self, status_code=404, headers={}, content='PAGE_NOT_FOUND'):
r = MagicMock(Response())
r.status_code = status_code
r.headers = CaseInsensitiveDict(headers if headers is not None else {})
r.content = content
r.ok = status_code < 400
return r
示例13: test_add_new_entities
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_add_new_entities(monkeypatch, json):
zmon_client = MagicMock()
resp = MagicMock()
resp.status_code = 200
zmon_client.add_entity.return_value = resp
existing_ids = ['1', '2', '3']
current_ids = ['2', '3', '4', '5']
existing_entities = [{'id': i, 'type': 'e-type'} for i in existing_ids]
all_current_entities = [{'id': i, 'type': 'e-type'} for i in existing_ids + current_ids]
new_entities, count = add_new_entities(all_current_entities, existing_entities, zmon_client, json=json)
expected = [{'id': '4', 'type': 'e-type'}, {'id': '5', 'type': 'e-type'}]
assert new_entities == expected
assert count == 0
calls = [call(e) for e in expected]
if not json:
zmon_client.add_entity.assert_has_calls(calls, any_order=True)
else:
zmon_client.add_entity.assert_not_called()
示例14: test_add_image_with_file_object
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_add_image_with_file_object(self, mocked_os_path_getsize, mocked_os_path_isfile, mocked_requests_post, mocked_url, mocked_headers):
mocked_os_path_isfile.return_value = True
mocked_os_path_getsize.return_value = 7
response_mock = MagicMock()
response_mock.status_code = 201
mocked_requests_post.return_value = response_mock
mocked_url.return_value = 'url'
mocked_headers.return_value = {'Accept': 'application/json'}
content = 'content'
m = '__builtin__'
dummy_data = 'dummy_image_data_to_read'
if sys.version_info >= (3,):
m = 'builtins'
import io
sio = io.StringIO(dummy_data)
else:
import StringIO
sio = StringIO.StringIO(dummy_data)
# this should not be called
mocked_open = mock_open(read_data=content)
with patch(m + '.open', mocked_open):
result = self._client.add_image(sio)
mocked_requests_post.assert_called_once_with('url', data=dummy_data, headers={'Accept': 'application/json'})
示例15: test_getters_from_invalid_queue_item
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import status_code [as 别名]
def test_getters_from_invalid_queue_item():
# First we mock an HTTP 404 error response, which is what the Jenkins
# REST API will return when the endpoint referenced by our queue item
# no longer exists
mock_response = MagicMock()
mock_response.status_code = 404
# Mock a Jenkins REST API object with the relevant structures used by
# our queue item
mock_api = MagicMock()
mock_api.get_api_data.side_effect = HTTPError(response=mock_response)
expected_id = 1234
mock_api.url = "https://jenkins.server/queue/item/" + str(expected_id)
# Flex our code
q1 = QueueItem(mock_api)
# confirm the results
assert q1.uid == expected_id
assert q1.stuck is None
assert q1.blocked is None
assert q1.buildable is None
assert q1.reason is None
assert q1.waiting is None
assert q1.cancelled is None
assert q1.job is None
assert q1.build is None