I'm using decorators to validate parameters arriving to my function (via a dictionary object), when I have 2 keys or more it works fine. But if I have only key it returns an error (check_person). I defined 2 functions to exemplify my problem:
def required(**mandatory):
"""
:param mandatory:
:return:
"""
def decorator(f):
@wraps(f)
def wrapper(**dicts):
for argname, d in dicts.items():
for key in mandatory.get(argname, []):
if key not in d:
raise Exception('Key "%s" is missing from argument "%s"' % (key, argname))
return f(**dicts)
return wrapper
return decorator
@required(json_request=(_PROVIDER, _REPORT))
def check_campaign(json_request):
"""
:param json_request:
:return:
"""
return True
@required(json_request=(_NAME))
def check_person(json_request=None):
"""
:param json_request:
:return:
"""
return True
I need to change check_person to:
if _NAME in json_request:
return True
return False
To make it work.
When I try:
self.assertTrue(validator.check_person(json_request=json.loads("""{"name": "Elon Musk"}""")))
or specifically:
{"name": "Elon Musk"}
I get:
Error
Traceback (most recent call last):
File "/Users/spicyramen/Documents/OpenSource/Development/Python/gonzo/utils/validate/validator_test.py", line 46, in test_person
self.assertTrue(validator.check_person(json_request=json.loads("""{"name": "Elon Musk"}""")))
File "/Users/spicyramen/Documents/OpenSource/Development/Python/gonzo/utils/validate/validator.py", line 26, in wrapper
raise Exception('Key "%s" is missing from argument "%s"' % (key, argname))
Exception: Key "n" is missing from argument "json_request"
When my dictionary has more than 1 key it works fine (Like check_campaign).