Avoid indexing into an empty list in getcallargs
If a method signature has no named arguments, either empty or (*args, **kwargs), then inspect.getargspec() will return an empty list for argnames. In that case we should not try to compare against the first element of that list. Also updates the docstring for getcallargs to specify a limitation of the method. Change-Id: I68af587fe91310a68bb5c37b80d3f00f5d45dd16
This commit is contained in:
parent
f9347ebd3a
commit
34e089d229
|
@ -24,6 +24,11 @@ def getcallargs(function, *args, **kwargs):
|
|||
"""This is a simplified inspect.getcallargs (2.7+).
|
||||
|
||||
It should be replaced when python >= 2.7 is standard.
|
||||
|
||||
This method can only properly grab arguments which are passed in as
|
||||
keyword arguments, or given names by the method being called. This means
|
||||
that an *arg in a method signature and any arguments captured by it will
|
||||
be left out of the results.
|
||||
"""
|
||||
keyed_args = {}
|
||||
argnames, varargs, keywords, defaults = inspect.getargspec(function)
|
||||
|
@ -33,7 +38,7 @@ def getcallargs(function, *args, **kwargs):
|
|||
# NOTE(alaski) the implicit 'self' or 'cls' argument shows up in
|
||||
# argnames but not in args or kwargs. Uses 'in' rather than '==' because
|
||||
# some tests use 'self2'.
|
||||
if 'self' in argnames[0] or 'cls' == argnames[0]:
|
||||
if len(argnames) > 0 and ('self' in argnames[0] or 'cls' == argnames[0]):
|
||||
# The function may not actually be a method or have im_self.
|
||||
# Typically seen when it's stubbed with mox.
|
||||
if inspect.ismethod(function) and hasattr(function, 'im_self'):
|
||||
|
|
|
@ -96,3 +96,15 @@ class GetCallArgsTestCase(test.NoDBTestCase):
|
|||
self.assertEqual(3, callargs['red'])
|
||||
self.assertIn('blue', callargs)
|
||||
self.assertIsNone(callargs['blue'])
|
||||
|
||||
def test_no_named_args(self):
|
||||
def _fake(*args, **kwargs):
|
||||
pass
|
||||
|
||||
# This is not captured by getcallargs
|
||||
args = (3,)
|
||||
kwargs = {'instance': {'uuid': 1}}
|
||||
callargs = safe_utils.getcallargs(_fake, *args, **kwargs)
|
||||
self.assertEqual(1, len(callargs))
|
||||
self.assertIn('instance', callargs)
|
||||
self.assertEqual({'uuid': 1}, callargs['instance'])
|
||||
|
|
Loading…
Reference in New Issue