2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【GiHub Action】CIで全てのテストを通してしまった話

Last updated at Posted at 2024-07-10

はじめに

GitHub Actionのワークフローの改修をしたのですが、全てのテストを通るようになってしまっていました。ちなみに、幸いすぐ気付いたので影響はなかったですが、今後気をつけるように残しておきます。

問題のワークフロー

ワークフローは以下のようになってます。

  1. make testでPyhonのテストを動かす
  2. PRにカバレッジのコメントをつける (参考 :MishaKav/pytest-coverage-comment
.gihub/workflows/test.yml
  - name: Run tests
    run: make test
  - name: Create coverage report
    uses: MishaKav/pytest-coverage-comment@main
    with:
      pytest-coverage-path: ./pytest-coverage.txt
      junitxml-path: ./pytest.xml
      badge-title: Coverage

Makefileでは、pytestを動かして、カバレッジレポートを作成するのに必要なため、pipeを使用して、pytest-coverage.txtを作成しております。

makefile
.PHONY: test
test:
	pytest --cov=./ --junitxml=pytest.xml --cov-config=.coveragerc --cov-report=term-missing | tee pytest-coverage.txt

Pipeの罠

上記のmakefileでpipeを使ってしまっているので、前半のpytest --cov=./ --junitxml=pytest.xml --cov-config=.coveragerc --cov-report=term-missingの部分が落ちても、pipeで渡しているので、正常終了してしまいます。

試しに、以下のコードをローカルで実行してみます。

$ exit 1 | exit 0
$ echo $?
0

$?0 となっているので、正常終了していることがわかります。

$ set -o pipefail
$ exit 1 | exit 0
$ echo $?
1

$?が1となっているので、異常終了します。

また、オプション-eをつけることで、失敗した時点で異常終了させることが可能なので、set -eo pipefailのようにします。

makefileの罠

set -eo pipefailをつけることで、解決できたと思ったのですが、これだけだとGitHub Actionでのtestは期待通りに動作しませんでした。

例として、以下のmakefileを作ってみます。

makefile
SHELL=/bin/bash

.PHONY: foo
foo:
	set -eo pipefail
	exit 1 | exit 0

これを実行してみます。

$ make foo
$ echo $?
0

set -eo pipefailをしたのにも関わらず、makeコマンドだと正常終了してしまうことがわかります。

この問題の解決策は2通りあるのですが、まず1つ目は以下のように一行に書いてみると改善されます。

makefile
SHELL=/bin/bash

.PHONY: foo
foo:
	set -eo pipefail; exit 1 | exit 0
$ make foo
$ echo $?
2

2つ目は.SHELLFLAGSを設定することで解決できます。

makefile
SHELL=/bin/bash
.SHELLFLAGS := -eu -o pipefail -c

.PHONY: foo
foo:
	exit 1 | exit 0

.SHELLFLAGS := -eu -o pipefail -cのように設定しています。

  • -e : bashで実行したコマンドが失敗した場合に終了させる
  • -o pipefail : パイプの最初や途中で処理が失敗した場合、全体を失敗させる
  • -u : bashで変数未定義の場合にエラーで止める
  • -c : オプションを設定する時には必須のオプション(bash -c "echo 'Hello'"として動かす)

これを実行すると、無事エラーとなってくれました。

shell
$ make foo
exit 1 | exit 0
make: *** [makefile:6: foo] Error 1

参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?