【Python】pytestの基本的な使い方

■概要

Pythonのテストフレームワーク「pytest」は、シンプルで使いやすく、柔軟なテストが可能なテストツールである。

▼実行環境

実行環境は以下の通り。

項目内容
pythonバージョン3系
OSMac
実行環境Pycharm(統合開発環境)

▼インストール方法

pytestを実行するために、ターミナル上で以下のコマンドを実行。

pip install pytest

▼テストファイルの命名規則

pytestを実行するにあたり、以下ファイルやモジュール名に`test`を記載する必要あり。
※テストファイルにimport pytestを使用しなくても、pytestとして自動で読み取ってくれる。

  • テストファイルは test_*.py または *_test.py の形式
  • テスト関数は test_ で始める
  • テストクラスは Test で始める

■サンプルコード

・pytest_target_sample_cal.py

class Cal:
    def add_for_num(self, x: int) -> int:
        """
        計算処理:入力値1をループして加算する
        :param x: 入力値1
        :return: 計算結果
        """
        if type(x) is not int:
            raise ValueError

        result_value = 0
        
        for i in range(x):
            result_value += i

        return result_value

・test_pytest_target_sample_cal.py

import pytest

from src.pytest_target_sample_cal import Cal


# 関数で実行(先頭に`test_`を記載する)
def test_add_for_num():
    cal = Cal()
    # 一致テスト(0 + 1 + ... + 9)
    assert cal.add_for_num(10) == 45

    # 不一致テスト(0 + 1)
    assert cal.add_for_num(2) != 9


def test_add_num_and_double_raise_value_error():
    # 例外テスト
    with pytest.raises(ValueError):
        cal = Cal()
        cal.add_for_num('1')


# クラスで実行(先頭に`Test`を記載する)
class TestCal:
    def test_test_add_num_and_double(self):
        cal = Cal()
        # 一致テスト
        assert cal.add_for_num(1) == 0

■実行結果

・test_add_for_num()を実行した場合

============================= test session starts ==============================
collecting ... collected 1 item

test_pytest_target_sample_cal.py::test_add_for_num PASSED                [100%]

============================== 1 passed in 0.01s ===============================

・test_add_num_and_double_raise_value_error()を実行した場合

============================= test session starts ==============================
collecting ... collected 1 item

test_pytest_target_sample_cal.py::test_add_num_and_double_raise_value_error PASSED [100%]

============================== 1 passed in 0.01s ===============================

・参考:テストが失敗したケース

test_add_for_num()について、cal.add_for_num(10)の予測値を「45」から「46」に変更した場合

============================= test session starts ==============================
collecting ... collected 1 item

test_pytest_target_sample_cal.py::test_add_for_num FAILED                [100%]
test_pytest_target_sample_cal.py:6 (test_add_for_num)
45 != 46

予想:46
実際:45
<クリックで差分を表示>

def test_add_for_num():
        cal = Cal()
        # 一致テスト(0 + 1 + ... + 9)
>       assert cal.add_for_num(10) == 46
E       assert 45 == 46
E        +  where 45 = add_for_num(10)
E        +    where add_for_num = <src.pytest_target_sample_cal.Cal object at 0x7f83b35932b0>.add_for_num

test_pytest_target_sample_cal.py:10: AssertionError


============================== 1 failed in 0.09s ===============================

コメント