本文整理汇总了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
示例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
示例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")
示例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'))
示例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']")
示例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)
示例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/")
示例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)
示例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)
示例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)
示例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)
示例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)
示例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
)
示例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
示例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')