LoginSignup
8
3

More than 3 years have passed since last update.

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

Posted at

簡潔に

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 とは

  • 特定のホストと 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] [-t timeout] [-- 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] [-t timeout] [-- 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

参考

8
3
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
8
3