Overview
インスタンス生成時の引数と、期待する結果だけ指定すれば、テーブルドリブンテストが走るようにしたかった。
@pytest.mark.parametrize
の indirect
引数に関数名を指定すると fixture のパラメータ化ができるらしいので、
テストのパラメータ化と合わせて、こんな感じ。
test_sample.py
import pytest
class Sample:
"""これをテストしたい"""
def __init__(self, val):
self._val = val
def m1(self):
return self._val[:2]
def m2(self):
return self._val[2:7]
def m3(self):
return self._val[7:10]
def f(self):
return len(self._val) == 10
# テストするメソッドを unbound method で準備
methods = [
Sample.m1,
Sample.m2,
Sample.m3,
Sample.f,
]
@pytest.fixture
def actual(request):
""" fixture のパラメータ化 """
s = request.param
that = Sample(s)
# self を付与して unbound method を呼び出す
return [ m(that) for m in methods ]
# テストのパラメータ化
@pytest.mark.parametrize('actual, expected', [
# expected の並び順は methods を呼び出す順に合わせる必要がある
("1234567890", ["12", "34567", "890", True]),
("0987654321", ["09", "87654", "321", True]),
("11122233345", ["11", "12223", "334", False]),
], indirect=["actual"])
def test_sample(actual, expected):
assert actual == expected
参考
https://pytest.readthedocs.io/en/2.8.7/parametrize.html
https://gist.github.com/yyyk-bp/30e1d5b9be4b2d00e4f072faa5a1ece8