当前位置: 首页>>代码示例>>Python>>正文


Python MagicMock.read方法代码示例

本文整理汇总了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)
开发者ID:ZhangXinNan,项目名称:keras,代码行数:28,代码来源:test_utils.py

示例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])
开发者ID:ICTU,项目名称:quality-report,代码行数:30,代码来源:sharepoint_planner_tests.py

示例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)
开发者ID:Benzhaomin,项目名称:twitchcancer,代码行数:9,代码来源:test_twitchapi.py

示例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)
开发者ID:ICTU,项目名称:quality-report,代码行数:28,代码来源:tfs_owasp_dependency_xml_report_tests.py

示例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"}))
开发者ID:athmane,项目名称:gns3-server,代码行数:10,代码来源:test_compute.py

示例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()
开发者ID:sp4x,项目名称:presence,代码行数:13,代码来源:tests.py

示例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)
开发者ID:drewthepooh,项目名称:youtube-py,代码行数:14,代码来源:test_youtube.py

示例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.
开发者ID:deepsnow,项目名称:SwLn_Stuff,代码行数:14,代码来源:XforceLookup_Template.py

示例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)
开发者ID:ICTU,项目名称:quality-report,代码行数:53,代码来源:tfs_owasp_dependency_xml_report_tests.py

示例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
开发者ID:BioQwer,项目名称:find_forks,代码行数:16,代码来源:test_find_forks.py

示例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
开发者ID:django-silk,项目名称:silk,代码行数:17,代码来源:test_profile_dot.py

示例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)
开发者ID:ICTU,项目名称:quality-report,代码行数:18,代码来源:tfs_owasp_dependency_xml_report_tests.py

示例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'))
开发者ID:ICTU,项目名称:quality-report,代码行数:48,代码来源:tfs_owasp_dependency_xml_report_tests.py

示例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}
    ]
开发者ID:GNS3,项目名称:gns3-server,代码行数:21,代码来源:test_compute.py

示例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()
})

开发者ID:lwcolton,项目名称:turf,代码行数:31,代码来源:test_s3config.py


注:本文中的unittest.mock.MagicMock.read方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。