KnowHow

技術的なメモを中心にまとめます。
検索にて調べることができます。

pytestの書き方サンプル

登録日 :2024/09/15 11:07
カテゴリ :Python基礎

pytestをインストールする

pip install pytest

次のプログラのテストをする

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

pytestによるテストコード

import pytest

import calcuration


class TestCal(object):
    @classmethod
    def setup_class(cls):
        print('start')
        cls.cal = calcuration.Cal()

    @classmethod
    def teardown_class(cls):
        print('end')
        del cls.cal

    def setup_method(self, method):
        #self.cal = calcuration.Cal()
        print({'method': method.__name__})

    def teardown_method(self, method):
        #del self.cal
        print({'method': method.__name__})

    def test_add_mum_and_double(self):
        cal = calcuration.Cal()
        assert cal.add_num_and_double(1, 1) == 4

    def test_add_num_and_double_raise(self):
        with pytest.raises(ValueError):
            cal = calcuration.Cal()
            cal.add_num_and_double('1', '1')


if __name__ == '__main__':
    pytest.main()

実行するときは

$ pytest lesson.py
=========================================================== test session starts ===========================================================
platform darwin -- Python 3.8.10, pytest-8.3.3, pluggy-1.5.0
rootdir: /Users/basic
collected 2 items                                                                                                                         

lesson.py ..                                                                                                                        [100%]

============================================================ 2 passed in 0.01s ============================================================

$ 
Skip

テストをスキップする場合のコード。
pytestを実行する時に、-rs オプションをつけると、スキップの理由も表示できる。

import pytest

import calcuration

is_release = True


class TestCal(object):
    @classmethod
    def setup_class(cls):
        print('start')
        cls.cal = calcuration.Cal()

    @classmethod
    def teardown_class(cls):
        print('end')
        del cls.cal

    def setup_method(self, method):
        #self.cal = calcuration.Cal()
        print({'method': method.__name__})

    def teardown_method(self, method):
        #del self.cal
        print({'method': method.__name__})

    def test_add_mum_and_double(self):
        cal = calcuration.Cal()
        assert cal.add_num_and_double(1, 1) == 4

    # @pytest.mark.skip(reason='skip!')
    @pytest.mark.skipif(is_release=True, reason='skipped by is_release')
    def test_add_num_and_double_raise(self):
        with pytest.raises(ValueError):
            cal = calcuration.Cal()
            cal.add_num_and_double('1', '1')

if __name__ == '__main__':
    #normal
    #pytest lesson.py
    #show skip reaseon
    #pytest -rs lesson.py

    pytest.main()