LoginSignup
23
18

More than 5 years have passed since last update.

pytestのfixture、基本のき

Posted at

概要

『テスト駆動Python』を読んでpytestのfixtureの機能を理解したので、基本的な考え方と使い方をまとめる。

私はfixtureについてドキュメントを読んでもよくわからず使っていなかったので、同じような人の参考になればうれしい。

fixtureとは

次の説明が簡潔でわかりやすい。

フィクスチャは、実際のテスト関数の実行に先立って(またはその前後に)、pytestによって実行される関数です。(『テスト駆動Python』P.59)

つまり、テストデータの用意や、テスト前後に行いたいデータベースのセットアップと後始末などに使える。

サンプル

Python3.7.0とpytest3.8.2で実行した。

fixtureでテストデータを用意

import pytest

# fixtureであることを示すデコレータ
@pytest.fixture()
def my_fixture_1():
    return "hello"

# fixtureを引数として渡す
def test_foo(my_fixture_1):
    assert my_fixture_1 == "hello"

fixtureでテスト前後の処理を行う

test_pytest.py
import pytest

@pytest.fixture()
def my_fixture_2():
    # 前処理
    print("fixture start")

    # ここでテストを実行
    yield

    # 後処理
    print("fixture end")

def test_foo(my_fixture_2):
    print("in test_foo")
    assert True

実行

コマンドラインから実行。

# print関数の結果が見れるように"capture=no"を追加
$ pytest --capture=no

結果。(出力は一部省略)

test_pytest.py fixture start
in test_foo
.fixture end

少しわかりにくいが、テストの前後で、fixtureに定義した"fixture start"と"fixture end"が表示されている。
test_pytest.pyはモジュール名、"fixture end"の前に出ている.は実行されたテストごとに表示されるpytestのいつものアレ。)

その他fixtureのあれこれ

  • 上記の例ではテストデータで"hello"を作成したが、配列や辞書などデータ型は自由
  • fixtureのスコープ(実行の単位)は設定可能
    • session, class, module, functionがある
    • 例えば、データベースのセットアップはsessionで良さそう。(各テスト実行につき一度だけ実行される)
    • デフォルトはfunction(テストメソッド・関数の実行毎にfixtureが実行される)
  • fixtureをテストモジュール間で共有したいときは、conftest.pyに書く

参考資料

23
18
1

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
23
18