pytestを使って、統合テストを行いたい。 統合テストでは、外部のAPIやリソースにアクセスする。 そのため、pytest実行時にフラグを指定した場合のみ、統合テストを実行するようにしたい。
実装としては、@pytest.mark
をつかって、テストをマークしておく方法がある。
この方法ではテストファイルのディレクトリ構成に関係なく、個々のテストを統合テストとしてマークする。 これはこれで便利だが、今回は、「特定のディレクトリ内のテストファイル」をすべて統合テストとして実行する方法を試してみた。
pytestの設定
テストコードのディレクトリ構成は以下のようになっているとする:
tests/
├── conftest.py
├── integration/
│ ├── conftest.py
│ ├── test_integration.py
├── test_unit.py
ここで、integration/
ディレクトリ内のテストファイルを統合テストとして、--integration
フラグを指定した場合のみ実行したい:
pytest --integration
ベースとなるtests/conftest.py
に以下のコードを追加する:
def pytest_addoption(parser):
parser.addoption(
"--integration",
action="store_true",
default=False,
help="run integration tests",
)
これで、--integration
フラグをpytest
コマンドに指定できるようになる。
次に、tests/integration/conftest.py
に以下のコードを追加する:
def pytest_collection_modifyitems(config, items):
# skip all integration tests if not explicitly requested
if not config.option.integration:
skip_integration = pytest.mark.skip(reason="need --integration option to run")
for item in items:
if "integration" in item.keywords:
item.add_marker(skip_integration)
これで、--integration
フラグが指定されていない場合、integration/
内のテストはスキップされるようになる。
例
とあるbqm
というレポジトリにおける--integration
フラグを指定した場合のみ実行されるテストコードの追加コミット.
統合テストとして、GCPのBigQueryにアクセスするテストコードを書いている。
--integration
フラグを指定せずにテストを実行すると、統合テストはスキップされる:
❯ pytest tests/integration -vv
==== test session starts ============================================
platform darwin -- Python 3.12.7, pytest-8.3.3, pluggy-1.5.0 -- /Users/hoge/work/repos/bqm/.venv/bin/python3
cachedir: .pytest_cache
rootdir: /Users/hoge/work/repos/bqm
configfile: pyproject.toml
plugins: syrupy-4.7.2
collected 2 items
tests/integration/test_integration.py::test_integration SKIPPED (need --integration option to run) [ 50%]
tests/integration/test_integration.py::test_tables_dryrun SKIPPED (need --integration option to run) [100%]
=== 2 skipped in 0.32s ==============================================
--integration
フラグを指定してテストを実行すると、統合テストが実行される (このツールでは、--project
でGCPのプロジェクトIDも指定する必要がある):
❯ python -m pytest --integration --project hoge-gcp -vv
==== test session starts ============================================
platform darwin -- Python 3.12.7, pytest-8.3.3, pluggy-1.5.0 -- /Users/hoge/work/repos/bqm/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/hoge/work/repos/bqm
configfile: pyproject.toml
plugins: syrupy-4.7.2
collected 5 items
tests/integration/test_integration.py::test_integration PASSED [ 20%]
tests/integration/test_integration.py::test_tables_dryrun PASSED [ 40%]
tests/test_bqm.py::test_version PASSED [ 60%]
tests/test_bqm.py::test_tables_dryrun PASSED [ 80%]
tests/test_bqm.py::test_views_dryrun PASSED [100%]
---snapshot report summary ------------------------------------------
3 snapshots passed.
=== 5 passed in 5.97s ===============================================