LoginSignup
2
1

More than 3 years have passed since last update.

pytestのデコレータに引数を渡す

Last updated at Posted at 2018-05-15
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

デコレータの中身に引数を渡すには、ダミーのフィクスチャを用意し、シグネチャからそのフィクスチャのインデックスを取得、argsを書き換えれば良い。

To pass arguments to pytest decorator, prepare dummy fixture and let the wrapper get the argument index using signature, and overwrite args.

overwrite_fixture.py
import pytest
import decorator

try:
    from inspect import signature
except ImportError:
    from funcsigs import signature

@pytest.fixture(scope='module')
def var1():
    return 1

@pytest.fixture(scope='module')
def var2():
    return 2

def wrap(func):
    def wrapper(func,*args):
        sig = signature(func)
        idx = list(sig.parameters).index('var1')
        arglst = list(args)
        result = []
        for e in [10,20]:
            arglst[idx] = e
            result.append(func(*arglst))
        assert result[1]-result[0]==10
    return decorator.decorator(wrapper,func)

@wrap
def test_0(var1,var2):
    return var1
2
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
2
1