本文整理汇总了Python中unittest.mock.MagicMock.read方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.read方法的具体用法?Python MagicMock.read怎么用?Python MagicMock.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FileIO
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def FileIO(self, name, mode):
"""Proxy for tensorflow.python.lib.io.file_io.FileIO class. Mocks the class
if a real GCS bucket is not available for testing.
"""
self._check_started()
if not self.mock_gcs:
return tf_file_io.FileIO(name, mode)
filepath = name
if filepath.startswith(self._gcs_prefix):
mock_fio = MagicMock()
mock_fio.__enter__ = Mock(return_value=mock_fio)
if mode == 'rb':
if filepath not in self.local_objects:
raise IOError('{} does not exist'.format(filepath))
self.local_objects[filepath].seek(0)
mock_fio.read = self.local_objects[filepath].read
elif mode == 'wb':
self.local_objects[filepath] = BytesIO()
mock_fio.write = self.local_objects[filepath].write
else:
raise ValueError(
'{} only supports wrapping of FileIO for `mode` "rb" or "wb"')
return mock_fio
return open(filepath, mode)
示例2: test_datetime_http_error
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_datetime_http_error(self, mock_url_read, mock_error, mock_write_json, mock_read_json):
""" Test that the last activity date is min date, when an http error occurs. """
file_object = MagicMock()
file_object.read = MagicMock(return_value=b'additional reason')
mock_url_read.side_effect = [urllib.error.HTTPError(None, None, None, None, file_object)]
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
last_activity_date = planner.datetime('plan_id_xx')
mock_write_json.assert_not_called()
mock_url_read.assert_called_once_with(
url='https://login.microsoftonline.com/common/oauth2/token',
post_body=bytes(parse.urlencode({
"grant_type": "refresh_token",
"client_id": 'client_id_xx',
"client_secret": 'client_secret_k=',
"resource": "https://graph.microsoft.com",
"refresh_token": 'refresh_token_content_xx'
}), 'ascii')
)
self.assertEqual(last_activity_date, datetime.datetime.min)
self.assertEqual(
'Error retrieving access token. Reason: %s. Additional information: %s', mock_error.call_args_list[0][0][0])
self.assertIsInstance(mock_error.call_args_list[0][0][1], urllib.error.HTTPError)
self.assertEqual('additional reason', mock_error.call_args_list[0][0][2])
示例3: get_opener
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def get_opener(response_data):
data = MagicMock()
data.read = Mock(return_value=response_data)
response = MagicMock()
response.__enter__ = Mock(return_value=data)
return MagicMock(return_value=response)
示例4: test_nr_warnings_no_archived_content
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_nr_warnings_no_archived_content(self, mock_url_open, mock_url_read, mock_error):
""" Test retrieving high priority warnings. """
mock_url_read.return_value = '{"value": [{"url": "http://build/tfs/api"}]}'
archive = zipfile.ZipFile('temp.zip', 'w')
report = 'some content'
archive.writestr('zipped_file.txt', report)
archive.close()
with open('temp.zip', 'rb') as disk_file:
byte_stream = disk_file.read()
os.remove('temp.zip')
response = MagicMock()
response.read = MagicMock(return_value=byte_stream)
mock_url_open.return_value = response
report = metric_source.TfsOWASPDependencyXMLReport(
base_url='http://base.url', organization='org', project='Project',
definitions='2,3', pat_token='abc3_pat_token')
self.assertEqual(-1, report.nr_warnings(('url',), 'high'))
self.assertEqual("Archive of the OWASP report is corrupted: %s.", mock_error.mock_calls[0][1][0])
self.assertIsInstance(mock_error.mock_calls[0][1][1], KeyError)
self.assertEqual('Error parsing returned xml: %s.', mock_error.mock_calls[1][1][0])
self.assertIsInstance(mock_error.mock_calls[1][1][1], xml.etree.ElementTree.ParseError)
示例5: test_compute_httpQueryConflictError
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_compute_httpQueryConflictError(compute, async_run):
response = MagicMock()
with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock:
response.status = 409
response.read = AsyncioMagicMock(return_value=b'{"message": "Test"}')
with pytest.raises(ComputeConflict):
async_run(compute.post("/projects", {"a": "b"}))
示例6: testDone
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def testDone(self):
request = MagicMock()
serial = MagicMock()
serial.readline = MagicMock(return_value=modem.MSG_OK)
controller = modem.AtlantisModemController(serial)
controller.add_reader = MagicMock()
controller.setup(request)
serial.read = MagicMock(return_value=modem.MSG_RING)
serial.readline = MagicMock(return_value=modem.MSG_BUSY)
controller.handle_ring()
request.done.assert_called_with()
示例7: test_handle_API_errors
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_handle_API_errors(self):
t = youtube.Tuber(None, None)
t.username = 'test_tuber'
with open('errors_sample.xml') as xml:
mock_urlresponse = MagicMock()
mock_urlresponse.read = xml.read
mock_urlresponse.status = 400
mock_urlopen = MagicMock(return_value=mock_urlresponse)
with patch('youtube.urllib.request.urlopen', new=mock_urlopen):
self.assertRaisesRegex(helpers.YouTubeAPIError,
'too_many_recent_calls',
t.fetch_link, 30)
示例8: test__LookUpIpAddr_OneUrlReqMade
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test__LookUpIpAddr_OneUrlReqMade(self):
ip_data = { 'ip': '198.60.22.4', 'geo': { 'countrycode': 'US', 'country': 'United States' } }
json_data = json.dumps(ip_data) ## Construct a small amount of JSON.
resp = bytes(json_data, 'UTF-8') ## Turn the JSON into raw bytes, just like those that will come in an HTTP reply.
resp_mock = MagicMock(spec=http.client.HTTPResponse) ## Create an object to substitute for a genuine HTTP response object.
resp_mock.read = MagicMock(return_value=resp) ## Anticipate a call to read() on that response object.
with patch.object(urllib.request, 'urlopen', return_value=resp_mock) as open_mock:
self.xl._PrepareRequest('198.60.22.4')
output = self.xl._LookUpIpAddr()
open_mock.assert_called_once_with(self.xl.urlRequest) ## Ensure that the HTTP request is made.
resp_mock.read.assert_called_once() ## Ensure that read() is called on the response object.
assert output == ip_data ## Ensure that the HTTP response body is properly decoded into a string, and that its initial parsing from JSON to a Python dict object succeeds.
示例9: test_get_dependencies_info
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_get_dependencies_info(self, mock_url_open, mock_url_read):
""" Test that it gets medium priority warnings. """
mock_url_read.return_value = '{"value": [{"url": "http://build/tfs/api"}]}'
archive = zipfile.ZipFile('temp.zip', 'w')
report = '''<analysis xmlns="https://namespace.1.3.xsd">
<dependencies>
<dependency />
<dependency>
<fileName>dependency.name</fileName>
<description>Desc.</description>
<vulnerabilities>
<vulnerability>
<name>CVE-123</name>
<severity>Medium</severity>
<references>
<reference><url>http://www.securityfocus.com/bid/123</url></reference>
</references>
</vulnerability>
<vulnerability>
<name>CVE-124</name>
<severity>Medium</severity>
<references>
<reference><url>http://www.securityfocus.com/bid/124</url></reference>
</references>
</vulnerability>
</vulnerabilities>
</dependency>
</dependencies>
</analysis>'''
archive.writestr(os.path.join('OWASP', 'dependency-check-report.xml'), report)
archive.close()
with open('temp.zip', 'rb') as disk_file:
byte_stream = disk_file.read()
os.remove('temp.zip')
response = MagicMock()
response.read = MagicMock(return_value=byte_stream)
mock_url_open.return_value = response
report = metric_source.TfsOWASPDependencyXMLReport(
base_url='http://base.url', organization='org', project='Project',
definitions='2,3', pat_token='abc3_pat_token')
result = report.get_dependencies_info('url', 'normal')
self.assertEqual('dependency.name', result[0].file_name)
self.assertEqual(2, result[0].nr_vulnerabilities)
self.assertEqual([('CVE-123', 'http://www.securityfocus.com/bid/123'),
('CVE-124', 'http://www.securityfocus.com/bid/124')], result[0].cve_links)
示例10: make_mock
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def make_mock(json_response):
"""Used in test_interesting.py."""
response_mock = MagicMock()
response_mock.read = Mock(return_value=json_response)
if PY3:
response_mock.status = 200
response_mock.getheader = Mock(return_value='<https://api.github.com/repos/frost-nzcr4/find_forks/forks?page=2>; rel="next", '
'<https://api.github.com/repos/frost-nzcr4/find_forks/forks?page=3>; rel="last"')
else:
response_mock.code = 200
response_mock.info = Mock(return_value=(('link', '<https://api.github.com/repos/frost-nzcr4/find_forks/forks?page=2>; rel="next", '
'<https://api.github.com/repos/frost-nzcr4/find_forks/forks?page=3>; rel="last"'), ))
return response_mock
示例11: _mock_file
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def _mock_file(cls, data):
"""
Get a mock object that looks like a file but returns data when read is called.
"""
i = [0]
def read(n):
if not i[0]:
i[0] += 1
return data
stream = MagicMock()
stream.open = lambda: None
stream.read = read
return stream
示例12: test_nr_warnings_corrupted_archive
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_nr_warnings_corrupted_archive(self, mock_url_open, mock_url_read, mock_error):
""" Test retrieving high priority warnings. """
mock_url_read.return_value = '{"value": [{"url": "http://build/tfs/api"}]}'
response = MagicMock()
response.read = MagicMock(return_value=b'unexpected content')
mock_url_open.return_value = response
report = metric_source.TfsOWASPDependencyXMLReport(
base_url='http://base.url', organization='org', project='Project',
definitions='2,3', pat_token='abc3_pat_token')
self.assertEqual(-1, report.nr_warnings(('url',), 'high'))
self.assertEqual("Archive of the OWASP report is corrupted: %s.", mock_error.mock_calls[0][1][0])
self.assertIsInstance(mock_error.mock_calls[0][1][1], zipfile.BadZipFile)
self.assertEqual('Error parsing returned xml: %s.', mock_error.mock_calls[1][1][0])
self.assertIsInstance(mock_error.mock_calls[1][1][1], xml.etree.ElementTree.ParseError)
示例13: test_nr_warnings
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_nr_warnings(self, mock_url_open, mock_url_read):
""" Test retrieving high priority warnings. """
mock_url_read.return_value = '{"value": [{"url": "http://build/tfs/api"}]}'
archive = zipfile.ZipFile('temp.zip', 'w')
report = '''<?xml version="1.0"?>
<analysis xmlns="https://jeremylong.github.io/DependencyCheck/dependency-check.1.3.xsd">
<dependencies>
<dependency>
<filePath>testHigh</filePath>
<vulnerabilities>
<vulnerability>
<severity>High</severity>
</vulnerability>
</vulnerabilities>
<relatedDependencies>
<relatedDependency>
<filePath>/tmp/src/packaging/target/vib/WEB-INF/lib/vib-services-soap-client-11.0.234.jar</filePath>
<sha1>93622cad52550fa7b5dd186ae8bddd10c16df215</sha1>
<md5>5bb4f244edd7d043507432e76e804581</md5>
<identifier type="maven">
<name>(nl.ictu.isr.templates:vib-services-soap-client:11.0.234)</name>
</identifier>
</relatedDependency>
</relatedDependencies>
</dependency>
</dependencies>
</analysis>
'''
archive.writestr(os.path.join('OWASP', 'dependency-check-report.xml'), report)
archive.close()
with open('temp.zip', 'rb') as disk_file:
byte_stream = disk_file.read()
os.remove('temp.zip')
response = MagicMock()
response.read = MagicMock(return_value=byte_stream)
mock_url_open.return_value = response
report = metric_source.TfsOWASPDependencyXMLReport(
base_url='http://base.url', organization='org', project='Project',
definitions='2,3', pat_token='abc3_pat_token')
self.assertEqual(1, report.nr_warnings(('url',), 'high'))
示例14: test_images
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
def test_images(compute, async_run, images_dir):
"""
Will return image on compute
"""
response = MagicMock()
response.status = 200
response.read = AsyncioMagicMock(return_value=json.dumps([{
"filename": "linux.qcow2",
"path": "linux.qcow2",
"md5sum": "d41d8cd98f00b204e9800998ecf8427e",
"filesize": 0}]).encode())
with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock:
images = async_run(compute.images("qemu"))
mock.assert_called_with("GET", "https://example.com:84/v2/compute/qemu/images", auth=None, data=None, headers={'content-type': 'application/json'}, chunked=None, timeout=None)
async_run(compute.close())
assert images == [
{"filename": "linux.qcow2", "path": "linux.qcow2", "md5sum": "d41d8cd98f00b204e9800998ecf8427e", "filesize": 0}
]
示例15: str
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import read [as 别名]
encrypted = True
mock_config_dict = {
str(sentinel.key): str(sentinel.value)
}
raw_yaml_body = yaml.dump(mock_config_dict)
MockValidator = MagicMock()
MockValidator.validate = MagicMock(return_value=True)
MockStreamingBody = MagicMock()
MockStreamingBody.read = MagicMock(return_value=raw_yaml_body)
MockAwsClient = MagicMock()
MockAwsClient.get_object = MagicMock(return_value={
"Body": MockStreamingBody,
"ContentLength": sentinel.content_length
})
MockAwsClient.put_object = MagicMock()
MockAwsClient.decrypt = MagicMock(return_value={
"Plaintext": raw_yaml_body
})
MockAwsClient.encrypt = MagicMock(return_value={
"CiphertextBlob": str(sentinel.ciphertext_blob).encode()
})