1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デコレータを評価するためのテストコード

Posted at

Pythonのデコレータを評価するためのテストコードの書き方です.
もっといい方法あったら教えて下さい.

デコレータ自体のテスト

hoge デコレータをつけると, 戻り値に 1 を加算します.

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

デコレータ自体は, 次のように評価できます (ANY_VALUE はなんでもよい).

assert hoge(lambda n: 6)(ANY_VALUE) == 7

引数があるデコレータのテスト

つぎの hoge デコレータを使うと, デコレータの引数に指定した値を戻り値に加算します.

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

デコレータ自体は, 次のように評価できます.

assert hoge(2)(lambda n: 4)(ANY_VALUE) == 6
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?