How to write test code to evaluate a Python decorator. Please let me know if there is a better way.
With the hoge decorator, 1 is added to the return value.
def hoge(func):
@functools.wraps(func)
def wrapper(n):
return func(n) + 1
return wrapper
@hoge
def sample(n):
return n * 2
if __name__ == '__main__':
assert sample(3) == 7
The decorator itself can be evaluated as follows (ʻANY_VALUE` can be anything):
assert hoge(lambda n: 6)(ANY_VALUE) == 7
The following hoge decorator adds the value specified in the decorator's argument to the return value.
def hoge(m):
def decorator(func):
@functools.wraps(func)
def wrapper(n):
return func(n) + m
return wrapper
return decorator
@hoge(2)
def sample(n):
return n * 2
if __name__ == '__main__':
assert sample(2) == 6
The decorator itself can be evaluated as follows:
assert hoge(2)(lambda n: 4)(ANY_VALUE) == 6
Recommended Posts