Pytest の fixture 関数を普通の関数のように利用できる ― 2022年12月17日 11時27分36秒
fixture はテストの前準備。テスト関数の引数として、fixture 関数の名前を並べる。テスト関数の実行が始まる前に、fixture 関数が全て呼ばれる。
時によっては fixture としてではなく普通の関数として使いたいときもある。そこで、fixture 関数を普通のテスト関数から呼べるか実験。
import pytest
@pytest.fixture
def fixture():
print("fixture")
def test_as_fixture(fixture):
pass
def test_as_function():
fixture()
二つ目の方は普通に関数として呼んでいる。pytest を呼び出すのは、-rP を渡して成功するテストでも print の出力を見る。
余計な出力が増えて若干見づらいが、両方とも問題なく使えている。
# pytest -rP test_fixture.py
================================================ test session starts ================================================
...
collected 2 items
test_fixture.py ..
====================================================== PASSES =======================================================
__________________________________________________ test_as_fixture __________________________________________________
====================================================== PASSES =======================================================
__________________________________________________ test_as_fixture __________________________________________________
----------------------------------------------- Captured stdout setup -----------------------------------------------
fixture
_________________________________________________ test_as_function __________________________________________________
----------------------------------------------- Captured stdout call ------------------------------------------------
fixture
======================================= 2 passed in 0.11 seconds ========================================
最近のコメント