[PYTHON] Test code for evaluating decorators

How to write test code to evaluate a Python decorator. Please let me know if there is a better way.

Testing the decorator itself

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

Testing decorators with arguments

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

Test code for evaluating decorators
Strengthen with code test ⑦
Strengthen with code test ⑨
Strengthen with code test ③
Strengthen with code test ⑤
Strengthen with code test ④
Techniques for code testing?
Strengthen with code test ②
[Memo] Test code summary
Strengthen with code test ①
Test automation for work
Strengthen with code test ⑧
Strengthen with code test ⑨
Tutorial for doing Test Driven Development (TDD) in Flask-2 Decorators
Test code to check for broken links in the page
Hypothesis test for product improvement
For the G test 2020 # 2 exam
Python code memo for yourself
PyCharm test code automatic generation
Python template for Codeforces-manual test-
[Python] Sample code for Python grammar
Python> I made a test code for my own external file
Decision tree (for beginners) -Code edition-
VS Code snippets for data analysts
Test methods for customizing Pickle behavior
Write selenium test code in python
Created AtCoder test tool for Python
A note for writing Python-like code
Linear regression (for beginners) -Code edition-
Code for self-organizing state-space model (unfinished)
Ridge Regression (for beginners) -Code Edition-