『テスト駆動Python』によれば、@pytest.fixtureで修飾した関数内でyieldを実行すると値を返すことができるとあります。
しかし、返した値をテスト側でどのように受け取ればいいのかが書いていないようなので、実験してみました。
1.テスト関数の引数にフィクスチャ関数を指定するとき
[サンプルスクリプト] test_str.py
import pytest @pytest.fixture() def prepare_strings(): print('セットアップ') yield 'Python入門' print('\nティアダウン') def test_len(prepare_strings): assert len(prepare_strings) == 8 def test_reverse(prepare_strings): assert prepare_strings[::-1] == '門入nohtyP'
フィクスチャ関数prepare_stringsをテスト関数の引数として渡してやると、関数内でprepare_stringsという変数が使えるようになる。
[実行結果]
セットアップ . ティアダウン セットアップ . ティアダウン 2 passed in 0.01 seconds
2.pytest.fixtureにautouse=Trueを指定した時
[サンプルスクリプト]
import pytest @pytest.fixture(autouse=True) def prepare_strings(): print('セットアップ') yield 'Python入門' print('\nティアダウン') def test_len(prepare_strings): assert len(prepare_strings) == 8 def test_reverse(prepare_strings): assert prepare_strings[::-1] == '門入nohtyP'
autouse=Trueにより、フィクスチャ関数prepare_stringsは自動的に実行されるが、テスト関数側で受け取る手段がない(あるのか?)。
結局、prepare_stringsをテスト関数の引数として渡さなければならないような気がする。