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


Python MagicMock.headers方法代码示例

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


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

示例1: make_cookies

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
    def make_cookies(*args, **kwargs):
        cookies = kwargs['cookies']
        r = MagicMock()
        try:
            r.headers = HTTPMessage()
            add_header = r.headers.add_header
        except TypeError:
            # PY2
            r.headers = HTTPMessage(StringIO())
            add_header = r.headers.addheader
        r.info.return_value = r.headers
        for name, value in (('Foo', 'bar'), ('Baz', 'qux')):
            cookie = Cookie(
                version=0,
                name=name,
                value=value,
                port=None,
                port_specified=False,
                domain="ansible.com",
                domain_specified=True,
                domain_initial_dot=False,
                path="/",
                path_specified=True,
                secure=False,
                expires=None,
                discard=False,
                comment=None,
                comment_url=None,
                rest=None
            )
            cookies.set_cookie(cookie)
            add_header('Set-Cookie', '%s=%s' % (name, value))

        return r
开发者ID:awiddersheim,项目名称:ansible,代码行数:36,代码来源:test_fetch_url.py

示例2: create_mock_response

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [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
开发者ID:thomasyu888,项目名称:synapsePythonClient,代码行数:35,代码来源:unit_test_download.py

示例3: test_get_request_location_history

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
def test_get_request_location_history():
    """
    Request location follows redirect history.
    """
    url = "http://pypi.python.org/simple/foo"

    redirect = MagicMock()
    redirect.headers = {"location": "https://pypi.python.org/simple/foo"}

    response = MagicMock()
    response.history = [redirect]
    response.headers = {}
    eq_(get_request_location(response, url), "https://pypi.python.org/simple/foo")
开发者ID:jessemyers,项目名称:cheddar,代码行数:15,代码来源:test_remote.py

示例4: test_admin_token

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
    def test_admin_token(self, cfg):
        req = MagicMock()
        req.headers = {'X-AUTH-TOKEN': 'ADMIN'}
        resp = MagicMock()
        cfg.CONF = {'DEFAULT': {'admin_token': 'ADMIN'}}

        admin_token(req, resp, {})
        self.assertTrue(req.env['is_admin'])

        req.headers = {'X-AUTH-TOKEN': 'ABC'}
        req.env = {}
        admin_token(req, resp, {})
        self.assertIsNone(req.env.get('is_admin'))
开发者ID:ajiang38740,项目名称:jumpgate,代码行数:15,代码来源:test_hooks.py

示例5: test_parameter_validator

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
def test_parameter_validator(monkeypatch):
    request = MagicMock(name='request')
    request.args = {}
    request.headers = {}
    request.params = {}
    app = MagicMock(name='app')
    app.response_class = lambda a, mimetype, status: json.loads(''.join(a))['detail']
    monkeypatch.setattr('flask.request', request)
    monkeypatch.setattr('flask.current_app', app)

    def orig_handler(*args, **kwargs):
        return 'OK'

    params = [{'name': 'p1', 'in': 'path', 'type': 'integer', 'required': True},
              {'name': 'h1', 'in': 'header', 'type': 'string', 'enum': ['a', 'b']},
              {'name': 'q1', 'in': 'query', 'type': 'integer', 'maximum': 3},
              {'name': 'a1', 'in': 'query', 'type': 'array', 'minItems': 2, 'maxItems': 3,
               'items': {'type': 'integer', 'minimum': 0}}]
    validator = ParameterValidator(params)
    handler = validator(orig_handler)

    assert handler() == "Missing path parameter 'p1'"
    assert handler(p1='123') == 'OK'
    assert handler(p1='') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='foo') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='1.2') == "Wrong type, expected 'integer' for path parameter 'p1'"

    request.args = {'q1': '4'}
    assert handler(p1=1).startswith('4 is greater than the maximum of 3')
    request.args = {'q1': '3'}
    assert handler(p1=1) == 'OK'

    request.args = {'a1': "1,2"}
    assert handler(p1=1) == "OK"
    request.args = {'a1': "1,a"}
    assert handler(p1=1).startswith("'a' is not of type 'integer'")
    request.args = {'a1': "1,-1"}
    assert handler(p1=1).startswith("-1 is less than the minimum of 0")
    request.args = {'a1': "1"}
    assert handler(p1=1).startswith("[1] is too short")
    request.args = {'a1': "1,2,3,4"}
    assert handler(p1=1).startswith("[1, 2, 3, 4] is too long")
    del request.args['a1']

    request.headers = {'h1': 'a'}
    assert handler(p1='123') == 'OK'

    request.headers = {'h1': 'x'}
    assert handler(p1='123').startswith("'x' is not one of ['a', 'b']")
开发者ID:rafaelcaricio,项目名称:connexion,代码行数:51,代码来源:test_validation.py

示例6: test_negative_skew

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
 def test_negative_skew(self):
     now = datetime.datetime.utcnow() + datetime.timedelta(minutes=-11)
     now_str = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
     response = MagicMock()
     response.headers = {'Date': now_str}
     with self.assertRaises(ClockSkew):
         ClockSkewHook().post_request('POST', 'http://example.com', {}, response)
开发者ID:Backblaze,项目名称:B2_Command_Line_Tool,代码行数:9,代码来源:test_b2http.py

示例7: test_get_request_location_multiple_history

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
def test_get_request_location_multiple_history():
    """
    Request location follows redirect history across multiple redirects.
    """
    url = "http://pypi.python.org/simple/foo"

    redirect1 = MagicMock()
    redirect1.headers = {"location": "https://pypi.python.org/simple/foo"}

    redirect2 = MagicMock()
    redirect2.headers = {"location": "https://pypi.python.org/simple/foo/"}

    response = MagicMock()
    response.history = [redirect1, redirect2]
    response.headers = {}
    eq_(get_request_location(response, url), "https://pypi.python.org/simple/foo/")
开发者ID:jessemyers,项目名称:cheddar,代码行数:18,代码来源:test_remote.py

示例8: test_verify_oauth_scopes_local

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
def test_verify_oauth_scopes_local(monkeypatch):
    tokeninfo = dict(uid="foo", scope="scope1 scope2")

    def func(request):
        pass

    def token_info(token):
        return tokeninfo

    wrapped_func = verify_oauth_local(token_info, set(['admin']), func)

    request = MagicMock()
    request.headers = {"Authorization": "Bearer 123"}
    app = MagicMock()
    monkeypatch.setattr('flask.current_app', app)

    with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
        wrapped_func(request)

    tokeninfo["scope"] += " admin"
    wrapped_func(request)

    tokeninfo["scope"] = ["foo", "bar"]
    with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
        wrapped_func(request)

    tokeninfo["scope"].append("admin")
    wrapped_func(request)
开发者ID:liamdiprose,项目名称:connexion,代码行数:30,代码来源:test_security.py

示例9: test_verify_oauth_scopes_remote

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
def test_verify_oauth_scopes_remote(monkeypatch):
    tokeninfo = dict(uid="foo", scope="scope1 scope2")

    def get_tokeninfo_response(*args, **kwargs):
        tokeninfo_response = requests.Response()
        tokeninfo_response.status_code = requests.codes.ok
        tokeninfo_response._content = json.dumps(tokeninfo).encode()
        return tokeninfo_response

    def func(request):
        pass

    wrapped_func = verify_oauth_remote('https://example.org/tokeninfo', set(['admin']), func)

    request = MagicMock()
    request.headers = {"Authorization": "Bearer 123"}
    app = MagicMock()
    monkeypatch.setattr('flask.current_app', app)

    session = MagicMock()
    session.get = get_tokeninfo_response
    monkeypatch.setattr('connexion.decorators.security.session', session)

    with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
        wrapped_func(request)

    tokeninfo["scope"] += " admin"
    wrapped_func(request)

    tokeninfo["scope"] = ["foo", "bar"]
    with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
        wrapped_func(request)

    tokeninfo["scope"].append("admin")
    wrapped_func(request)
开发者ID:liamdiprose,项目名称:connexion,代码行数:37,代码来源:test_security.py

示例10: test_handle_response

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
    def test_handle_response(self):
        connection = Connection('store.mybigcommerce.com', ('user', 'abcdef'))
        # A normal, 200-ok response
        data = {
            'name': 'Shirt'
        }
        res = MagicMock()
        res.headers = {'Content-Type': 'application/json'}
        res.status_code = 200
        res.content = json.dumps(data)
        res.json.return_value = data
        self.assertEqual(connection._handle_response('products/1', res), data)

        res.status_code = 500
        self.assertRaisesHttpException(ServerException,
                                       lambda: connection._handle_response('products/1', res),
                                       # Test all of the properties of a HttpException
                                       500,
                                       {'Content-Type': 'application/json'},
                                       json.dumps(data))

        res.status_code = 404
        self.assertRaisesHttpException(ClientRequestException,
                                       lambda: connection._handle_response('products/1', res), 404)

        res.status_code = 301
        self.assertRaisesHttpException(RedirectionException,
                                       lambda: connection._handle_response('products/1', res), 301)
开发者ID:MUDASSARHASHMI,项目名称:bigcommerce-api-python,代码行数:30,代码来源:test_connection.py

示例11: test_notification_rate_limit2

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
 def test_notification_rate_limit2(self, mock_retry, mock_summ, mock_delay,
                                   verify_signature_mock, debug_mock):
     """ Test that the notification task rate limit errors ok """
     # Check that we fail gracefully when we hit the rate limit
     mock_delay.side_effect = lambda arg: process_notification(arg)
     resp = MagicMock()
     resp.headers = {'x-ratelimit-reset': 1404298869}
     exc = misfit_exceptions.MisfitRateLimitError(429, '', resp)
     mock_summ.side_effect = exc
     mock_retry.side_effect = Exception
     with HTTMock(JsonMock().goal_http,
                  JsonMock().profile_http,
                  JsonMock('summary_detail').summary_http):
         try:
             content = json.dumps(self.notification_content).encode('utf8')
             self.client.post(reverse('misfit-notification'), data=content,
                              content_type='application/json')
             assert False, 'We should have raised an exception'
         except Exception:
             assert True
     mock_delay.assert_called_once_with(content)
     mock_summ.assert_called_once_with(
         detail=True,
         end_date=datetime.date(2014, 10, 8),
         start_date=datetime.date(2014, 10, 5))
     mock_retry.assert_called_once_with(countdown=549)
     eq_(Goal.objects.filter(user=self.user).count(), 2)
     eq_(Profile.objects.filter(user=self.user).count(), 1)
     eq_(Summary.objects.filter(user=self.user).count(), 0)
开发者ID:orcasgit,项目名称:django-misfit,代码行数:31,代码来源:test_tasks.py

示例12: test_getContextForCollectionMappings_contextRecieved

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
    def test_getContextForCollectionMappings_contextRecieved(self, mock_get):
        mappingResponse = MagicMock(spec=Response)
        collection = ["Some Results"]
        mappingResponse.json.return_value = collection
        mappingResponse.status_code = 200
        mappingResponse.headers = []
        mock_get.return_value = mappingResponse

        collectionMappingsView = views.CollectionMappingsView()
        collectionMappingsView.request = FakeRequest()

        hash = {'collection': 'test', 'org': 'org1'}
        collectionMappingsView.kwargs = hash
        context = collectionMappingsView.get_context_data()

        self.assertEquals(context['url_params'], {})
        self.assertEquals(context['kwargs'], hash)
        self.assertEquals(context['selected_tab'], 'Mappings')
        self.assertEquals(context['results'], collection)
        self.assertEquals(context['pagination_url'], '/foobar')
        self.assertEquals(context['search_query'], '')
        self.assertIsInstance(context['search_filters'], SearchFilterList)
        # TODO: Revise sort assertion to work with new sort option definitions
        # self.assertEquals(context['search_sort_options'], ['Best Match', 'Last Update (Desc)', 'Last Update (Asc)', 'Name (Asc)', 'Name (Desc)'])
        self.assertEquals(context['search_sort'], '')
        self.assertEquals(context['search_facets_json'], None)
开发者ID:snyaggarwal,项目名称:ocl_web,代码行数:28,代码来源:test_views.py

示例13: test_handle_response

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
    def test_handle_response(self):
        connection = Connection("store.mybigcommerce.com", ("user", "abcdef"))
        # A normal, 200-ok response
        data = {"name": "Shirt"}
        res = MagicMock()
        res.headers = {"Content-Type": "application/json"}
        res.status_code = 200
        res.content = json.dumps(data)
        res.json.return_value = data
        self.assertEqual(connection._handle_response("products/1", res), data)

        res.status_code = 500
        self.assertRaisesHttpException(
            ServerException,
            lambda: connection._handle_response("products/1", res),
            # Test all of the properties of a HttpException
            500,
            {"Content-Type": "application/json"},
            json.dumps(data),
        )

        res.status_code = 404
        self.assertRaisesHttpException(
            ClientRequestException, lambda: connection._handle_response("products/1", res), 404
        )

        res.status_code = 301
        self.assertRaisesHttpException(
            RedirectionException, lambda: connection._handle_response("products/1", res), 301
        )
开发者ID:bigcommerce,项目名称:bigcommerce-api-python,代码行数:32,代码来源:test_connection.py

示例14: _mock_response

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
 def _mock_response(self, status_code=404, headers={}, content='PAGE_NOT_FOUND'):
     r = MagicMock(Response())
     r.status_code = status_code
     r.headers = CaseInsensitiveDict(headers if headers is not None else {})
     r.content = content
     r.ok = status_code < 400
     return r
开发者ID:appliedcode,项目名称:vcloudtools,代码行数:9,代码来源:requestmocker.py

示例15: TestCommandParsing

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import headers [as 别名]
 def TestCommandParsing(self):
     request = MagicMock()
     request.path = "/test"
     request.query = "item1=value1"
     request.remote_ip = "1.2.3.4"
     request.method = "PUT"
     request.headers = {
         'User': 'test_user',
         'Creation-Time': 'test_time',
         'User-Agent': 'test_user_agent'
     }
     request.body="item2=value2&item2=value3&item2=value4"
     self.command = Command(request)
     self.assertEqual(self.command.command_name, 'test')
     self.assertEqual(self.command.command_type, 'PUT')
     self.assertEqual(self.command.has_param('item1'), True)
     self.assertEqual(self.command.has_param('item2'), True)
     self.assertEqual(self.command.has_param('item3'), False)
     self.assertEqual(self.command.get_param('item1'), 'value1')
     self.assertEqual('value2' in self.command.get_param('item2'), True)
     self.assertEqual('value3' in self.command.get_param('item2'), True)
     self.assertEqual('value4' in self.command.get_param('item2'), True)
     data = self.command.format_trace
     self.assertEqual(data['Username'], 'test_user')
     self.assertEqual(data['Created'], 'test_time')
     self.assertEqual(data['Source_Address'], '1.2.3.4')
     self.assertEqual(data['Source_ID'], 'test_user_agent')
开发者ID:percival-detector,项目名称:percivalui,代码行数:29,代码来源:test_command.py


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