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


Python Mock.content方法代码示例

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


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

示例1: test_get_product_get_image

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def test_get_product_get_image(self, requests_mock):
        response_mock = Mock()
        response_mock.status_code = 200
        response_mock.content = json.dumps({'id': 991, 'name': 'test prod'})
        requests_mock.get.return_value = response_mock
        cli = APIClient('test_api_key', 'test user agent')
        p = ProductResource(cli, '46')


        res = p.get(991)

        self.assertEqual(991, res.id)

        requests_mock.get.assert_called_with(
            url='https://api.tiendanube.com/v1/46/products/991',
            headers={'Authentication': 'bearer test_api_key', 'User-Agent': 'test user agent'},
            params=None
        )
        response_mock.content = json.dumps({'id': 1, 'name': 'test prod image'})
        res = res.images.get(1)
        self.assertEqual(bunchify({'id': 1, 'name': 'test prod image'}), res)

        requests_mock.get.assert_called_with(
            url='https://api.tiendanube.com/v1/46/products/991/images/1',
            headers={'Authentication': 'bearer test_api_key', 'User-Agent': 'test user agent'},
            params=None
        )
开发者ID:AndresOsinski,项目名称:tiendanube-python,代码行数:29,代码来源:resources.py

示例2: test_validate_package

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def test_validate_package(self):
        maint = self.get_maintainer()
        pack = Package(filename='foo',
                       name='bar_2go',
                       package_format='1',
                       version='0.0.0',
                       description='pdesc',
                       licenses=['BSD'],
                       maintainers=[maint])
        pack.validate()
        # check invalid names
        pack.name = '2bar'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.name = 'bar bza'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.name = 'BAR'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # dashes should be acceptable in packages other than catkin or
        # ament*.
        # no build_type, so catkin is assumed per REP-140.
        pack.name = 'bar-bza'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # check explicit catkin and ament_* build_types
        build_type = Mock(tagname='build_type', attributes={}, content='catkin')
        pack.exports = [build_type]
        self.assertRaises(InvalidPackage, Package.validate, pack)
        build_type.content = 'ament_cmake'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        build_type.content = 'ament_python'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # check non ament/catkin build type is valid
        build_type.content = 'cmake'
        pack.validate()
        # check authors emails
        pack.name = 'bar'
        auth1 = Mock()
        auth2 = Mock()
        auth2.validate.side_effect = InvalidPackage('foo')
        pack.authors = [auth1, auth2]
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.authors = []
        pack.validate()
        # check maintainer required with email
        pack.maintainers = []
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.maintainers = [maint]
        maint.email = None
        self.assertRaises(InvalidPackage, Package.validate, pack)
        maint.email = '[email protected]'

        for dep_type in [
                pack.build_depends, pack.buildtool_depends,
                pack.build_export_depends, pack.buildtool_export_depends,
                pack.exec_depends, pack.test_depends, pack.doc_depends]:
            pack.validate()
            depend = Dependency(pack.name)
            dep_type.append(depend)
            self.assertRaises(InvalidPackage, Package.validate, pack)
            dep_type.remove(depend)
开发者ID:esteve,项目名称:ament_package,代码行数:61,代码来源:test_package.py

示例3: __init__

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def __init__(self):
     ticket_mock = Mock()
     ticket_mock.content = json.dumps(_get_ticket('Test'))
     ticket_mock.status_code = 200
     child_mock = Mock()
     child_mock.content = json.dumps([_get_ticket('Child'),
                                      _get_ticket('Child2')])
     child_mock.status_code = 200
     self.mocks = [ticket_mock, child_mock]
开发者ID:OddBloke,项目名称:centipede,代码行数:11,代码来源:test_views.py

示例4: mock_response

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
def mock_response(fixture=None, status=200):
    response = Mock()
    if fixture is None:
        response.content = ''
    elif isinstance(fixture, dict):
        response.content = str(fixture)
    else:
        response.content = load_fixture(fixture)
    response.status_code = status
    return response
开发者ID:iviamontes,项目名称:autojenkins,代码行数:12,代码来源:test_unit_jobs.py

示例5: inner

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def inner(status_code=200, response_ok=True, response=None, content=None):
     mock_box_response = Mock(BoxResponse)
     mock_network_response = Mock(DefaultNetworkResponse)
     mock_box_response.network_response = mock_network_response
     mock_box_response.status_code = status_code
     mock_box_response.ok = response_ok
     if response is not None:
         mock_box_response.json.return_value = response
         mock_box_response.content = json.dumps(response).encode()
     else:
         mock_box_response.content = content
     return mock_box_response, mock_network_response
开发者ID:vallamsetty,项目名称:DIOTools,代码行数:14,代码来源:conftest.py

示例6: side_effect

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def side_effect(*args, **kwargs):
     response = Mock()
     data = json.loads(kwargs.get('data', "{}"))
     for param in required_post_params:
         if param not in data:
             response.status_code = 400
             response.content = '%r is required'
             return response
         
     response.status_code = 200
     response.content = json.dumps({'s':1})
     return response
开发者ID:tbarbugli,项目名称:python-transifex,代码行数:14,代码来源:api.py

示例7: test_internal_message_list

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def test_internal_message_list(self):
        msg = {
            "status": "queued",
            "messages": []
        }

        response = Mock()
        response.status_code = 200
        response.content = json.dumps(msg)

        self.mock_requests.request.return_value = response

        lbh = LogBookHandler('uuid')

        # The logbook starts off with no messages
        eq_(0, len(lbh.messages))

        msg['messages'].append(
        {
            "asctime": "2012-02-08T11:15:04",
            "message": "message1",
        })

        response.content = json.dumps(msg)
        self.mock_requests.request.return_value = response

        new_msg = lbh.fetch()

        # The logbook has one message now
        eq_(1, len(lbh.messages))
        eq_(new_msg, lbh.messages)

        messages = [
        {
            "asctime": "2012-02-08T11:15:05",
            "message": "message2",
        },
        {
            "asctime": "2012-02-08T11:15:06",
            "message": "message3",
        }]

        msg['messages'].extend(messages)

        response.content = json.dumps(msg)
        self.mock_requests.request.return_value = response

        new_msg = lbh.fetch()

        # The logbook has one message now
        eq_(3, len(lbh.messages))
        eq_(new_msg, messages)
开发者ID:30loops,项目名称:libthirty,代码行数:54,代码来源:tests.py

示例8: setUp

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def setUp(self):
     response = Mock()
     response.content = self.response_body
     response.status_code = 200
     with patch('requests.post') as post:
         post.return_value = response
         self.perform_action()
开发者ID:Lacrymology,项目名称:django-oscar-paypal,代码行数:9,代码来源:facade_tests.py

示例9: request

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def request(*args, **kwargs):
     response = Mock()
     response.status_code = status
     if fixture:
         fixture_path = os.path.join(FIXTURES, fixture)
         response.content = open(fixture_path).read()
     return response
开发者ID:kindrid,项目名称:python-intercom,代码行数:9,代码来源:__init__.py

示例10: it_can_fetch_resources_from_a_remote_endpoint

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def it_can_fetch_resources_from_a_remote_endpoint(self):
        mock_resp = Mock(name="mock_response")
        expected = {'id': 1}
        mock_resp.content = json.dumps(expected)
        mock_resp.status_code = 200

        self.mock_request.get.return_value = mock_resp

        manager = BackendManager('http')

        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = 'http'

            def uri(self):
                return 'http://location'

        doc = Doc({'id': 1})

        # the http manager returns the response as python dict
        content = manager.fetch(doc)

        # make sure we are working with correct expectations
        eq_(HttpBackendManager, type(manager))
        eq_(mock_resp, manager.response)
        ok_(isinstance(content, dict))
        eq_([('get', {'url': doc.uri()})],
                self.mock_request.method_calls)
开发者ID:30loops,项目名称:python-docar,代码行数:32,代码来源:http_backend_tests.py

示例11: setUp

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def setUp(self):
        # mock request object
        request = Request()
        request.method = 'GET'
        request.url = 'http://example.com/'
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock response object
        response = Mock()
        response.content = 'access_token=321'
        response.headers = {'content-type': 'text/html; charset=UTF-8'}
        response.ok = True
        response.status_code = 200
        self.response = response

        # mock raise_for_status with an error
        def raise_for_status():
            raise Exception('Response not OK!')

        self.raise_for_status = raise_for_status

        # mock hook object
        hook = Mock()
        hook.consumer_key = '123'
        hook.consumer_secret = '456'
        hook.access_token = '321'
        hook.access_token_secret = '654'
        self.hook = hook
开发者ID:appsforartists,项目名称:rauth,代码行数:33,代码来源:base.py

示例12: test_list_objects_with_invalid_content_length

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
 def test_list_objects_with_invalid_content_length(self):
     http_response = Mock()
     http_response.encoding = 'utf-8'
     http_response.headers = CaseInsensitiveDict(
         {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
          # We say we have 265 bytes but we're returning 0,
          # this should raise an exception because this is not
          # a HEAD request.
          'Content-Length': '265',
          'x-amz-request-id': '2B74ECB010FF029E',
          'ETag': '"40d06eb6194712ac1c915783004ef730"',
          'Server': 'AmazonS3',
          'content-type': 'binary/octet-stream',
          'Content-Type': 'binary/octet-stream',
          'accept-ranges': 'bytes',
          'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
          'x-amz-server-side-encryption': 'AES256'
          })
     http_response.content = ''
     http_response.request.method = 'GET'
     list_objects = self.s3.get_operation('ListObjects')
     expected = {"AcceptRanges": "bytes",
                 "ContentType": "binary/octet-stream",
                 "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
                 "ContentLength": "265",
                 "ETag": '"40d06eb6194712ac1c915783004ef730"',
                 "ServerSideEncryption": "AES256"
                 }
     with self.assertRaises(IncompleteReadError):
         response_data = get_response(self.session, list_objects,
                                      http_response)[1]
开发者ID:ainoya,项目名称:botocore,代码行数:33,代码来源:test_response_parsing.py

示例13: test_unexpected_response_without_error_message

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

        response = Mock()
        response.status_code = 422
        response.content = 'no processable response'
        exception = UnexpectedResponse(response)
        self.assertEqual("%s" % exception, "Unexpected response from server (422 error code)")
开发者ID:GreenIDer-Donati,项目名称:wirecloud,代码行数:9,代码来源:store.py

示例14: build_response_mock

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
def build_response_mock(status_code, json_body=None, headers=None,
                        add_content_length=True, **kwargs):
    real_response = requests.Response()
    real_response.status_code = status_code

    text = None
    if json_body is not None:
        text = json.dumps(json_body)
        if add_content_length and headers is not {}:
            real_response.headers['content-length'] = len(text)

    if headers is not None:
        for k, v in headers.items():
            real_response.headers[k] = v

    for k, v in kwargs.items():
        setattr(real_response, k, v)

    response = Mock(wraps=real_response, autospec=True)
    if text:
        response.text = text

    # for some reason, wraps cannot handle attributes which are dicts
    # and accessed by key
    response.headers = real_response.headers
    response.content = text

    return response
开发者ID:openstack,项目名称:python-jenkins,代码行数:30,代码来源:helper.py

示例15: test_success

# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import content [as 别名]
    def test_success(self):
        # Setting up valid ticket
        valid_ticket = "valid_ticket"
        LoginEmailSentCertified(ticket=valid_ticket).put()

        # setting user data return
        rpc = Mock()
        result = Mock()
        result.status_code = 200
        result.content = '{"id":"123456","email":"[email protected]"}'
        rpc.get_result = Mock(return_value=result)
        pswdless.urlfetch.create_rpc = Mock(return_value=rpc)
        fetch = Mock()
        pswdless.urlfetch.make_fetch_call = fetch
        post_params = {"app_id": "1", "token": "2", "ticket": valid_ticket}
        url_detail = "https://pswdless.appspot.com/rest/detail"
        params = {"url_detail": url_detail}
        params.update(post_params)
        response = Mock()
        response.set_cookie = Mock()
        cmd = LogUserIn(cookie_name="user", response=response, **params)
        cmd.execute()
        self.assertDictEqual({"id": "123456", "email": "[email protected]"}, cmd.result)
        fetch.assert_called_once_with(
            rpc, url_detail, urllib.urlencode(post_params), method=urlfetch.POST, validate_certificate=True
        )
        self.assertIsNone(LoginEmailSentCertified.find_by_ticket(valid_ticket).get())
        response.set_cookie.assert_called_once_with("user", cmd._signed, httponly=True)
开发者ID:renzon,项目名称:pswdclient,代码行数:30,代码来源:pswdless_tests.py


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