\ 最大7.5%ポイントアップ! /

【pytest】事前処理と事後処理の方法まとめ

  • setup、teardownで事前・事後処理ができるのはわかった
  • より細かい設定方法が知りたい

このような疑問にお答えします。

プログラムテストにあたってはただ単にテストコードを走らせるのではなく、テストコードの前後に準備や後始末をすることが一般的です。

そこで使われるのがsetupteardown

この二つの方法はコードの組み方で挙動を変えることができ、それを使い分けることで思い通りのテストケースを作ることができます。

本記事では事前・事後処理の方法を解説します。

【pytest】事前処理と事後処理の方法まとめ

事前・事後処理は実行させるタイミングで3パターンがあります。

  • 関数の前後で実施
  • クラスの前後で実施
  • モジュールの前後で実施

どの粒度の事前・事後処理なのかを考えつつ、使い分けていきましょう。

各関数の前後で「事前・事後処理」をさせたい

各関数の前後で、決まった事前・事後処理をさせたい場合には以下のように記載します。

# 前処理
def setup_function(function):
    print("setup function")


# 後処理
def teardown_function(function):
    print("teardown_function")


def test_hello_world():
    print("hello world!")


def test_pytest():
    print("pytest")


# 実施される順番

# setup function
# hello world!
# .teardown_function
# setup function
# pytest
# .teardown_function

各テスト関数が実施されるたびに事前・事後処理が走る、というのがこの書き方の特徴です。

クラスの場合にも同様に書くことができます。

class TestExample:
    def setup_method(self, method):
        print("setup_method")

    def teardown_method(self, method):
        print("teardown_method")

    def test_example(self):
        print("hello")

    def test_example2(self):
        print("pytest")


# 実施される順番

# setup_method
# hello
# .teardown_method
# setup_method
# pytest
# .teardown_method

動き的には先ほどの関数のものと同様です。

クラスの前後で「事前・事後処理」をさせたい

メソッドの前後ではなく、もっと大きな単位でクラスの前後で事前・事後処理を実施する場合には以下とします。

# 前処理、後処理のメソッドを作成
class TestExample:
    @classmethod
    def setup_class(cls):
        print("setup_class")

    @classmethod
    def teardown_class(cls):
        print("teardown_class")

    def test_example(self):
        print("hello")

    def test_example2(self):
        print("pytest")


# 実施される順番
# setup_class
# hello
# .pytest
# .teardown_class

スクリプト実施時に事前処理を、スクリプト終了前に事後処理を行う

クラスよりももっと大きな「モジュール」という単位で事前・事後処理をさせたい場合には、以下のようにモジュールに対してsetup, teardownを実施します。

def setup_module(module):
    print("setup_module")


def teardown_module(module):
    print("teardown_module")


def test_hello_world():
    print("hello world!")


def test_pytest():
    print("pytest")


class TestExample:
    def test_hello_world(self):
        print("hello world!")

    def test_pytest(self):
        print("pytest")


# setup_module
# hello world!
# .pytest
# .hello world!
# .pytest
# .teardown_module

この記事が気に入ったら
フォローしてね!

シェア・記事の保存はこちら!

この記事を書いた人

karo@プログラマのアバター karo@プログラマ プログラマ

「書くことで人の役にたつ」をモットーに活動中。
本職はプログラマで、Pythonが得意。
基本情報技術者試験合格。

コメント

コメントする

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)