pytestメモ

Udemyでお世話になっている酒井さんの講座の学習メモ。

www.udemy.com

テストしたい関数がある。

class Cal(object):
    def add_num_and_double(self, x, y):
        if type(x) is not int or type(y) is not int:
            raise ValueError
        result = x + y
        result *= 2
        return result

関数をテストするpytestファイルを作成する。

# pytestのファイル名は「test_」から始める
# 別ファイルの関数にアクセスするのでimportする
import calculation
import pytest

class TestCal(object):
    # テストを開始するときだけ実行
    @classmethod
    def setup_class(cls):
        print('start')
        cls.cal = calculation.Cal()

    # テストを終了するときだけ実行
    @classmethod
    def teardown_class(cls):
        print('end')
        del cls._cal

    # テスト関数を実行する度に実行
    def setup_method(self, method):
        print('method={}'.format(method.__name__))

    # テスト関数が終了する度に実行
    def teardown_method(self, method):
        print('method={}'.format(method.__name__))

    # テスト関数
    # 4が返るか確認
    def test_add_num_and_double(self):
        assert self.cal.add_num_and_double(1, 1) == 4

    # 例外テスト関数
    # 文字列を渡してValueErrorが返るか確認(返らなければエラー)
    def test_add_num_and_double_raise(self):
        with pytest.raises(ValueError):
            self.cal.add_num_and_double('1', '1')

    # スキップ
    @pytest.mark.skip(reason='Skip!')
    def test_add_num_and_double(self):
        assert self.cal.add_num_and_double(1, 1) == 4

    # 条件付きスキップ
    is_release = True
    @pytest.mark.skipif(is_release==True, reason='Skip!')
    def test_add_num_and_double(self):
        assert self.cal.add_num_and_double(1, 1) == 4