LoginSignup
1
1

More than 3 years have passed since last update.

pytestでデコレータを使いたい

Last updated at Posted at 2018-02-28
pytest URL
xdistの-nオプションについて https://qiita.com/cielavenir/items/3f3319f3fa153c16c703
デコレータの作り方 https://qiita.com/cielavenir/items/542f7eaa612c6bb9ed90
デコレータに引数を渡す https://qiita.com/cielavenir/items/2c971ca4bc138c375d17
部分テストパラメータの値を使ってテストパラメータを生成する https://qiita.com/cielavenir/items/ce328313a9f0f498cbcb
pytestのfixtureを別の箇所でライブラリとして読み込みたい
(当該環境にはpytestが存在しない可能性がある)
https://qiita.com/cielavenir/items/8144774a6ac2eca2e2ce

例えばある計算の結果が要求を満たすかどうかを確認するテストを書きたいとする。そして、その確認方法は複数のテスト間で共通としよう。
計算結果を確認関数に渡したくなる。こういう場合にデコレータを使うことが出来る。

しかし、一般的なデコレータ作成方法だと、 TypeError: test_foo() takes exactly 1 argument (0 given). やら、 ValueError: <function test_and at 0x10a534848> uses no argument 'a' やらといったエラーが出てしまう。
これを回避するには、decoratorモジュールのdecorator関数を用いれば良い。
標準モジュールではないが、IPythonを導入する際に同時に導入されるので、導入済みの環境も多いのではと思う。

なお、Python3ではこのような制限はないことを付記しておきます。

test_deco.py
import pytest

def check_divtwo(func):
    if 0: # change to 1 to make Py2/3 compatible!
        import decorator
        def wrapper(func,*args,**kwargs):
            r=func(*args,**kwargs)
            assert r%2==0
        return decorator.decorator(wrapper,func)
    else:
        import functools
        @functools.wraps(func)
        def wrapper(*args,**kwargs):
            r=func(*args,**kwargs)
            assert r%2==0
        return wrapper

@check_divtwo
@pytest.mark.parametrize(('a','b'),[
    (1,2),
    (3,4),
])
def test_and(a,b):
    return a&b

@check_divtwo
@pytest.mark.parametrize('n',[
    2,
    6,
])
def test_leastbit(n):
    return -n&n
  • この件に関する日本語の情報は私が調べた限りでは存在しないようです。。
1
1
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
1