Last active
January 17, 2020 17:38
-
-
Save huangsam/4fc000c1c499abb3e0ae604e0375e189 to your computer and use it in GitHub Desktop.
Testing decorator with parameter(s)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def approve(whitelist): | |
"""Bind whitelist arg to wrapper""" | |
def wrapper(func): | |
"""Bind old func to guard""" | |
def guard(*args, **kwargs): | |
"""Check if 'name' keyword matches whitelist""" | |
name = kwargs.get("name") | |
if name in whitelist: | |
print(f"=== approved {name}") | |
func(*args, **kwargs) | |
return True | |
else: | |
print(f"=== rejected {name}") | |
return False | |
return guard | |
return wrapper | |
@approve(whitelist={"johndoe", "marydoe"}) | |
def hello(name): | |
print(f"Hello {name}") | |
assert hello(name="johndoe") is True | |
assert hello(name="marydoe") is True | |
assert hello(name="foobar") is False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment