Be careful when you use pipx in GitHub Actions!

I ran tests with wrong Python version when I used pipx to install Hatch for a testing environment in GitHub Actions.

GitHub Actions でテスト環境作成用の Hatch を pipx でインストールしてたら、誤ったバージョンの Python でテストをしていたので、その失敗について記す。

GitHub Actions workflow file with the problem

---
name: Test

on:
  push:
    branches:
      - master
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version:
          - "3.10"
          - "3.11"
          - "3.12"
      fail-fast: false
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install hatch
        run: pipx install hatch
      - name: Lint
        run: hatch run lint:lint
      - name: Check type
        run: hatch run check-type
      - name: Test
        run: hatch run test --cov-report=xml
      - name: Upload coverage
        uses: codecov/codecov-action@v3

The problem is the following part.

- name: Install hatch
  run: pipx install hatch

By default, pipx uses the default Python in the runner, which is ubuntu-latest in this case. It doesn't use Python setup by actions/setup-python@v4.

Therefore, your virtual environment created with Hatch has the same Python version as the runner's.

The matrix strategy of python-version is totally useless, and your CI testing is no longer functional.

デフォルトで pipx はランナー(この場合ではubuntu-latest)の Python を使用する。 これはactions/setup-python@v4でセットアップした Python とは異なる。 そのため、Hatch で作成した仮想環境はランナーの Python と同じバージョンになる。 これは、ストラテジーで設定したpython-versionは全くの無意味であり、CI テストはもはや機能していないことを意味する。

To fix this, add PIPX_DEFAULT_PYTHON environment variable to the step as the following shows.

これを修正するには下記が示すように環境変数PIPX_DEFAULT_PYTHONをそのステップに加える。

- name: Install hatch
  run: pipx install hatch
  env:
    PIPX_DEFAULT_PYTHON: python

Refrection

I hadn't noticed the problem for 6 months because I didn't fully check the result of CI. As a result, all the tests during the period had come to nothing.

Fortunately, nothing wrong has happened with my project. I feel scared when I think an huge modification could be demanded.

6 ヵ月間もその問題に気づけなかったのは CI の結果を十分にチェックしていなかったからだ。 その結果、その間の全てのテストは無に帰してしまった。 幸運にもプロジェクトには何も悪いことは起こっていない。 莫大な修正が発生しえたことを考えると恐ろしくなる。

みんなも CI の結果には注意を配ろう!