pytestとblackのテスト環境をGitHub Actionsで作る

poetryのインストール

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

環境変数を通す

vim ~/.bash_profile

下記を追加

export PATH="$HOME/.poetry/bin:$PATH"

既存のプロジェクトの場合はinitでpyproject.tomlとpoetry.lockをルートディレクトリにつくる
質問は全てEnterで良いがメールアドレスも含まれてしまうためGitHubで公開したくない場合はAUTHORを適当に答える(あとでtomlファイルを編集できる)

poetry init

poetryのローカルでの実行はpoetry run

poetry add --dev pytest
poetry run pytest


GitHub Actionsでの実行は .github/workflow/pytest.pyに以下のファイルを用意

env:
  POETRY_VERSION: 1.1.7
  POETRY_URL: https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py

jobs:
  pytest:
    name: Run tests with pytest
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [3.7, 3.8, 3.9]
    steps:
      # checkout repository
      # See: https://github.com/actions/checkout
      - name: Checkout
        uses: actions/checkout@v2
      # set up python runtime
      # See: https://github.com/actions/setup-python
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v2
        with:
          python-version: ${{ matrix.python-version }}
      # install poetry
      - name: Install Poetry
        run: |
          curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python -
          echo "$HOME/.local/bin" >> $GITHUB_PATH
      # install python packages
      - name: Install Dependencies
        run: poetry install --no-interaction
      # pytest
      - name: Run Tests
        run: poetry run pytest tests/
  black:
    name: Check code style with Black
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Set up Python 3.9
        uses: actions/setup-python@v2
        with:
          python-version: 3.9
      - name: Install Poetry
        run: |
          curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python -
          echo "$HOME/.local/bin" >> $GITHUB_PATH
      - name: Install Dependencies
        run: poetry install --no-interaction
      - name: Check code style with Black
        run: poetry run black --check --diff .

最後にgit commitしてpush

git add pyproject.toml
git add poetry.lock
git add .github/workflows/pytest.yml
git commit -m 'add: pytest'
git push origin branch


参考
www.lifewithpython.com