From 5d5480ff1dcaf2f50b7185452472a4112504f922 Mon Sep 17 00:00:00 2001 From: Nikola Petkanski Date: Tue, 16 Jul 2024 01:19:02 +0300 Subject: [PATCH] Support for waiting on tcp port to open --- src/Wait/WaitForTcpPort.php | 52 ++++++++++++++++++++++++++ tests/Integration/WaitStrategyTest.php | 11 ++++++ 2 files changed, 63 insertions(+) create mode 100644 src/Wait/WaitForTcpPort.php diff --git a/src/Wait/WaitForTcpPort.php b/src/Wait/WaitForTcpPort.php new file mode 100644 index 0000000..a2f3b84 --- /dev/null +++ b/src/Wait/WaitForTcpPort.php @@ -0,0 +1,52 @@ +findContainerAddress($id); + + if (! is_string($remoteAddress)) { + throw new ContainerNotReadyException($id, new RuntimeException('Unable to find container IP address')); + } + + if (fsockopen($remoteAddress, $this->port) === false) { + throw new ContainerNotReadyException($id, new RuntimeException('Unable to connect to container TCP port')); + } + } + + /** + * @throws JsonException + */ + protected function findContainerAddress(string $id): ?string + { + $process = new Process(['docker', 'inspect', $id]); + $process->mustRun(); + + /** @var array $data */ + $data = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR); + + return $data[0]['NetworkSettings']['IPAddress'] ?? null; + } +} diff --git a/tests/Integration/WaitStrategyTest.php b/tests/Integration/WaitStrategyTest.php index 2424196..e78d0eb 100644 --- a/tests/Integration/WaitStrategyTest.php +++ b/tests/Integration/WaitStrategyTest.php @@ -13,6 +13,7 @@ use Testcontainer\Wait\WaitForHealthCheck; use Testcontainer\Wait\WaitForHttp; use Testcontainer\Wait\WaitForLog; +use Testcontainer\Wait\WaitForTcpPort; class WaitStrategyTest extends TestCase { @@ -90,6 +91,16 @@ public function testWaitForHTTP(): void $this->assertNotEmpty($response); } + public function testWaitForTcpPort(): void + { + $container = Container::make('nginx:alpine') + ->withWait(WaitForTcpPort::make(80)); + + $container->run(); + + $this->assertNotFalse(fsockopen($container->getAddress(), 80)); + } + public function testWaitForHealthCheck(): void { $container = Container::make('nginx')