Fix validate_args function in cliutils
Fix validate_args() for more strict validation. Current logic works if only 1 required arg for functions. May fails if more than 1 required args. Refer to bug description for example failure case. Change-Id: Ie9bc54631d431f0933daf74793f0bcca1ba227f7 Closes-Bug: #1555764
This commit is contained in:
parent
d4daeafb34
commit
7dac478026
|
@ -79,7 +79,7 @@ def validate_args(fn, *args, **kwargs):
|
||||||
MissingArgs: Missing argument(s): b, d
|
MissingArgs: Missing argument(s): b, d
|
||||||
|
|
||||||
:param fn: the function to check
|
:param fn: the function to check
|
||||||
:param arg: the positional arguments supplied
|
:param args: the positional arguments supplied
|
||||||
:param kwargs: the keyword arguments supplied
|
:param kwargs: the keyword arguments supplied
|
||||||
"""
|
"""
|
||||||
argspec = inspect.getargspec(fn)
|
argspec = inspect.getargspec(fn)
|
||||||
|
@ -87,14 +87,11 @@ def validate_args(fn, *args, **kwargs):
|
||||||
num_defaults = len(argspec.defaults or [])
|
num_defaults = len(argspec.defaults or [])
|
||||||
required_args = argspec.args[:len(argspec.args) - num_defaults]
|
required_args = argspec.args[:len(argspec.args) - num_defaults]
|
||||||
|
|
||||||
def isbound(method):
|
if getattr(fn, "__self__", None):
|
||||||
return getattr(method, "__self__", None) is not None
|
|
||||||
|
|
||||||
if isbound(fn):
|
|
||||||
required_args.pop(0)
|
required_args.pop(0)
|
||||||
|
|
||||||
missing = [arg for arg in required_args if arg not in kwargs]
|
missing_required_args = required_args[len(args):]
|
||||||
missing = missing[len(args):]
|
missing = [arg for arg in missing_required_args if arg not in kwargs]
|
||||||
if missing:
|
if missing:
|
||||||
raise MissingArgs(missing)
|
raise MissingArgs(missing)
|
||||||
|
|
||||||
|
|
|
@ -421,6 +421,10 @@ class ValidateArgsTest(test.TestCase):
|
||||||
self.assertRaises(cliutils.MissingArgs,
|
self.assertRaises(cliutils.MissingArgs,
|
||||||
self._test_lambda_with_args, y=2)
|
self._test_lambda_with_args, y=2)
|
||||||
|
|
||||||
|
def test_lambda_missing_args4(self):
|
||||||
|
self.assertRaises(cliutils.MissingArgs,
|
||||||
|
self._test_lambda_with_args, 1, x=2)
|
||||||
|
|
||||||
def _test_lambda_with_default(self, *args, **kwargs):
|
def _test_lambda_with_default(self, *args, **kwargs):
|
||||||
cliutils.validate_args(lambda x, y, z=3: None, *args, **kwargs)
|
cliutils.validate_args(lambda x, y, z=3: None, *args, **kwargs)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue