Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2914

テスト実行時に DB の Port Listen を待つ

$
0
0

簡潔に

wait-for-itで特定の Port の Listen を待って、任意のコマンドを実行することができます

$ ./wait-for-it.sh -s-t 60 db:3306 -- php artisan test--testdox

対象読者

  • テスト実行時に DB などの Port Listen を待つ必要がある
    • 特に、 CI 環境で DB をコンテナで立ち上げるときなど
  • 今は sleepでなんとなく待って凌いでいるけど、本質的な解決じゃないのでなんとかしたいと思っている

以上の質問に全部 YES と回答した方

wait-for-it とは

https://github.com/vishnubob/wait-for-it

  • 特定のホストと TCP ポートが利用可能になるまで待つ機能をもった bash スクリプトです
    • 利用可能になるまで待ったあと、任意のコマンドを実行できます
    • 待つ時間の上限を指定できます ( -t | --timeoutオプション )

Installation

単純な bash スクリプトなので、 git cloneするか wget等で raw ファイルを DL するだけで使えます

$ wget https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh
$ bash ./wait-for-it.sh
Error: you need to provide a host and port to test.
Usage:
    wait-for-it.sh host:port [-s][-ttimeout][--command args]
    -h HOST | --host=HOST       Host or IP under test-p PORT | --port=PORT       TCP port under test
                                Alternatively, you specify the host and port as host:port
    -s | --strict               Only execute subcommand if the test succeeds
    -q | --quiet                Don't output any status messages
    -t TIMEOUT | --timeout=TIMEOUT
                                Timeout in seconds, zero for no timeout
    -- COMMAND ARGS             Execute command with args after the test finishes
$ sudo apt install wait-for-it
$ wait-for-it
Error: you need to provide a host and port to test.
Usage:
    wait-for-it host:port [-s][-ttimeout][--command args]
    -h HOST | --host=HOST       Host or IP under test-p PORT | --port=PORT       TCP port under test
                                Alternatively, you specify the host and port as host:port
    -s | --strict               Only execute subcommand if the test succeeds
    -q | --quiet                Don't output any status messages
    -t TIMEOUT | --timeout=TIMEOUT
                                Timeout in seconds, zero for no timeout
    -- COMMAND ARGS             Execute command with args after the test finishes
  • なぜかComposer package もあります
    • しかし fork されたもので最近は更新されてないので、公式を vcs で取り込むほうが良いと思います
    • Composer でインストールした場合は、デフォルトで vendor/bin/wait-for-it.shにインストールされます
"require-dev":{"vishnubob/wait-for-it":"dev-master"},"repositories":[{"type":"vcs","url":"https://github.com/vishnubob/wait-for-it"}],

使い方

  • 簡単なので READMEを見てもらうのが早いと思います
  • もっぱら CI 環境で DB コンテナの起動待ちなどに使っています
    • 以下の用に、複数の Port を待ちたい場合は wait-for-it をチェインすればいいです
$ ./vendor/bin/wait-for-it.sh -s-t 60 db:3306 -- ./vendor/bin/wait-for-it.sh -s-t 60 selenium:4444 -- php artisan dusk

参考


Viewing all articles
Browse latest Browse all 2914

Trending Articles