Only register callable items in lists
authorIan Cordasco <graffatcolmingov@gmail.com>
Mon, 1 Oct 2012 17:09:02 +0000 (13:09 -0400)
committerRadu Voicilas <radu.voicilas@gmail.com>
Mon, 8 Oct 2012 21:42:49 +0000 (00:42 +0300)
Prior to this, you could sneak a list of anything to register_hook and it
would accept it. This will check if the items in the list are callable before
registering them. Also added a regression test to make sure if this gets
changed it will be noticed.

requests/models.py
tests/test_requests.py

index 2193c6e55b86ef7c4c6e35085426992dde68a089..78311491cd1d873896235d2dd0a618a54882a441 100644 (file)
@@ -462,10 +462,10 @@ class Request(object):
 
     def register_hook(self, event, hook):
         """Properly register a hook."""
-        if isinstance(hook, (list, tuple, set)):
-            self.hooks[event].extend(hook)
-        else:
+        if callable(hook):
             self.hooks[event].append(hook)
+        elif hasattr(hook, '__iter__'):
+            self.hooks[event].extend(h for h in hook if callable(h))
 
     def deregister_hook(self, event, hook):
         """Deregister a previously registered hook.
index 0f67618a89a7931da43fbbf64f0277c5a729c5f7..3d6f49c29392a9036274b1761b892c8ef9ca1a57 100755 (executable)
@@ -778,6 +778,10 @@ class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):
         r = requests.models.Request(hooks={'args': hooks})
         assert_hooks_are_callable(r.hooks)
 
+        hooks.append('string that should not be registered')
+        r = requests.models.Request(hooks={'args': hooks})
+        assert_hooks_are_callable(r.hooks)
+
     def test_session_persistent_cookies(self):
 
         s = requests.session()