Python の構文チェックツールが乱立しており、それぞれ用途が異なり、設定が大変だったところを tox というツールでまとめてみました。
利用する構文チェックツール
requirements-dev.txt
1 2 3 4 5 6 7
| pytest==6.2.5 tox==4.26.0 black==25.1.0 bandit==1.8.3 flake8==7.2.0 mypy==1.16.0 isort==6.0.1
|
tool |
explain |
pytest |
Python の テスト実行ツール。テスト関数を自動で見つけて実行します。 |
tox |
複数の環境でテストやチェックを自動化するツール。CI/CDや複数Pythonバージョン対応に使います。 |
black |
コード整形ツール(自動フォーマッター)。PEP8に準拠したスタイルに自動で直します。 |
bandit |
Pythonコードの セキュリティチェックツール。危険なコードパターンを検出します。 |
flake8 |
Pythonコードの 文法・スタイルチェックツール。PEP8違反などを報告します。 |
mypy |
Pythonコードの 型チェックツール。型ヒント(type hint)が正しく使われているか確認します。 |
isort |
import文を自動で整理・ソートするツール。blackと一緒によく使われます。 |
tox.ini 設定例
除外ディレクトリについて CDK プロジェクトを考慮している tox.ini の設定です。
流用十分可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| [tox]
skipsdist = True
[testenv]
deps = -rrequirements.txt -rrequirements-dev.txt commands = pytest -rsfp
[testenv:lint] deps = -rrequirements-dev.txt commands = black . --check --skip-string-normalization bandit --quiet --exclude ./.tox,./.venv,./.pytest_cache --recursive . flake8 . mypy --ignore-missing-imports . isort . --profile black --check --diff --skip-glob .venv,./.tox,./.pytest_cache
[testenv:lint_auto_fix] deps = -rrequirements-dev.txt commands = black . --skip-string-normalization isort . --profile black --diff --skip-glob .venv,./.tox,./.pytest_cache
[flake8] deps = -rrequirements-dev.txt
max-line-length = 119
exclude = .git __pychache__ .tox .mypy_cache .venv .pytest_cache cdk.out
|
利用方法
テスト実行方法
構文チェック実行
構文自動修正
GitHub Actions 設定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| name: CDK Unit Test
on: pull_request: push: branches: - main
jobs: test: runs-on: ubuntu-latest timeout-minutes: 5
steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
- name: Pick python version id: python run: echo "version=$(awk '$1 ~ /^python/{print $2}' .tool-versions)" >> $GITHUB_OUTPUT
- name: Set up Python uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c with: python-version: ${{ steps.python.outputs.version }}
- name: Install dependencies run: pip install -r requirements-dev.txt
- name: Run linter run: tox -e lint
- name: Run tests run: tox
|
実装例
Raspberry PI の設定で利用しました。
https://github.com/kenzo0107/raspi-talk/commits/main/tox.ini
以上
参考になれば幸いです。