本文整理汇总了Python中mock.MagicMock.text方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.text方法的具体用法?Python MagicMock.text怎么用?Python MagicMock.text使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.text方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_mock_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [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_undo
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_undo(self):
"""
Does the undo disable the interface?
"""
connection = MagicMock(name='connection')
html = MagicMock(name='html')
connection.return_value = html
html.text = open('radio_asp.html').read()
command = EnableInterface(connection=connection)
command.band = 5
command()
html.text = open('radio_5_asp.html').read()
command.undo()
query_call = call(data={'wl_unit':'1'})
calls = [query_call,
call(data={'action':'Apply',
'wl_unit':'1',
'wl_radio':'1'}),
call(data ={'action':'Apply',
'wl_unit':'1',
'wl_radio':'0'})]
self.assertEqual(connection.mock_calls, calls)
self.command.previous_state = 'Enabled'
# the disable checks the state so we need to change the html so it is Disabled
#self.html.text = open('radio_5_asp.html').read()
#self.command.undo()
#self.assertEqual(self.connection.mock_calls, calls)
return
示例3: _build_mock_request
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def _build_mock_request(method):
status_values = {
'get': 200,
'put': 200,
'post': 201,
'delete': 204
}
# Build response
response = MagicMock()
response.status_code = status_values[method]
if method == 'get':
response.headers = {
'content-type': 'application/rdf+xml'
}
response.text = 'value returned'
def _mock_request(url, headers={}, data=''):
# Check headers
if 'Authorization' not in headers:
response.status_code = 401
if method == 'get' and 'Accept' not in headers:
response.status_code = 406
if (method == 'put' or method == 'post') and 'Content-Type' not in headers:
response.status_code = 415
response.url = url
return response
return _mock_request
示例4: test_metrics
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_metrics(monkeypatch):
client = client_mock(monkeypatch)
resp = MagicMock()
resp.text = 'metrics'
client.return_value.session.get.return_value = resp
parsed = MagicMock()
parsed.samples = [
('metric-1', {}, 20.17), ('metric-2', {'verb': 'GET'}, 20.16), ('metric-1', {'verb': 'POST'}, 20.18)
]
parser = MagicMock()
parser.return_value = [parsed]
monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.kubernetes.text_string_to_metric_families', parser)
k = KubernetesWrapper()
metrics = k.metrics()
expected = {
'metric-1': [({}, 20.17), ({'verb': 'POST'}, 20.18)],
'metric-2': [({'verb': 'GET'}, 20.16)],
}
assert metrics == expected
parser.assert_called_with(resp.text)
client.return_value.session.get.assert_called_with(CLUSTER_URL + '/metrics')
示例5: test_provider_shows_validation_error_message
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_provider_shows_validation_error_message(self):
provider = AuthorizeNetProvider(
login_id=LOGIN_ID, transaction_key=TRANSACTION_KEY)
error_msg = 'The merchant does not accept this type of credit card.'
response_data = [
ERROR_PROCESSING,
'',
'',
error_msg,
'',
'',
'1234']
with patch('requests.post') as mocked_post:
post = MagicMock()
# post.ok = False
post.text = '|'.join(response_data)
mocked_post.return_value = post
form = provider.get_form(self.payment, data=PROCESS_DATA)
self.assertEqual(form.errors['__all__'][0], error_msg)
self.assertFalse(form.is_valid())
self.assertEqual(self.payment.status, 'error')
self.assertEqual(self.payment.captured_amount, 0)
self.assertEqual(self.payment.message, error_msg)
示例6: test_handle_http_error
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_handle_http_error(self, transport, input):
status, error_cls = input
error_body_json = {
'message': 'error message',
'support_email': '[email protected]'
}
error_body_text = json.dumps(error_body_json)
mock_response = MagicMock()
mock_response.status_code = status
mock_response.text = error_body_text
mock_response.json.return_value = error_body_json
error = HTTPError('error message', status)
error.response = mock_response
with pytest.raises(error_cls) as excinfo:
transport._handle_http_error(error)
err = excinfo.value
assert err.message == 'error message'
assert err.status == status
assert err.raw == error_body_text
assert err.json == error_body_json
示例7: test_does_not_find_labels
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_does_not_find_labels(self, m_requests):
mock_response = MagicMock()
job_config = '<?xml version="1.0" encoding="UTF-8"?><project></project>'
mock_response.text = job_config
m_requests.get.return_value = mock_response
result = util.match_node_from_job_config("https://jenkins.ceph.com/job/ceph-pull-requests")
assert not result
示例8: test_finds_labels
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_finds_labels(self, m_requests):
mock_response = MagicMock()
job_config = '<?xml version="1.0" encoding="UTF-8"?><project><assignedNode>amd64 && debian</assignedNode></project>'
mock_response.text = job_config
m_requests.get.return_value = mock_response
result = util.match_node_from_job_config("https://jenkins.ceph.com/job/ceph-pull-requests")
assert result == "wheezy"
示例9: test_json_parsing_error
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_json_parsing_error(self):
# Make sure if the json parsing fails, we get a useful exception
# Create a mock response that raises an exception when we try to get the json from it
mock_response = MagicMock()
mock_response.text = "This was the content"
mock_response.content = mock_response.text.encode("utf-8")
mock_response.json.side_effect = Exception("This is an exception")
# Mock session that returns our mock response on a 'get' call.
mock_session = MagicMock()
mock_session.get.return_value = mock_response
client = OnaApiClient("example.com", "2384729347234")
with patch.object(client, "session") as mock_session_method:
# 'session' method on our client returns our mock session
mock_session_method.return_value = mock_session
try:
client.get("foo")
except OnaApiClientException as e:
# Make sure the exception has lots of useful info
s = str(e)
self.assertIn("could not be parsed", s)
self.assertIn("This is an exception", s)
self.assertIn("This was the content", s)
else:
self.fail("Expected OnaApiClientException")
示例10: test_signups_worker_retries
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_signups_worker_retries(self) -> None:
"""Tests the retry logic of signups queue."""
fake_client = self.FakeClient()
user_id = self.example_user('hamlet').id
data = {'user_id': user_id, 'id': 'test_missed'}
fake_client.queue.append(('signups', data))
def fake_publish(queue_name: str, event: Dict[str, Any], processor: Callable[[Any], None]) -> None:
fake_client.queue.append((queue_name, event))
fake_response = MagicMock()
fake_response.status_code = 400
fake_response.text = ujson.dumps({'title': ''})
with simulated_queue_client(lambda: fake_client):
worker = queue_processors.SignupWorker()
worker.setup()
with patch('zerver.worker.queue_processors.requests.post',
return_value=fake_response), \
patch('zerver.lib.queue.queue_json_publish',
side_effect=fake_publish), \
patch('logging.info'), \
self.settings(MAILCHIMP_API_KEY='one-two',
PRODUCTION=True,
ZULIP_FRIENDS_LIST_ID='id'):
worker.start()
self.assertEqual(data['failed_tries'], 4)
示例11: test_fields
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_fields(self, mocked_requests):
""""""
mocked_result = MagicMock()
mocked_result.text = self.sample_response
mocked_requests.get.return_value = mocked_result
# print self.client.fields("sf1", "2010")
self.assertTrue(isinstance(self.client.fields("sf1", "2010"), dict))
self.assertTrue('H0040002' in self.client.fields("sf1", "2010"))
示例12: get_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def get_response(self, method, url, verify, headers, data=None):
resp = MagicMock()
resp.status_code = 400
parts = urlparse(url)
url = parts[2]
params = parts[4]
if method == "GET":
if url == "/infrastructures/infid" or url == "/infrastructures/newinfid":
resp.status_code = 200
resp.json.return_value = {"uri-list": [{ "uri": "http://server.com/infid/vms/0"},
{ "uri": "http://server.com/infid/vms/1"}]}
elif url == "/infrastructures/infid/state":
resp.status_code = 200
resp.json.return_value = {"state": {"state": "configured",
"vm_states": {"0": "configured",
"1": "configured"}}}
elif url == "/infrastructures/infid/vms/0":
resp.status_code = 200
resp.text = "network public (outbound='yes')\n"
resp.text += "system front (net_interface.0.connection = 'public' and net_interface.0.ip = '8.8.8.8')"
elif url == "/infrastructures/infid/data":
resp.status_code = 200
resp.json.return_value = {"data": "data"}
elif url == "/infrastructures/infid/contmsg":
resp.status_code = 200
resp.text = "contmsg"
elif url == "/infrastructures/infid/radl":
resp.status_code = 200
resp.text = "network public (outbound='yes')\n"
resp.text += "system front (net_interface.0.connection = 'public' and net_interface.0.ip = '8.8.8.8')"
elif method == "POST":
if url == "/infrastructures":
resp.status_code = 200
resp.text = 'http://server.com/infid'
elif method == "PUT":
if url == "/infrastructures":
resp.status_code = 200
resp.text = 'http://server.com/newinfid'
elif url == "/infrastructures/infid/reconfigure":
resp.status_code = 200
resp.text = ''
elif url == "/infrastructures/newinfid/stop":
resp.status_code = 200
resp.text = ''
elif url == "/infrastructures/infid/start":
resp.status_code = 200
resp.text = ''
elif method == "DELETE":
if url == "/infrastructures/infid":
resp.status_code = 200
return resp
示例13: create_mock_response
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [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)
}
def _create_iterator(buffer_size):
response._content_iterator = IterateContents(kwargs['contents'],
kwargs['buffer_size'],
kwargs.get('partial_start', 0),
kwargs.get('partial_end', None))
return response._content_iterator
response.iter_content = _create_iterator
response.raw.tell = lambda: response._content_iterator.total_bytes_iterated()
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
示例14: it_uses_lastfm_to_find_song
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def it_uses_lastfm_to_find_song(self, twitter, complete_song):
complete_song.return_value = {}
tweet = MagicMock()
tweet.text = "Wake up by Motopony, from #SoundHound http:\/\/t.co\/n2egIeV5dC"
tweet.created_at = "Thu May 30 00:00:20 +0000 2013"
twitter.Api.return_value.GetUserTimeline = lambda x: [tweet]
tracks = twit.get_user_listens('satshabad')
expect(tracks[0]).contains('type')
expect(tracks[0]).contains('dateListened')
示例15: test_ticket_count_unauthorized
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import text [as 别名]
def test_ticket_count_unauthorized(self):
response_mock = MagicMock()
response_mock.status_code = 403
response_mock.text = None
with self.assertRaises(livezilla.APIError):
self.connector.http_client.post = MagicMock(return_value=response_mock)
self.connector.ticket_count()
self.connector.http_client.post.assert_called_once_with(self.LZ_URL, data={'p_user': self.LZ_USER,
'p_pass': self.password_md5,
'p_tickets_list': 1})