Skip to content

Commit

Permalink
Support for waiting on tcp port to open
Browse files Browse the repository at this point in the history
  • Loading branch information
dinamic committed Jul 15, 2024
1 parent 3ddc75e commit 5d5480f
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Wait/WaitForTcpPort.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Testcontainer\Wait;

use JsonException;
use RuntimeException;
use Symfony\Component\Process\Process;
use Testcontainer\Exception\ContainerNotReadyException;

class WaitForTcpPort implements WaitInterface
{
public function __construct(protected readonly int $port)
{
}

public static function make(int $port): self
{
return new static($port);

Check failure on line 20 in src/Wait/WaitForTcpPort.php

View workflow job for this annotation

GitHub Actions / build

Unsafe usage of new static().
}

/**
* @throws JsonException
*/
public function wait(string $id): void
{
$remoteAddress = $this->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<int, array{'NetworkSettings': array{'IPAddress': string}}> $data */
$data = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);

return $data[0]['NetworkSettings']['IPAddress'] ?? null;
}
}
11 changes: 11 additions & 0 deletions tests/Integration/WaitStrategyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Testcontainer\Wait\WaitForHealthCheck;
use Testcontainer\Wait\WaitForHttp;
use Testcontainer\Wait\WaitForLog;
use Testcontainer\Wait\WaitForTcpPort;

class WaitStrategyTest extends TestCase
{
Expand Down Expand Up @@ -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')
Expand Down

0 comments on commit 5d5480f

Please sign in to comment.