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


Python Mock.read方法代码示例

本文整理汇总了Python中mock.Mock.read方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.read方法的具体用法?Python Mock.read怎么用?Python Mock.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mock.Mock的用法示例。


在下文中一共展示了Mock.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _fake_popen

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def _fake_popen( self, stdout, stderr, sleeptime ):
        def wait_stdout( self ):
            import time
            for line in stdout.splitlines():
                time.sleep(sleeptime)
                yield line

        def wait_stderr( self ):
            import time
            for line in stderr.splitlines():
                time.sleep(sleeptime)
                yield line

        m = Mock(spec=subprocess.Popen)
        sout = Mock()
        sout.read = stdout
        sout.__iter__ = wait_stdout

        serr = Mock()
        serr.read = stderr
        serr.__iter__ = wait_stderr
        
        m.return_value.stdout = sout
        m.return_value.stderr = serr
        return m
开发者ID:necrolyte2,项目名称:beast_whip,代码行数:27,代码来源:common.py

示例2: side_effect

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
 def side_effect(filePath, mode):
   mockFile = Mock()
   if filePath == masterChangeSetFilePath:
     mockFile.read = Mock(return_value=mockMasterYaml)
   else:
     self.assertEqual('migrations/include1.yml', filePath)
     mockFile.read = Mock(return_value=mockIncludedYaml)
   return mockFile
开发者ID:rhyolight,项目名称:liquipy,代码行数:10,代码来源:liquibasedb_test.py

示例3: test_run

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_run(self, mock_execute):
        # Ensure execute returns a sensible result
        result = Mock()
        result.read = Mock(return_value=json.dumps({'result': 'ok'}))
        mock_execute.return_value = result

        # Invoke run
        self.session.run('foo/bar')
        self.assertTrue(mock_execute.called)

        # Sanity check
        self.assertTrue(self.session.access_token is not None)

        # Verify call args
        args = mock_execute.call_args[0]
        self.assertEqual(args[0], 'foo/bar')
        self.assertEqual(args[1], None)
        self.assertTrue(args[2].has_key('User-Agent'))
        self.assertTrue(args[2].has_key('Authorization'))

        # Invoke run
        data = {'one': 1}
        headers = {'two': 2}
        self.session.run('foo/bar', data, headers)
        self.assertTrue(mock_execute.called)

        args = mock_execute.call_args[0]
        self.assertEqual(args[0], 'foo/bar')
        self.assertEqual(args[1], data)
        self.assertTrue(args[2].has_key('two'))

        # Unset asset_token and verify that the 'Authorization'
        # header is not added to the request.
        self.session.access_token = None
        self.session.auth = None

        self.session.run('foo/bar')
        self.assertTrue(mock_execute.called)

        args = mock_execute.call_args[0]
        self.assertFalse(args[2].has_key('Authorization'))

        # Verify that the run method will retry if execute returns
        # an expired_token response.
        result.read = Mock(return_value=json.dumps({'error': 'expired_token'}))
        mock_execute.return_value = result

        with patch.object(Session, 'renew_access_token') as mock_renew_access_token:
            self.session.run('foo/bar')
            self.assertTrue(mock_renew_access_token.called)
开发者ID:geoloqi,项目名称:geoloqi-python,代码行数:52,代码来源:tests.py

示例4: testFlickrWrapperGetUrls

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def testFlickrWrapperGetUrls(self, mock_urlopen):
        response = {'photos': {'photo': [
            {'id': 'id1', 'secret': 'secret1', 'server': 'server1', 'farm': 1},
            {'id': 'id2', 'secret': 'secret2', 'server': 'server2', 'farm': 2}
        ]}}
        response = json.dumps(response)

        m = Mock()
        m.read = Mock(return_value=response)
        mock_urlopen.return_value = m

        api_key = 'key'
        tag = 'tag'
        wrapper = FlickrWrapper(api_key)
        result = wrapper.get_urls(tag)

        self.assertEqual(2, len(result))

        self.assertTrue('farm1' in result[0])
        self.assertTrue('id1' in result[0])
        self.assertTrue('secret1' in result[0])
        self.assertTrue('server1' in result[0])

        self.assertTrue('farm2' in result[1])
        self.assertTrue('id2' in result[1])
        self.assertTrue('secret2' in result[1])
        self.assertTrue('server2' in result[1])
开发者ID:oscarlorentzon,项目名称:repstruct,代码行数:29,代码来源:test_flickrwrapper.py

示例5: test_should_not_update_state_if_unaavailable

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_should_not_update_state_if_unaavailable(self):
        # Set
        app = NewrelicApp('1111','777')
        headers = {"X-Api-Key":'1111'}
        url     ='/v2/applications/777.json'

        # Mocks
        connection_obj         = Mock()
        response_obj           = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status        = 500 # Error
        response_obj.read          = Mock(return_value='')
        connection_obj.connect     = Mock()
        connection_obj.request     = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with('GET', url, '', headers)
        connection_obj.getresponse.assert_called_once()

        self.assertFalse(app.reachable)
开发者ID:viniciusferreira,项目名称:newrelic-indicator,代码行数:27,代码来源:newrelic_app_test.py

示例6: test_retrieve_of_json_data_from_api

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_retrieve_of_json_data_from_api(self):
        json_response = json.dumps({"steps": ["step 1", "step 2"]})
        response_mock = Mock()
        response_mock.read = Mock(return_value=json_response)
        self.cache.get_authorized_response = Mock(return_value=response_mock)

        self.assertListEqual(self.cache.get_steps_information(), ["step 1", "step 2"])
开发者ID:kitaka,项目名称:prioritizer,代码行数:9,代码来源:test_steps_cache.py

示例7: test_not_validated_returned

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_not_validated_returned(self, mock_open):
        document = {}
        message = 'hello'
        key_path = '/etc/pki/pulp/consumer/server/rsa_pub.pem'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))


        test_conf = {'server': {'rsa_pub': key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test
        try:
            patcher = patch('pulp.agent.gofer.pulpplugin.RSA')
            rsa = patcher.start()
            rsa.load_pub_key_bio.return_value.verify.return_value = False
            authenticator = self.plugin.Authenticator()
            self.assertRaises(
                ValidationFailed, authenticator.validate, document, message, key.sign(message))
        finally:
            if patcher:
                patcher.stop()

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
开发者ID:beav,项目名称:pulp,代码行数:31,代码来源:test_agent.py

示例8: test_load_data

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_load_data(self):
        cached = {"prod1": "Product 1", "prod2": "Product 2"}
        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(cached))

        data = self.mgr._load_data(mock_file)
        self.assertEquals(data, cached)
开发者ID:jaredjennings,项目名称:subscription-manager,代码行数:9,代码来源:test_cache.py

示例9: test_crawl

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
def test_crawl():
    html =\
    """<html>
        <head>
            <title>Python is fun!</title>
        </head>
        <body>
            <div>Python is similar to Ruby, but different.</div>
        </body>
    </html>"""

    response_mock = Mock(url="http://expanded_url.com")
    response_mock.read = Mock(return_value=html)
    urllib2.urlopen = Mock(return_value=response_mock)
    url = "http://a.com"

    input_queue = Mock()
    input_queue.get = Mock(return_value=url)
    output_queue = Queue()

    crawler = Crawler()

    crawler.crawl(input_queue, output_queue)

    expected_result = {'CONTENT': html,
                       'EXPANDED_URL': 'http://expanded_url.com',
                       'STATUS': 'OK',
                       'URL': 'http://a.com'}

    eq_(expected_result, output_queue.get())
开发者ID:ashpool,项目名称:ketchlip,代码行数:32,代码来源:crawler_test.py

示例10: _mock_pkg_profile

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def _mock_pkg_profile(packages, repo_file, enabled_modules):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_rpm_profile = RPMProfile(from_file=mock_file)

        mock_enabled_repos_profile = EnabledReposProfile(repo_file=repo_file)

        mock_module_profile = ModulesProfile()
        mock_module_profile.collect = Mock(return_value=enabled_modules)

        mock_profile = {
            "rpm": mock_rpm_profile,
            "enabled_repos": mock_enabled_repos_profile,
            "modulemd": mock_module_profile
        }
        return mock_profile
开发者ID:Januson,项目名称:subscription-manager,代码行数:27,代码来源:test_cache.py

示例11: create_file_context_manager

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
 def create_file_context_manager(*args, **kwargs):
     path = args[0]
     file_mock = Mock()
     file_mock.read = Mock(return_value=file_map[path])
     cm = Mock()
     cm.__enter__ = Mock(return_value=file_mock)
     cm.__exit__ = Mock()
     return cm
开发者ID:gitashutosh,项目名称:infi.storagemodel,代码行数:10,代码来源:test_sysfs.py

示例12: test_getNode

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_getNode(self):
        """

        @return:
        """
        uri = "vos://foo.com!vospace/bar"

        nodes = (' <vos:nodes>\n'
                 '<vos:node uri="vos://cadc.nrc.ca!vospace/mydir/file123" '
                 'xs:type="vos:DataNode">\n'
                 '   <vos:properties>\n'
                 '       <vos:property '
                 'uri="ivo://ivoa.net/vospace/core#date">2016-05-10T09:52:13'
                 '</vos:property>\n'
                 '   </vos:properties>\n'
                 '</vos:node>\n'
                 '<vos:node uri="vos://cadc.nrc.ca!vospace/mydir/file456" '
                 'xs:type="vos:DataNode">\n'
                 '   <vos:properties>\n'
                 '       <vos:property uri="ivo://ivoa.net/vospace/core#date">'
                 '2016-05-19T09:52:14</vos:property>\n'
                 '   </vos:properties>\n'
                 '</vos:node>\n'
                 '</vos:nodes>\n')

        mock_vofile = Mock()
        client = Client()
        client.open = Mock(return_value=mock_vofile)

        mock_vofile.read = Mock(
            return_value=NODE_XML.format(uri, '').encode('UTF-8'))
        my_node = client.get_node(uri, limit=0, force=False)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 0)

        mock_vofile.read = Mock(
            return_value=NODE_XML.format(uri, nodes).encode('UTF-8'))

        my_node = client.get_node(uri, limit=2, force=True)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 2)

        my_node = client.get_node(uri, limit=2, force=False)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 2)
开发者ID:canfar,项目名称:vos,代码行数:47,代码来源:test_vos.py

示例13: empty_sagemaker_session

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
def empty_sagemaker_session():
    ims = Mock(name='sagemaker_session')
    ims.default_bucket = Mock(name='default_bucket', return_value=BUCKET_NAME)
    ims.sagemaker_runtime_client = Mock(name='sagemaker_runtime')

    response_body = Mock('body')
    response_body.read = Mock('read', return_value=RETURN_VALUE)
    response_body.close = Mock('close', return_value=None)
    ims.sagemaker_runtime_client.invoke_endpoint = Mock(name='invoke_endpoint', return_value={'Body': response_body})
    return ims
开发者ID:cheesama,项目名称:sagemaker-python-sdk,代码行数:12,代码来源:test_predictor.py

示例14: test_call_helper

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
 def test_call_helper(self, transport):
     getresponse_mock = Mock()
     transport.return_value = getresponse_mock
     read_mock = Mock()
     read_mock.read = Mock(return_value='data!')
     getresponse_mock.getresponse = Mock(return_value=read_mock)
     s = HttpLibHttpService('host', 42, 'path')
     r = s._call('body', {})
     self.assertIsInstance(r, tuple)
     self.assertEqual(len(r), 3)
开发者ID:storecast,项目名称:holon,代码行数:12,代码来源:tests.py

示例15: test_load_data

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import read [as 别名]
    def test_load_data(self):
        cached = {
                'prod1': 'Product 1',
                'prod2': 'Product 2'
        }
        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(cached))

        data = self.mgr._load_data(mock_file)
        self.assertEquals(data, cached)
开发者ID:NehaRawat,项目名称:subscription-manager,代码行数:12,代码来源:test_cache.py


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