テスト環境を構築する

稼働中のシステムで想定内のエラーを検知するにはif文やtry-except文を使うと思いますが、テストやデバッグの時には想定外のエラーも検知したいものです。そのためには、pytestとassert文を組み合わせてテストの環境を構築するのがいいのかなと思っています。ここでは、そのテスト環境の構築方法をまとめました。

動作環境

ホストOSWindows 10 21H1(19043.1889) 64bit
仮想化ソフトウェアVirtualBox 6.1.34 r150636 (Qt5.6.2)
ゲストOSUbuntu 22.04
Python3.10.4

事前準備

pytestをインストール

python -m pip install -U pip
pip install pytest
pip list

Package    Version
---------- -------
attrs      22.1.0
iniconfig  1.1.1
packaging  21.3
pip        22.2.2
pluggy     1.0.0
py         1.11.0
pyparsing  3.0.9
pytest     7.1.3
setuptools 59.6.0
tomli      2.0.1

サンプル

実装及びテスト準備

下記のファイル・フォルダ構成を作成しました。
テスト対象のソースファイルを*.pyとした時、テストコードはtest_*.pyにまとめて書きます。

.
├── app
│   ├── __init__.py
│   └── python_sample_0044.py
└── tests
    ├── __init__.py
    └── test_python_sample_0044.py
# python_sample_0044.py

# この関数をテストする
def add(x, y):
    return x + y
# test_python_sample_0044.py

from app import python_sample_0044 as tgt

# add関数のテストコード
def test_add():
    res = tgt.add(1, 2)
    # add関数の戻り値が3でない場合は例外を出力
    assert res == 3

__init__.pyは両方とも空ファイルにしています。

テスト結果

コンソールで下記を実行すると、pytestが自動でtest_*.pyを検索し、実行結果を返してくれます。

pytest
======================================================================= test session starts =======================================================================
platform linux -- Python 3.10.4, pytest-7.1.3, pluggy-1.0.0
rootdir: /home/gen_user/py_sample/0044/prj
collected 1 item                                                                                                                                                  

tests/test_python_sample_0044.py .                                                                                                                          [100%]

======================================================================== 1 passed in 0.02s ========================================================================

たとえばassert文のところを『assert res == 3000』に変更して実行してみると下記のようにエラーが検出できます。

pytest
======================================================================= test session starts =======================================================================
platform linux -- Python 3.10.4, pytest-7.1.3, pluggy-1.0.0
rootdir: /home/gen_user/py_sample/0044/prj
collected 1 item                                                                                                                                                  

tests/test_python_sample_0044.py F                                                                                                                          [100%]

============================================================================ FAILURES =============================================================================
____________________________________________________________________________ test_add _____________________________________________________________________________

    def test_add():
        res = tgt.add(1, 2)
        # add関数の戻り値が3でない場合は例外を出力
>       assert res == 3000
E       assert 3 == 3000

tests/test_python_sample_0044.py:7: AssertionError
===================================================================== short test summary info =====================================================================
FAILED tests/test_python_sample_0044.py::test_add - assert 3 == 3000
======================================================================== 1 failed in 0.04s ========================================================================