python でテストを書く

pytest external_link というライブラリを使ってテストコードを実行する方法

シンプルな例

テスト用ファイルを準備

tests/test.py
def test_hoge(): a = 1 b = 1 assert a == b def test_fuga(): a = 1 b = 2 assert a == b

以下コマンドでテストを実行

$ pip install pytest $ pytest ./tests/test.py =============================== test session starts ================================ platform darwin -- Python 3.7.9, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 rootdir: /Users/yusuketakizawa/mahjong-manager-bot collected 2 items tests/test.py .F [100%] ===================================== FAILURES ===================================== ____________________________________ test_fuga _____________________________________ def test_fuga(): a = 1 b = 2 > assert a == b E assert 1 == 2 tests/test.py:66: AssertionError ============================= short test summary info ============================== FAILED tests/test.py::test_fuga - assert 1 == 2 =========================== 1 failed, 1 passed in 0.03s ============================

こんな感じで結果が表示される。

注意点

テスト対象のメソッドかどうかはメソッド名で判別される

テストをするメソッドかどうかは python_functions という設定値で指定される(デフォルトは test_* )

https://docs.pytest.org/en/latest/reference.html#confval-python_functions external_link

テスト対象のメソッドがなかった場合 no tests run となるが、これは github action 上では Error: Process completed with exit code 5. となり fail と扱われるので注意が必要

ライブラリのパスが通るパターンと通らないパターン

$ pytest ./tests/test.py >>> ModuleNotFoundError: No module named 'flask'

上記のように直接 pytest コマンドを実行するとモジュールインポート時にエラーが出る場合は以下のように python コマンドで実行すればよい

$ python -m pytest ./tests/test.py

上位階層にあるファイルのインポート

tests ディレクトリと同階層にあるファイル(例えばlibs.py)を使いたいとき import ..lib.py としてもインポートできない。以下のように予め上位ディレクトリにパスを通しておくとインポートできるようになる

import sys import os sys.path.append(os.path.abspath( os.path.dirname(os.path.abspath(__file__)) + "/../"))