環境
- Python 3.11
はじめに
TravisCIでPythonコードのテストとリントを実行していましたが、諸々の理由でGitHub Actionsへ移行することになりました。
TravisCIの設定ファイル
dist: xenial
language: python
python:
- "3.11"
- "3.12"
install:
- pip install poetry
- travis_retry poetry install
script:
- make lint
- make test
branches:
only:
- main
GitHub Actionsの設定ファイル
設定ファイルは"Python application"というテンプレートを利用しました。
https://github.com/actions/starter-workflows/blob/main/ci/python-app.yml
https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python を参考にしました。
name: Python application
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip "poetry<1.9"
poetry install
- name: Lint
run: |
make lint
- name: Test
run: |
make test
Makefile
ifndef SOURCE_FILES
export SOURCE_FILES:=src
endif
ifndef TEST_FILES
export TEST_FILES:=tests
endif
.PHONY: lint format test
format:
poetry run ruff format ${SOURCE_FILES} ${TEST_FILES}
poetry run ruff check ${SOURCE_FILES} ${TEST_FILES} --fix-only --exit-zero
lint:
poetry run ruff check ${SOURCE_FILES} ${TEST_FILES}
poetry run mypy ${SOURCE_FILES} ${TEST_FILES}
test:
poetry run pytest tests
Pull Requestのマージをブロック
GitHub Actionsでのリントとテストが成功しないと、マージできないようにしたいです。
以下の手順で対応しました。
- "Sttings"タブから"Branch protection rule"を設定する画面に移動する
- "Require status checks to pass before merging"チェックボックスをONにする
- ステータスに"build"を入力する。検索候補である"build (3.11)"と"build (3.12)"を選択する
- "build"は、GitHub Actionsの設定ファイルに記載されている
jobs
配下のbuild
というjob_idに対応する
- "build"は、GitHub Actionsの設定ファイルに記載されている
ちなみに、TravisCIの場合は、ステータスに"travis"と入力して"Travis CI - Branch"と"Travis CI - Pull Request"を選択していました。
Github Actionsに移行した際、どのようなスタータスが候補になるのか分からなくて、少しハマりました。
所感
- ステータスは、最初から選択できる候補をすべて表示して欲しかった。そうすれば、今回ハマることはなかったと思う。
- GitHub Actionsの場合、
matrix
に指定したPythonのバージョンごとにステータスを選択できる。便利。
参考にしたサイト