実際のプロジェクトでpytestを使用してユニットテストを行う方法(PyCharmと組み合わせる)


pytestを使用してユニットテストを行います(PyCharmと組み合わせて)
目的
ネット上ではpytestを紹介する文章が多いが、実際の開発と結びつけることは少なく、簡単なdemoが多い.以下では、実際のプロジェクトと組み合わせてどのように使用するかを説明します.
主な内容
  • 一般プロジェクトの作成
  • pytest依存
  • を追加
  • テストディレクトリ
  • を作成する
  • 実行テスト
  • 結合PyCharm
  • 参考文献
  • 一般プロジェクトの作成
    プロジェクトルートディレクトリ「pytest-demo」を作成
    プロジェクトファイルを追加します.ディレクトリ構造は次のとおりです.
    pytest-demo
  • demo
  • \_\_init\_\_.py
  • utils
  • \_\_init\_\_.py
  • math_helper.py




  • math_helper.pyは以下の通りです
    class MathHelper(object):
        def addition(self, first, second):
            """
              
            :param first:      
            :param second:      
            :return:       
            """
            #        
            if not isinstance(first, (int, float)):
                raise ValueError("first       ")
            if not isinstance(second, (int, float)):
                raise ValueError("second       ")
            #     
            return first + second

    pytest依存の追加
    $ pip install pytest

    ユニットテストディレクトリの追加
    ルートディレクトリの下にユニットテストディレクトリ「tests」を作成します(packageとして作成し、全量テストを容易にすることに注意してください).
    テストクラスを追加するには、テストクラスのファイル名をtest_とする必要があります.pyまたは_test.py、命名規則はpytestの公式ドキュメントを表示します
    最終ディレクトリ構造は次のとおりです.
    pytest-demo
  • demo
  • \_\_init\_\_.py
  • utils
  • \_\_init\_\_.py
  • math_helper.py



  • tests
  • demo
  • \_\_init\_\_.py
  • utils
  • \_\_init\_\_.py
  • test_math_helper.py





  • test_math_helper.pyは以下の通りです
    import pytest
    from demo.utils.math_helper import MathHelper
    
    
    def test_addition():
        #    
        helper = MathHelper()
        #       ,    ValueError   
        with pytest.raises(ValueError):
            helper.addition("1", 2)
        with pytest.raises(ValueError):
            helper.addition(1, "2")
        #     
        result = helper.addition(1, 2)
        #   assert    
        assert result == 3

    テストケースの実行
    $ pytest

    すべてのテストを実行し、結果を表示できます.
    PyCharmの結合
  • PyCharmデフォルトテストタイプ
  • を設定
  • 開くFile>Settings>Tools>Python Integrated Tools>Testing>Default test runner
  • ドロップダウンボックスを変更し、「pytest」
  • に変更
  • 右クリックユニットテストファイル、「run」をクリックするとテストが実行され、下の「Run」ウィンドウにも対応するテスト結果
  • がある.
  • すべてのテストを実行する設定
  • 右クリック「tests」フォルダ、「Run」
  • を選択
  • 次にディレクトリの下のすべてのテスト例を直接走り、下の「Run」ウィンドウにテスト情報
  • が表示されます.
  • モジュールが見つからない場合は、右上の編集開始項目を開き、古い情報を削除する必要があります.そうしないと、キャッシュ
  • があります.
    参考文献
    pytest公式ドキュメント