Facilitate for multiple hooks

This commit is contained in:
Johannes Gorset
2012-01-21 12:05:59 +01:00
parent 5bff8e362f
commit 7647e52943
2 changed files with 68 additions and 4 deletions
+9 -4
View File
@@ -31,10 +31,15 @@ def dispatch_hook(key, hooks, hook_data):
hooks = hooks or dict()
if key in hooks:
try:
return hooks.get(key).__call__(hook_data) or hook_data
hooks = hooks.get(key)
except Exception:
traceback.print_exc()
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
try:
hook_data = hook(hook_data) or hook_data
except Exception:
traceback.print_exc()
return hook_data
+59
View File
@@ -516,6 +516,65 @@ class RequestsTestSuite(unittest.TestCase):
self.assertEqual(r2.status_code, 200)
def test_single_hook(self):
def add_foo_header(args):
if not args.get('headers'):
args['headers'] = {}
args['headers'].update({
'X-Foo': 'foo'
})
return args
for service in SERVICES:
url = service('headers')
response = requests.get(
url = url,
hooks = {
'args': add_foo_header
}
)
assert 'foo' in response.content
def test_multiple_hooks(self):
def add_foo_header(args):
if not args.get('headers'):
args['headers'] = {}
args['headers'].update({
'X-Foo': 'foo'
})
return args
def add_bar_header(args):
if not args.get('headers'):
args['headers'] = {}
args['headers'].update({
'X-Bar': 'bar'
})
return args
for service in SERVICES:
url = service('headers')
response = requests.get(
url = url,
hooks = {
'args': [add_foo_header, add_bar_header]
}
)
assert 'foo' in response.content
assert 'bar' in response.content
def test_session_persistent_cookies(self):
s = requests.session()