Python doctest / unittest / pytest のサンプル

目次

概要と特徴

モジュール  概要 特徴
doctest docstringを使用した標準モジュール docstringのみで簡単だが他モジュールの使用制限がある。1ファイルで簡単なテストをしたいときいいかも。
unittest 他言語と類似する標準モジュール 標準だが他言語と類似形式のため python らしくない(らしい)。
pytest サードパーティのテストモジュール python らしくテストが記述できる。一番人気ぽい。

doctest のサンプル実装

lesson.py ファイル

class Cal(object):
    def add_num_and_double(self, x, y):
        """Add and double
        >>> c = Cal()
        >>> c.add_num_and_double(1, 1)
        4

        >>> c.add_num_and_double("1", "1")
        Traceback (most recent call last):
        ・・・
        ValueError
        """
        if type(x) is not int or type(y) is not int:
            raise ValueError
        result = x + y
        result *= 2
        return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()

コマンドで実行

% python lesson.py

# なにも出力されなかったらOK、テスト失敗はエラーログが出力される。

unittest のサンプル実装

calculation.py ファイル

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

test_calculation.py ファイル

import unittest
import calculation


class CalTest(unittest.TestCase):
    def test_add_num_and_double(self):
        cal = calculation.Cal()
        self.assertEqual(cal.add_num_and_double(1,1), 4)

    # 例外処理のテスト
    def test_add_num_and_double_raise(self):
        cal = calculation.Cal()
        with self.assertRaises(ValueError):
            cal.add_num_and_double("1","1")


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

コマンド

%  python test_calculation.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

pytest のサンプル実装

calculation.py ファイル

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

test_calculation.py ファイル

import calculation


class TestCal(object):
    def test_add_num_and_double(self):
        cal = calculation.Cal()
        assert cal.add_num_and_double(1,1) == 4

    # 例外処理のテスト
    def test_add_num_and_double_raise(self):
        with pytest.raises(ValueError):
            cal = calculation.Cal()
            cal.add_num_and_double('1','1')

コマンドで実行

% pytest test_calculation.py

======================================================================================================= test session starts ========================================================================================================
platform darwin -- Python 3.9.6, pytest-8.2.2, pluggy-1.5.0
rootdir: /Users/ka-yamao/workspace/python_programming
collected 2 items                                                                                                                                                                                                                  

test_calculation.py ..                                                                                                                                                                                                       [100%]

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