• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

python pytest

date: 2024-06-09 excerpt: python pytestの使い方

tag: pythonpytest


python pytestの使い方

概要

  • pythonのテストフレームワーク
  • pytest.iniファイルにパスを設定することで、テスト対象のファイルを指定できる
  • 標準出力はデフォルトでは表示されないが、-sオプションをつけることで表示できる

インストール

$ pip install pytest

ファイル構成例

project/
│
├── src/
│   ├── __init__.py
│   └── my_module.py
│
├── tests/
│   ├── __init__.py
│   ├── conftest.py  # ここに sys.path.insert を追加
│   └── test_my_module.py
│
└── pytest.ini  # ここに pythonpath を追加する場合

pytest.ini

  • テスト対象のディレクトリの指定
  • テスト対象のファイル名の指定
# pytest.ini
[pytest]
pythonpath = src
testpaths = tests
python_files = test_*.py tests_*.py

src/my_module.py

def add(a, b):
    return a + b

tests/test_my_module.py

from my_module import add

def test_add():
    assert add(1, 2) == 3

実行

すべてのテストを実行

$ pytest

特定のテストを実行

  • ::<関数名>で実行するテストを指定できる
$ pytest tests/test_my_module.py::test_add

トラブルシューティング

pytestを実行してもテストが実行されない

  • 原因
    • tests/__init__.pyが存在しない
    • pytest.iniに記されているpython_filesに一致していないテストファイル名になっている


pythonpytest Share Tweet