Improve retry logic on start(), improved portBindings types

This commit is contained in:
Sergei Shitikov
2024-09-29 13:28:47 +02:00
parent 336f459d97
commit 2f1c8750e0
+11 -3
View File
@@ -47,6 +47,9 @@ class GenericContainer implements TestContainer
protected bool $isPrivileged = false; protected bool $isPrivileged = false;
protected ?string $networkName = null; protected ?string $networkName = null;
protected int $startAttempts = 0;
protected const MAX_START_ATTEMPTS = 2;
/** /**
* @var array<Mount> * @var array<Mount>
*/ */
@@ -173,13 +176,18 @@ class GenericContainer implements TestContainer
public function start(): StartedGenericContainer public function start(): StartedGenericContainer
{ {
$this->startAttempts++;
$containerConfig = $this->createContainerConfig(); $containerConfig = $this->createContainerConfig();
try { try {
/** @var ContainerCreateResponse|null $containerCreateResponse */ /** @var ContainerCreateResponse|null $containerCreateResponse */
$containerCreateResponse = $this->dockerClient->containerCreate($containerConfig); $containerCreateResponse = $this->dockerClient->containerCreate($containerConfig);
$this->id = $containerCreateResponse?->getId() ?? ''; $this->id = $containerCreateResponse?->getId() ?? '';
} catch (ContainerCreateNotFoundException) { } catch (ContainerCreateNotFoundException) {
if ($this->startAttempts >= self::MAX_START_ATTEMPTS) {
throw new \RuntimeException("Failed to start container after pulling image.");
}
// If the image is not found, pull it and try again // If the image is not found, pull it and try again
// TODO: add withPullPolicy support
$this->pullImage(); $this->pullImage();
return $this->start(); return $this->start();
} }
@@ -254,12 +262,12 @@ class GenericContainer implements TestContainer
} }
/** /**
* @return \ArrayObject<string, list<PortBinding>> * @return array<string, array<int, PortBinding>>
*/ */
protected function createPortBindings(): \ArrayObject protected function createPortBindings(): array
{ {
$portGenerator = new RandomUniquePortGenerator(); $portGenerator = new RandomUniquePortGenerator();
$portBindings = new \ArrayObject(); $portBindings = [];
foreach ($this->exposedPorts as $port) { foreach ($this->exposedPorts as $port) {
$portBinding = new PortBinding(); $portBinding = new PortBinding();