はじめてのpytest#

サンプルコードには テストのサンプルコード が含まれています。

Listing 1 テストのサンプルコード#
from connpass_client import ConnpassClient


def test_results():
    data = ConnpassClient().get(event_id="266898")
    assert data["results_returned"] == 1
    assert data["results_available"] == 1
    assert data["results_start"] == 1

pytest コマンドでテストを実行します。

%%bash

pytest
============================= test session starts ==============================
platform linux -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/driller/repo/pytest-hands-on/docs
plugins: anyio-3.6.2
collected 1 item

tests/test_sample.py .                                                   [100%]

============================== 1 passed in 0.19s ===============================

-vv フラグを使うとテストに失敗した場合に、どこで不一致が起きているかを確認できます。敢えて失敗するテストのコードに変更し、失敗箇所を確認してみましょう。

%%bash

pytest -vv
============================= test session starts ==============================
platform linux -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0 -- /home/driller/repo/pytest-hands-on/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/driller/repo/pytest-hands-on/docs
plugins: anyio-3.6.2
collecting ... collected 1 item

tests/test_sample.py::test_results PASSED                                [100%]

============================== 1 passed in 0.20s ===============================

特定の関数だけをテストする場合は次のように モジュール名::関数名 で記述して実行します。

%%bash

pytest tests/test_sample.py::test_results
============================= test session starts ==============================
platform linux -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/driller/repo/pytest-hands-on/docs
plugins: anyio-3.6.2
collected 1 item

tests/test_sample.py .                                                   [100%]

============================== 1 passed in 0.19s ===============================