diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2c5c78..b3616e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,11 +86,5 @@ jobs: name: vendor-artifact path: . - - name: Clean up Docker - run: docker system prune -f - - - name: Create Docker volume for migrations - run: docker volume create test-adm-migrations - - name: Run tests run: make tests diff --git a/Makefile b/Makefile index 83ead74..61140ff 100644 --- a/Makefile +++ b/Makefile @@ -14,11 +14,10 @@ PHP_VERSION := $(shell sed -n 's/.*"php": *"^\([0-9]*\.[0-9]*\)".*/\1/p' compose PHP_IMAGE := gustavofreze/php:${PHP_VERSION}-cli WORKSPACE := /var/www/html -DOCKER_RUN = docker run ${PLATFORM} -u ${HOST_USER} --rm ${TTY} --network=tiny-blocks --name test-lib \ +DOCKER_RUN = docker run ${PLATFORM} -u ${HOST_USER} --rm ${TTY} --network=tiny-blocks \ $(if $(DOCKER_GID),--group-add $(DOCKER_GID)) \ -e COMPOSER_HOME=/tmp/composer \ -v ${PWD}:${WORKSPACE} \ - -v ${PWD}/tests/Integration/Database/Migrations:/test-adm-migrations \ -v /var/run/docker.sock:/var/run/docker.sock \ ${PHP_IMAGE} @@ -41,14 +40,12 @@ tests: configure-test-environment ## Run unit and mutation tests with coverage @${DOCKER_RUN} composer tests .PHONY: test-file -test-file: ## Run tests for a specific file (usage: make test-file FILE=ClassNameTest) +test-file: configure-test-environment ## Run tests for a specific file (usage: make test-file FILE=ClassNameTest) @${DOCKER_RUN} composer test-file ${FILE} .PHONY: configure-test-environment configure-test-environment: - @if ! docker network inspect tiny-blocks > /dev/null 2>&1; then \ - docker network create --label tiny-blocks.docker-container=true tiny-blocks > /dev/null 2>&1; \ - fi + @docker network create tiny-blocks > /dev/null 2>&1 || true .PHONY: review review: configure-test-environment ## Run lint and static analysis diff --git a/README.md b/README.md index 72f74b1..5fb23d8 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ + [Setting tmpfs mounts](#setting-tmpfs-mounts) + [Setting environment variables](#setting-environment-variables) + [Disabling auto-remove](#disabling-auto-remove) + + [Setting the image pull timeout](#setting-the-image-pull-timeout) + [Copying files to a container](#copying-files-to-a-container) + [Stopping a container](#stopping-a-container) + [Stopping on shutdown](#stopping-on-shutdown) @@ -101,6 +102,9 @@ $container->run(commands: ['ls', '-la']); To wait after the container starts, register a wait strategy on the definition (see [Wait strategies](#wait-strategies)). +A container that fails to receive its files, to start, or to satisfy a wait strategy is removed before the failure is +raised, since nothing else holds it. + ### Running if not exists Starts a container only if a container with the same name does not exist yet, and reuses it otherwise. The returned @@ -109,6 +113,10 @@ neither `stopOnShutdown()` nor `remove()`: no single process owns it. When the c container removes the shared container once the test runner container exits. The wait strategies registered with `withWaitAfterStarted()` apply only when a new container starts. +Processes that ask for the same name at the same time are safe: Docker lets only one of them create the container, +and the others reuse it. A container another process has created but not started yet is handed over only once it +has started, so its address already carries the ports Docker assigned. + ```php $container->runIfNotExists(); ``` @@ -136,6 +144,9 @@ $execution->getOutput(); # "done\n" A non-zero exit raises `ContainerExitUnsuccessful` carrying what the container wrote to its standard error. A container still running when the timeout elapses raises `ContainerWaitTimeout`. +The removal runs in the PHP process that started the container. If that process is killed while the container runs, +the container is left behind. + ### Checking if the container was reused Tells whether the shared container came from an already-running instance. This distinguishes a fresh start from a @@ -152,7 +163,8 @@ $alreadyRunning = $started->wasReused(); Sets the Docker network the container should join. The network is created automatically when the container runs, if it does not already exist. Networks created by the library are labeled with `tiny-blocks.docker-container=true` for -safe cleanup. +safe cleanup. When a cleanup running in parallel removes the network before the container starts, the network is +created again and the container is started once more. ```php $container = $container->withNetwork(name: 'my-network'); @@ -209,10 +221,26 @@ By default, containers are removed when stopped. This disables that behavior. $container = $container->withoutAutoRemove(); ``` +### Setting the image pull timeout + +Bounds how long creating the container may take, which includes pulling the image when it is not available locally. +The default is 300 seconds. Raise it for large images on slow connections. + +```php +withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)); +``` + ### Copying files to a container Registers files or directories to be copied from the host into the container. The files are copied after the -container is created and before it starts, so its command already sees them. +container is created and before it starts, so its command already sees them. A copy that fails raises +`DockerCommandExecutionFailed` and removes the container that was created, so it never starts without its files. ```php $container = $container->copyToContainer(pathOnHost: '/path/to/files', pathOnContainer: '/path/in/container'); @@ -293,8 +321,9 @@ $container = $container #### Waiting for a dependency -Polls a readiness condition every 250 milliseconds until it holds, and raises `ContainerWaitTimeout` once the timeout -(30 seconds by default) elapses. This is useful when one container depends on another being fully ready. +Checks a readiness condition until it holds, pausing 250 milliseconds after each check that fails, and raises +`ContainerWaitTimeout` once the timeout (30 seconds by default) elapses. The time each check takes counts toward the +timeout. This is useful when one container depends on another being fully ready. ```php withMigrations(pathOnHost: '/path/to/migrations'); | `withTable` | `$table` | Overrides the history table name (default: `schema_history`). | | `withSchema` | `$schema` | Overrides the target schema (default: detected from MySQL). | | `withTimeout` | `$timeout` | Sets how long each command waits for Flyway to exit (120 s). | +| `withPullTimeout` | `$timeout` | Sets how long creating the container, pull included, may take. | | `withCredentials` | `$password`, `$username` | Overrides the credentials (default: root, from MySQL). | | `withConnectRetries` | `$retries` | Sets the number of database connection retries. | | `withMigrationNamingValidation` | | Rejects migrations whose file names break the naming convention. | @@ -597,8 +630,8 @@ Every factory accepts a `DockerClient`, the single boundary through which the li defaults to the local `docker` executable. A custom client can route the commands to another Docker-compatible engine, or stand in for the engine in the unit tests of code that builds containers. A `DockerCommand` carries only its arguments and runs through `execute()`, within the default timeout of the client. A `DockerCommandWithTimeout`, such as -a container run to completion or a stop, also carries the timeout it must finish within and runs through -`executeWithTimeout()`: +a container creation, a container run to completion, or a stop, also carries the timeout it must finish within and runs +through `executeWithTimeout()`: ```php timeout, - settings: $this->settings->withSource(source: $container), - container: $this->container - ); + return clone($this, ['settings' => $this->settings->withSource(source: $container)]); } /** @@ -148,11 +144,7 @@ public function withSource(MySQLDockerContainer $container): FlywayDockerContain */ public function withNetwork(string $name): FlywayDockerContainer { - return new FlywayDockerContainer( - timeout: $this->timeout, - settings: $this->settings, - container: $this->container->withNetwork(name: $name) - ); + return clone($this, ['container' => $this->container->withNetwork(name: $name)]); } /** @@ -165,7 +157,7 @@ public function withNetwork(string $name): FlywayDockerContainer */ public function withTimeout(Duration $timeout): FlywayDockerContainer { - return new FlywayDockerContainer(timeout: $timeout, settings: $this->settings, container: $this->container); + return clone($this, ['timeout' => $timeout]); } /** @@ -180,17 +172,16 @@ public function withMigrations(string $pathOnHost): FlywayDockerContainer { $template = 'filesystem:%s'; - return new FlywayDockerContainer( - timeout: $this->timeout, - settings: $this->settings->with( + return clone($this, [ + 'settings' => $this->settings->with( key: 'FLYWAY_LOCATIONS', value: sprintf($template, self::MIGRATIONS_ON_CONTAINER) ), - container: $this->container->copyToContainer( + 'container' => $this->container->copyToContainer( pathOnHost: $pathOnHost, pathOnContainer: self::MIGRATIONS_ON_CONTAINER ) - ); + ]); } /** @@ -243,6 +234,20 @@ public function withCredentials(string $password, string $username): FlywayDocke ->withEnvironmentVariable(key: 'FLYWAY_PASSWORD', value: $password); } + /** + * Returns a copy of the FlywayDockerContainer with the image pull timeout replaced. + * + *

The timeout bounds how long creating the container may take, which includes pulling the image when it + * is not available locally. It defaults to 300 seconds.

+ * + * @param Duration $timeout The longest time creating the container, image pull included, may take. + * @return FlywayDockerContainer The copy with the new image pull timeout. + */ + public function withPullTimeout(Duration $timeout): FlywayDockerContainer + { + return clone($this, ['container' => $this->container->withPullTimeout(timeout: $timeout)]); + } + /** * Returns a copy of the FlywayDockerContainer with the number of database connection retries replaced. * @@ -265,11 +270,7 @@ public function withConnectRetries(int $retries): FlywayDockerContainer */ public function withEnvironmentVariable(string $key, string $value): FlywayDockerContainer { - return new FlywayDockerContainer( - timeout: $this->timeout, - settings: $this->settings->with(key: $key, value: $value), - container: $this->container - ); + return clone($this, ['settings' => $this->settings->with(key: $key, value: $value)]); } /** diff --git a/src/GenericDockerContainer.php b/src/GenericDockerContainer.php index 37614fa..81d99d8 100644 --- a/src/GenericDockerContainer.php +++ b/src/GenericDockerContainer.php @@ -9,9 +9,8 @@ use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\Exceptions\ImageNameEmpty; use TinyBlocks\DockerContainer\Internal\Client\CommandLineDockerClient; -use TinyBlocks\DockerContainer\Internal\Containers\ContainerLauncher; -use TinyBlocks\DockerContainer\Internal\Containers\ContainerLookup; use TinyBlocks\DockerContainer\Internal\Containers\ContainerSharing; +use TinyBlocks\DockerContainer\Internal\Containers\ContainerStartup; use TinyBlocks\DockerContainer\Internal\Containers\ContainerWaits; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; use TinyBlocks\DockerContainer\Internal\Containers\OneShotContainer; @@ -59,7 +58,8 @@ public static function from( * Creates and starts the container, then applies the wait strategies registered with withWaitAfterStarted(). * *

Files registered with copyToContainer() are copied after the container is created and before it - * starts.

+ * starts. A container that fails to receive its files, to start, or to satisfy a wait strategy is + * removed.

* * @param array $commands The command, and its arguments, the container runs on startup. * @return DisposableContainer The started container, owned by this process. @@ -68,15 +68,8 @@ public static function from( */ public function run(array $commands = []): DisposableContainer { - $this->waits->waitBeforeRun(); - - $launcher = new ContainerLauncher(client: $this->client); - $id = $launcher->start(commands: $commands, definition: $this->definition); - $containerStarted = new ContainerLookup(client: $this->client)->byId(id: $id, name: $this->definition->name); - - $this->waits->waitAfterStarted(containerStarted: $containerStarted); - - return $containerStarted; + return new ContainerStartup(waits: $this->waits, client: $this->client, definition: $this->definition) + ->start(commands: $commands); } /** @@ -89,11 +82,7 @@ public function run(array $commands = []): DisposableContainer */ public function withName(string $name): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withName(name: $name) - ); + return clone($this, ['definition' => $this->definition->withName(name: $name)]); } /** @@ -107,11 +96,7 @@ public function withName(string $name): GenericDockerContainer */ public function withNetwork(string $name): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withNetwork(name: $name) - ); + return clone($this, ['definition' => $this->definition->withNetwork(name: $name)]); } /** @@ -122,6 +107,10 @@ public function withNetwork(string $name): GenericDockerContainer * current test runner container exits. The wait strategies registered with withWaitAfterStarted() apply only to * a newly started container.

* + *

Processes asking for the same name at the same time are safe: Docker lets only one of them create the + * container, and the others reuse it. A container another process has created but not started yet is handed + * over only once it has started.

+ * * @param array $commands The command, and its arguments, a new container runs on startup. * @return SharedContainer The existing or newly started container. * @throws DockerCommandExecutionFailed If a Docker command fails. @@ -129,10 +118,10 @@ public function withNetwork(string $name): GenericDockerContainer */ public function runIfNotExists(array $commands = []): SharedContainer { - return new ContainerSharing(client: $this->client)->share( - name: $this->definition->name, - start: fn(): DisposableContainer => $this->run(commands: $commands) - ); + $startup = new ContainerStartup(waits: $this->waits, client: $this->client, definition: $this->definition); + + return new ContainerSharing(client: $this->client, startup: $startup, definition: $this->definition) + ->share(commands: $commands); } /** @@ -146,11 +135,7 @@ public function runIfNotExists(array $commands = []): SharedContainer */ public function withTmpfsMount(string $pathOnContainer): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withTmpfsMount(pathOnContainer: $pathOnContainer) - ); + return clone($this, ['definition' => $this->definition->withTmpfsMount(pathOnContainer: $pathOnContainer)]); } /** @@ -165,14 +150,12 @@ public function withTmpfsMount(string $pathOnContainer): GenericDockerContainer */ public function copyToContainer(string $pathOnHost, string $pathOnContainer): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withCopyInstruction( + return clone($this, [ + 'definition' => $this->definition->withCopyInstruction( pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer ) - ); + ]); } /** @@ -207,11 +190,26 @@ public function runToCompletion(Duration $timeout, array $commands = []): Execut */ public function withPortMapping(int $portOnHost, int $portOnContainer): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withPortMapping(portOnHost: $portOnHost, portOnContainer: $portOnContainer) - ); + return clone($this, [ + 'definition' => $this->definition->withPortMapping( + portOnHost: $portOnHost, + portOnContainer: $portOnContainer + ) + ]); + } + + /** + * Returns a copy of the GenericDockerContainer with the image pull timeout replaced. + * + *

The timeout bounds how long creating the container may take, which includes pulling the image when it + * is not available locally. It defaults to 300 seconds.

+ * + * @param Duration $timeout The longest time creating the container, image pull included, may take. + * @return GenericDockerContainer The copy with the new image pull timeout. + */ + public function withPullTimeout(Duration $timeout): GenericDockerContainer + { + return clone($this, ['definition' => $this->definition->withPullTimeout(timeout: $timeout)]); } /** @@ -223,14 +221,12 @@ public function withPortMapping(int $portOnHost, int $portOnContainer): GenericD */ public function withVolumeMapping(string $pathOnHost, string $pathOnContainer): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withVolumeMapping( + return clone($this, [ + 'definition' => $this->definition->withVolumeMapping( pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer ) - ); + ]); } /** @@ -243,11 +239,7 @@ public function withVolumeMapping(string $pathOnHost, string $pathOnContainer): */ public function withWaitBeforeRun(ContainerWaitBeforeStarted $wait): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits->withBeforeRun(wait: $wait), - client: $this->client, - definition: $this->definition - ); + return clone($this, ['waits' => $this->waits->withBeforeRun(wait: $wait)]); } /** @@ -259,11 +251,7 @@ public function withWaitBeforeRun(ContainerWaitBeforeStarted $wait): GenericDock */ public function withoutAutoRemove(): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withoutAutoRemove() - ); + return clone($this, ['definition' => $this->definition->withoutAutoRemove()]); } /** @@ -277,11 +265,7 @@ public function withoutAutoRemove(): GenericDockerContainer */ public function withWaitAfterStarted(ContainerWaitAfterStarted $wait): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits->withAfterStarted(wait: $wait), - client: $this->client, - definition: $this->definition - ); + return clone($this, ['waits' => $this->waits->withAfterStarted(wait: $wait)]); } /** @@ -293,10 +277,6 @@ public function withWaitAfterStarted(ContainerWaitAfterStarted $wait): GenericDo */ public function withEnvironmentVariable(string $key, string $value): GenericDockerContainer { - return new GenericDockerContainer( - waits: $this->waits, - client: $this->client, - definition: $this->definition->withEnvironmentVariable(key: $key, value: $value) - ); + return clone($this, ['definition' => $this->definition->withEnvironmentVariable(key: $key, value: $value)]); } } diff --git a/src/Internal/Client/CommandExecution.php b/src/Internal/Client/CommandExecution.php new file mode 100644 index 0000000..54199ee --- /dev/null +++ b/src/Internal/Client/CommandExecution.php @@ -0,0 +1,30 @@ +execution->isSuccessful()) { + throw DockerCommandExecutionFailed::fromCommand(command: $this->command, execution: $this->execution); + } + + return $this->execution; + } +} diff --git a/src/Internal/Client/StrictExecutor.php b/src/Internal/Client/StrictExecutor.php index aad2596..a02ddfc 100644 --- a/src/Internal/Client/StrictExecutor.php +++ b/src/Internal/Client/StrictExecutor.php @@ -6,7 +6,7 @@ use TinyBlocks\DockerContainer\DockerClient; use TinyBlocks\DockerContainer\DockerCommand; -use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; +use TinyBlocks\DockerContainer\DockerCommandWithTimeout; use TinyBlocks\DockerContainer\ExecutionCompleted; final readonly class StrictExecutor @@ -17,12 +17,14 @@ public function __construct(private DockerClient $client) public function execute(DockerCommand $command): ExecutionCompleted { - $executionCompleted = $this->client->execute(command: $command); + return CommandExecution::from(command: $command, execution: $this->client->execute(command: $command)) + ->successful(); + } - if (!$executionCompleted->isSuccessful()) { - throw DockerCommandExecutionFailed::fromCommand(command: $command, execution: $executionCompleted); - } + public function executeWithTimeout(DockerCommandWithTimeout $command): ExecutionCompleted + { + $execution = $this->client->executeWithTimeout(command: $command); - return $executionCompleted; + return CommandExecution::from(command: $command, execution: $execution)->successful(); } } diff --git a/src/Internal/Commands/DockerCreate.php b/src/Internal/Commands/DockerCreate.php index a96bd06..95aed02 100644 --- a/src/Internal/Commands/DockerCreate.php +++ b/src/Internal/Commands/DockerCreate.php @@ -4,21 +4,26 @@ namespace TinyBlocks\DockerContainer\Internal\Commands; -use TinyBlocks\Collection\Collection; -use TinyBlocks\DockerContainer\DockerCommand; +use TinyBlocks\DockerContainer\DockerCommandWithTimeout; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; +use TinyBlocks\Time\Duration; -final readonly class DockerCreate implements DockerCommand +final readonly class DockerCreate implements DockerCommandWithTimeout { public const string MANAGED_LABEL = 'tiny-blocks.docker-container=true'; - private function __construct(private Collection $commands, private ContainerDefinition $definition) + private function __construct(private array $commands, private ContainerDefinition $definition) { } public static function from(array $commands, ContainerDefinition $definition): DockerCreate { - return new DockerCreate(commands: Collection::createFrom(elements: $commands), definition: $definition); + return new DockerCreate(commands: $commands, definition: $definition); + } + + public function timeout(): Duration + { + return $this->definition->pullTimeout; } public function toArguments(): array @@ -38,7 +43,7 @@ public function toArguments(): array self::MANAGED_LABEL, ...$this->definition->toArguments(), $this->definition->image->name, - ...$this->commands->toArray() + ...$this->commands ]; } } diff --git a/src/Internal/Commands/DockerExecute.php b/src/Internal/Commands/DockerExecute.php index b2a6a73..3589f9f 100644 --- a/src/Internal/Commands/DockerExecute.php +++ b/src/Internal/Commands/DockerExecute.php @@ -4,23 +4,22 @@ namespace TinyBlocks\DockerContainer\Internal\Commands; -use TinyBlocks\Collection\Collection; use TinyBlocks\DockerContainer\DockerCommand; use TinyBlocks\DockerContainer\Internal\Containers\Name; final readonly class DockerExecute implements DockerCommand { - private function __construct(private Name $name, private Collection $commands) + private function __construct(private Name $name, private array $commands) { } public static function from(Name $name, array $commands): DockerExecute { - return new DockerExecute(name: $name, commands: Collection::createFrom(elements: $commands)); + return new DockerExecute(name: $name, commands: $commands); } public function toArguments(): array { - return ['docker', 'exec', $this->name->value, ...$this->commands->toArray()]; + return ['docker', 'exec', $this->name->value, ...$this->commands]; } } diff --git a/src/Internal/Commands/DockerLookup.php b/src/Internal/Commands/DockerLookup.php new file mode 100644 index 0000000..53f73e4 --- /dev/null +++ b/src/Internal/Commands/DockerLookup.php @@ -0,0 +1,25 @@ +name->value]; + } +} diff --git a/src/Internal/Commands/DockerReaper.php b/src/Internal/Commands/DockerReaper.php index ab2701d..6145da9 100644 --- a/src/Internal/Commands/DockerReaper.php +++ b/src/Internal/Commands/DockerReaper.php @@ -4,27 +4,39 @@ namespace TinyBlocks\DockerContainer\Internal\Commands; -use TinyBlocks\DockerContainer\DockerCommand; +use TinyBlocks\DockerContainer\DockerCommandWithTimeout; use TinyBlocks\DockerContainer\Internal\Containers\Name; +use TinyBlocks\Time\Duration; -final readonly class DockerReaper implements DockerCommand +final readonly class DockerReaper implements DockerCommandWithTimeout { private function __construct( + private Duration $timeout, private Name $reaperName, private Name $containerName, private string $testRunnerHostname ) { } - public static function from(Name $reaperName, Name $containerName, string $testRunnerHostname): DockerReaper - { + public static function from( + Duration $timeout, + Name $reaperName, + Name $containerName, + string $testRunnerHostname + ): DockerReaper { return new DockerReaper( + timeout: $timeout, reaperName: $reaperName, containerName: $containerName, testRunnerHostname: $testRunnerHostname ); } + public function timeout(): Duration + { + return $this->timeout; + } + public function toArguments(): array { $template = implode(' ', [ diff --git a/src/Internal/Containers/ContainerInspection.php b/src/Internal/Containers/ContainerInspection.php index 1c0444e..6614692 100644 --- a/src/Internal/Containers/ContainerInspection.php +++ b/src/Internal/Containers/ContainerInspection.php @@ -4,7 +4,6 @@ namespace TinyBlocks\DockerContainer\Internal\Containers; -use TinyBlocks\Collection\Collection; use TinyBlocks\DockerContainer\Internal\Containers\Address\Address; use TinyBlocks\DockerContainer\Internal\Containers\Address\Hostname; use TinyBlocks\DockerContainer\Internal\Containers\Address\IP; @@ -14,6 +13,7 @@ final readonly class ContainerInspection { private const int LIMIT = 2; + private const string CREATED = 'created'; private const string SEPARATOR = '='; private function __construct(private array $inspectResult) @@ -41,6 +41,16 @@ public function toAddress(): Address ); } + public function toContainerId(): ContainerId + { + return ContainerId::from(value: (string)($this->inspectResult['Id'] ?? '')); + } + + public function wasNeverStarted(): bool + { + return ($this->inspectResult['State']['Status'] ?? '') === self::CREATED; + } + public function toEnvironmentVariables(): EnvironmentVariables { $rawEnvironment = ($this->inspectResult['Config']['Env'] ?? []); @@ -51,6 +61,6 @@ public function toEnvironmentVariables(): EnvironmentVariables $variables[$key] = $value; } - return EnvironmentVariables::from(variables: Collection::createFrom(elements: $variables)); + return EnvironmentVariables::from(variables: $variables); } } diff --git a/src/Internal/Containers/ContainerInspector.php b/src/Internal/Containers/ContainerInspector.php new file mode 100644 index 0000000..ed05790 --- /dev/null +++ b/src/Internal/Containers/ContainerInspector.php @@ -0,0 +1,26 @@ +client->execute(command: $command)->getOutput(), true); + + if (!is_array($inspectPayload) || empty($inspectPayload[0]) || !is_array($inspectPayload[0])) { + return null; + } + + return ContainerInspection::from(inspectResult: $inspectPayload[0]); + } +} diff --git a/src/Internal/Containers/ContainerLauncher.php b/src/Internal/Containers/ContainerLauncher.php index 9e97071..41342cf 100644 --- a/src/Internal/Containers/ContainerLauncher.php +++ b/src/Internal/Containers/ContainerLauncher.php @@ -5,10 +5,11 @@ namespace TinyBlocks\DockerContainer\Internal\Containers; use TinyBlocks\DockerContainer\DockerClient; +use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\Internal\Client\StrictExecutor; use TinyBlocks\DockerContainer\Internal\Commands\DockerCopy; use TinyBlocks\DockerContainer\Internal\Commands\DockerCreate; -use TinyBlocks\DockerContainer\Internal\Commands\DockerStart; +use TinyBlocks\DockerContainer\Internal\Commands\DockerRemove; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\CopyInstruction; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\Network; @@ -21,9 +22,18 @@ public function __construct(private DockerClient $client) public function start(array $commands, ContainerDefinition $definition): ContainerId { - $id = $this->create(commands: $commands, definition: $definition); + $attempt = new ContainerStartAttempt(client: $this->client); + $attempts = $definition->startAttempts(); - new StrictExecutor(client: $this->client)->execute(command: DockerStart::from(id: $id)); + do { + $attempts--; + $id = $this->create(commands: $commands, definition: $definition); + $failure = $attempt->failureOf(id: $id); + } while (!is_null($failure) && $attempts > 0); + + if (!is_null($failure)) { + throw $failure; + } return $id; } @@ -35,15 +45,21 @@ public function create(array $commands, ContainerDefinition $definition): Contai actions: static fn(Network $network) => $provisioner->provision(network: $network) ); + $executor = new StrictExecutor(client: $this->client); $dockerCreate = DockerCreate::from(commands: $commands, definition: $definition); - $creation = new StrictExecutor(client: $this->client)->execute(command: $dockerCreate); - $id = ContainerId::from(value: $creation->getOutput()); + $id = ContainerId::from(value: $executor->executeWithTimeout(command: $dockerCreate)->getOutput()); - $definition->copyInstructions->each( - actions: fn(CopyInstruction $instruction) => $this->client->execute( - command: DockerCopy::from(id: $id, instruction: $instruction) - ) - ); + try { + $definition->copyInstructions->each( + actions: static fn(CopyInstruction $instruction) => $executor->execute( + command: DockerCopy::from(id: $id, instruction: $instruction) + ) + ); + } catch (DockerCommandExecutionFailed $failure) { + $this->client->execute(command: DockerRemove::from(id: $id)); + + throw $failure; + } return $id; } diff --git a/src/Internal/Containers/ContainerLookup.php b/src/Internal/Containers/ContainerLookup.php index 313075a..2e090c3 100644 --- a/src/Internal/Containers/ContainerLookup.php +++ b/src/Internal/Containers/ContainerLookup.php @@ -6,7 +6,9 @@ use TinyBlocks\DockerContainer\DockerClient; use TinyBlocks\DockerContainer\Internal\Commands\DockerInspect; +use TinyBlocks\DockerContainer\Internal\Commands\DockerLookup; use TinyBlocks\DockerContainer\Internal\Exceptions\DockerContainerNotFound; +use TinyBlocks\DockerContainer\Waits\ContainerWaitForDependency; final readonly class ContainerLookup { @@ -16,20 +18,49 @@ public function __construct(private DockerClient $client) public function byId(ContainerId $id, Name $name): Started { - $inspectPayload = json_decode($this->client->execute(command: DockerInspect::from(id: $id))->getOutput(), true); + $inspection = new ContainerInspector(client: $this->client)->inspect(command: DockerInspect::from(id: $id)); - if (!is_array($inspectPayload) || empty($inspectPayload[0]) || !is_array($inspectPayload[0])) { + if (is_null($inspection)) { throw new DockerContainerNotFound(name: $name); } - $inspection = ContainerInspection::from(inspectResult: $inspectPayload[0]); + return Started::from(id: $id, name: $name, client: $this->client, inspection: $inspection); + } + + public function byName(Name $name): ?Started + { + $inspection = new ContainerInspector(client: $this->client)->inspect(command: DockerLookup::from(name: $name)); + + if (is_null($inspection)) { + return null; + } + + if (!$inspection->wasNeverStarted()) { + return Started::from( + id: $inspection->toContainerId(), + name: $name, + client: $this->client, + inspection: $inspection + ); + } + + ContainerWaitForDependency::untilReady(condition: ContainerPastCreation::from(name: $name, lookup: $this)) + ->waitBefore(); + + return $this->byName(name: $name); + } + + public function isPastCreation(Name $name): bool + { + $inspection = new ContainerInspector(client: $this->client)->inspect(command: DockerLookup::from(name: $name)); + + return is_null($inspection) || !$inspection->wasNeverStarted(); + } + + public function wasNeverStarted(ContainerId $id): bool + { + $inspection = new ContainerInspector(client: $this->client)->inspect(command: DockerInspect::from(id: $id)); - return new Started( - id: $id, - name: $name, - client: $this->client, - address: $inspection->toAddress(), - environmentVariables: $inspection->toEnvironmentVariables() - ); + return !is_null($inspection) && $inspection->wasNeverStarted(); } } diff --git a/src/Internal/Containers/ContainerPastCreation.php b/src/Internal/Containers/ContainerPastCreation.php new file mode 100644 index 0000000..f5e37fb --- /dev/null +++ b/src/Internal/Containers/ContainerPastCreation.php @@ -0,0 +1,24 @@ +lookup->isPastCreation(name: $this->name); + } +} diff --git a/src/Internal/Containers/ContainerReaper.php b/src/Internal/Containers/ContainerReaper.php index 7f346b4..baff3fb 100644 --- a/src/Internal/Containers/ContainerReaper.php +++ b/src/Internal/Containers/ContainerReaper.php @@ -7,6 +7,7 @@ use TinyBlocks\DockerContainer\DockerClient; use TinyBlocks\DockerContainer\Internal\Commands\DockerList; use TinyBlocks\DockerContainer\Internal\Commands\DockerReaper; +use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; final readonly class ContainerReaper { @@ -14,23 +15,24 @@ public function __construct(private DockerClient $client) { } - public function watch(Name $containerName): void + public function watch(ContainerDefinition $definition): void { if (!HostEnvironment::isInsideDocker()) { return; } $template = 'tiny-blocks-reaper-%s'; - $reaperName = Name::from(value: sprintf($template, $containerName->value)); + $reaperName = Name::from(value: sprintf($template, $definition->name->value)); if (trim($this->client->execute(command: DockerList::from(name: $reaperName))->getOutput()) !== '') { return; } - $this->client->execute( + $this->client->executeWithTimeout( command: DockerReaper::from( + timeout: $definition->pullTimeout, reaperName: $reaperName, - containerName: $containerName, + containerName: $definition->name, testRunnerHostname: HostEnvironment::containerHostname() ) ); diff --git a/src/Internal/Containers/ContainerSharing.php b/src/Internal/Containers/ContainerSharing.php index fc207b7..0a005be 100644 --- a/src/Internal/Containers/ContainerSharing.php +++ b/src/Internal/Containers/ContainerSharing.php @@ -4,26 +4,28 @@ namespace TinyBlocks\DockerContainer\Internal\Containers; -use Closure; use TinyBlocks\DockerContainer\DockerClient; -use TinyBlocks\DockerContainer\Internal\Commands\DockerList; +use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; final readonly class ContainerSharing { - public function __construct(private DockerClient $client) - { + public function __construct( + private DockerClient $client, + private ContainerStartup $startup, + private ContainerDefinition $definition + ) { } - public function share(Name $name, Closure $start): Shared + public function share(array $commands): Shared { - $listing = trim($this->client->execute(command: DockerList::from(name: $name))->getOutput()); + $name = $this->definition->name; $lookup = new ContainerLookup(client: $this->client); + $existing = $lookup->byName(name: $name); + $shared = is_null($existing) + ? new SharedStart(name: $name, lookup: $lookup, startup: $this->startup)->startOrJoin(commands: $commands) + : Shared::reused(containerStarted: $existing); - $shared = $listing === '' - ? Shared::created(containerStarted: $start()) - : Shared::reused(containerStarted: $lookup->byId(id: ContainerId::from(value: $listing), name: $name)); - - new ContainerReaper(client: $this->client)->watch(containerName: $name); + new ContainerReaper(client: $this->client)->watch(definition: $this->definition); return $shared; } diff --git a/src/Internal/Containers/ContainerStartAttempt.php b/src/Internal/Containers/ContainerStartAttempt.php new file mode 100644 index 0000000..fc98e53 --- /dev/null +++ b/src/Internal/Containers/ContainerStartAttempt.php @@ -0,0 +1,31 @@ +client)->execute(command: DockerStart::from(id: $id)); + + return null; + } catch (DockerCommandExecutionFailed $failure) { + $this->client->execute(command: DockerRemove::from(id: $id)); + + return $failure; + } + } +} diff --git a/src/Internal/Containers/ContainerStartup.php b/src/Internal/Containers/ContainerStartup.php new file mode 100644 index 0000000..e8a6d6f --- /dev/null +++ b/src/Internal/Containers/ContainerStartup.php @@ -0,0 +1,48 @@ +launch(commands: $commands); + + try { + return $this->handOver(id: $id); + } catch (Throwable $failure) { + $this->client->execute(command: DockerRemove::from(id: $id)); + + throw $failure; + } + } + + public function launch(array $commands): ContainerId + { + $this->waits->waitBeforeRun(); + + return new ContainerLauncher(client: $this->client)->start(commands: $commands, definition: $this->definition); + } + + public function handOver(ContainerId $id): Started + { + $containerStarted = new ContainerLookup(client: $this->client)->byId(id: $id, name: $this->definition->name); + $this->waits->waitAfterStarted(containerStarted: $containerStarted); + + return $containerStarted; + } +} diff --git a/src/Internal/Containers/ContainerWaits.php b/src/Internal/Containers/ContainerWaits.php index a965a23..065c8fd 100644 --- a/src/Internal/Containers/ContainerWaits.php +++ b/src/Internal/Containers/ContainerWaits.php @@ -30,7 +30,7 @@ public function waitBeforeRun(): void public function withBeforeRun(ContainerWaitBeforeStarted $wait): ContainerWaits { - return new ContainerWaits(beforeRun: $this->beforeRun->add($wait), afterStarted: $this->afterStarted); + return clone($this, ['beforeRun' => $this->beforeRun->add($wait)]); } public function waitAfterStarted(ContainerStarted $containerStarted): void @@ -42,6 +42,6 @@ public function waitAfterStarted(ContainerStarted $containerStarted): void public function withAfterStarted(ContainerWaitAfterStarted $wait): ContainerWaits { - return new ContainerWaits(beforeRun: $this->beforeRun, afterStarted: $this->afterStarted->add($wait)); + return clone($this, ['afterStarted' => $this->afterStarted->add($wait)]); } } diff --git a/src/Internal/Containers/Definitions/ContainerDefinition.php b/src/Internal/Containers/Definitions/ContainerDefinition.php index 6cbe2d1..79a3f87 100644 --- a/src/Internal/Containers/Definitions/ContainerDefinition.php +++ b/src/Internal/Containers/Definitions/ContainerDefinition.php @@ -5,21 +5,28 @@ namespace TinyBlocks\DockerContainer\Internal\Containers\Definitions; use TinyBlocks\Collection\Collection; +use TinyBlocks\Collection\KeyPreservation; use TinyBlocks\DockerContainer\Internal\Containers\Image; use TinyBlocks\DockerContainer\Internal\Containers\Name; +use TinyBlocks\Time\Duration; final readonly class ContainerDefinition { + private const int SINGLE_START_ATTEMPT = 1; + private const int START_ATTEMPTS_ON_A_NETWORK = 2; + private const int DEFAULT_PULL_TIMEOUT_IN_SECONDS = 300; + private function __construct( public Name $name, public Image $image, - public Removal $removal, public Collection $networks, + public Duration $pullTimeout, public Collection $tmpfsMounts, public Collection $portMappings, public Collection $volumeMappings, public Collection $copyInstructions, - public Collection $environmentVariables + public Collection $environmentVariables, + public Removal $removal = Removal::AUTOMATIC ) { } @@ -28,8 +35,8 @@ public static function create(string $image): ContainerDefinition return new ContainerDefinition( name: Name::generated(), image: Image::from(image: $image), - removal: Removal::AUTOMATIC, networks: Collection::createFromEmpty(), + pullTimeout: Duration::fromSeconds(seconds: self::DEFAULT_PULL_TIMEOUT_IN_SECONDS), tmpfsMounts: Collection::createFromEmpty(), portMappings: Collection::createFromEmpty(), volumeMappings: Collection::createFromEmpty(), @@ -40,17 +47,7 @@ public static function create(string $image): ContainerDefinition public function withName(string $name): ContainerDefinition { - return new ContainerDefinition( - name: Name::from(value: $name), - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + return clone($this, ['name' => Name::from(value: $name)]); } public function toArguments(): array @@ -61,125 +58,71 @@ public function toArguments(): array ->merge(other: $this->tmpfsMounts) ->add($this->removal) ->merge(other: $this->environmentVariables) - ->reduce( - accumulator: static fn(array $arguments, ContainerOption $option): array => [ - ...$arguments, - ...$option->toArguments() - ], - initial: [] - ); + ->map(transformations: static fn(ContainerOption $option): array => $option->toArguments()) + ->flatten() + ->toArray(keyPreservation: KeyPreservation::DISCARD); } public function withNetwork(string $name): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: Collection::createFrom(elements: [Network::from(name: $name)]), - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + return clone($this, ['networks' => Collection::createFrom(elements: [Network::from(name: $name)])]); + } + + public function startAttempts(): int + { + return $this->networks->isEmpty() ? self::SINGLE_START_ATTEMPT : self::START_ATTEMPTS_ON_A_NETWORK; } public function withTmpfsMount(string $pathOnContainer): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts->add(TmpfsMount::from(pathOnContainer: $pathOnContainer)), - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + return clone($this, [ + 'tmpfsMounts' => $this->tmpfsMounts->add(TmpfsMount::from(pathOnContainer: $pathOnContainer)) + ]); } public function withPortMapping(int $portOnHost, int $portOnContainer): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings->add( + return clone($this, [ + 'portMappings' => $this->portMappings->add( PortMapping::from(portOnHost: $portOnHost, portOnContainer: $portOnContainer) - ), - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + ) + ]); + } + + public function withPullTimeout(Duration $timeout): ContainerDefinition + { + return clone($this, ['pullTimeout' => $timeout]); } public function withVolumeMapping(string $pathOnHost, string $pathOnContainer): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings->add( + return clone($this, [ + 'volumeMappings' => $this->volumeMappings->add( VolumeMapping::from(pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer) - ), - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + ) + ]); } public function withoutAutoRemove(): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: Removal::MANUAL, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables - ); + return clone($this, ['removal' => Removal::MANUAL]); } public function withCopyInstruction(string $pathOnHost, string $pathOnContainer): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions->add( + return clone($this, [ + 'copyInstructions' => $this->copyInstructions->add( CopyInstruction::from(pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer) - ), - environmentVariables: $this->environmentVariables - ); + ) + ]); } public function withEnvironmentVariable(string $key, string $value): ContainerDefinition { - return new ContainerDefinition( - name: $this->name, - image: $this->image, - removal: $this->removal, - networks: $this->networks, - tmpfsMounts: $this->tmpfsMounts, - portMappings: $this->portMappings, - volumeMappings: $this->volumeMappings, - copyInstructions: $this->copyInstructions, - environmentVariables: $this->environmentVariables->add( + return clone($this, [ + 'environmentVariables' => $this->environmentVariables->add( EnvironmentVariable::from(key: $key, value: $value) ) - ); + ]); } } diff --git a/src/Internal/Containers/Drivers/Flyway/FlywaySettings.php b/src/Internal/Containers/Drivers/Flyway/FlywaySettings.php index 9306eaf..523c0c1 100644 --- a/src/Internal/Containers/Drivers/Flyway/FlywaySettings.php +++ b/src/Internal/Containers/Drivers/Flyway/FlywaySettings.php @@ -9,26 +9,23 @@ final readonly class FlywaySettings { - private const string HISTORY_TABLE = 'schema_history'; - private const string ROOT_USERNAME = 'root'; - - private function __construct(private ?MySQLDockerContainer $source, private array $settings) + private function __construct(private FlywaySource $source, private array $settings = []) { } public static function create(): FlywaySettings { - return new FlywaySettings(source: null, settings: []); + return new FlywaySettings(source: FlywaySource::none()); } public function with(string $key, string $value): FlywaySettings { - return new FlywaySettings(source: $this->source, settings: [...$this->settings, $key => $value]); + return clone($this, ['settings' => [...$this->settings, $key => $value]]); } public function applyTo(GenericDockerContainer $container): GenericDockerContainer { - $settings = [...$this->sourceSettings(), ...$this->settings]; + $settings = [...$this->source->toSettings(), ...$this->settings]; return array_reduce( array_keys($settings), @@ -40,24 +37,6 @@ public function applyTo(GenericDockerContainer $container): GenericDockerContain public function withSource(MySQLDockerContainer $source): FlywaySettings { - return new FlywaySettings(source: $source, settings: $this->settings); - } - - private function sourceSettings(): array - { - if (is_null($this->source)) { - return []; - } - - $sourceStarted = $this->source->runIfNotExists(); - $environmentVariables = $sourceStarted->getEnvironmentVariables(); - - return [ - 'FLYWAY_URL' => $sourceStarted->getJdbcUrl(), - 'FLYWAY_USER' => self::ROOT_USERNAME, - 'FLYWAY_TABLE' => self::HISTORY_TABLE, - 'FLYWAY_SCHEMAS' => $environmentVariables->getValueBy(key: 'MYSQL_DATABASE'), - 'FLYWAY_PASSWORD' => $environmentVariables->getValueBy(key: 'MYSQL_ROOT_PASSWORD') - ]; + return clone($this, ['source' => FlywaySource::from(container: $source)]); } } diff --git a/src/Internal/Containers/Drivers/Flyway/FlywaySource.php b/src/Internal/Containers/Drivers/Flyway/FlywaySource.php new file mode 100644 index 0000000..38cb165 --- /dev/null +++ b/src/Internal/Containers/Drivers/Flyway/FlywaySource.php @@ -0,0 +1,45 @@ +container)) { + return []; + } + + $sourceStarted = $this->container->runIfNotExists(); + $environmentVariables = $sourceStarted->getEnvironmentVariables(); + + return [ + 'FLYWAY_URL' => $sourceStarted->getJdbcUrl(), + 'FLYWAY_USER' => self::ROOT_USERNAME, + 'FLYWAY_TABLE' => self::HISTORY_TABLE, + 'FLYWAY_SCHEMAS' => $environmentVariables->getValueBy(key: 'MYSQL_DATABASE'), + 'FLYWAY_PASSWORD' => $environmentVariables->getValueBy(key: 'MYSQL_ROOT_PASSWORD') + ]; + } +} diff --git a/src/Internal/Containers/Drivers/MySQL/MySQLCommands.php b/src/Internal/Containers/Drivers/MySQL/MySQLCommands.php index 4ec9976..e4402e4 100644 --- a/src/Internal/Containers/Drivers/MySQL/MySQLCommands.php +++ b/src/Internal/Containers/Drivers/MySQL/MySQLCommands.php @@ -10,7 +10,7 @@ final class MySQLCommands private const string USER_ROOT = 'root'; private const string CREATE_USER = "CREATE USER IF NOT EXISTS '%s'@'%s' IDENTIFIED BY '%s';"; private const string ROOT_PASSWORD = 'MYSQL_PWD=%s'; - private const string CREATE_DATABASE = 'CREATE DATABASE IF NOT EXISTS %s;'; + private const string CREATE_DATABASE = 'CREATE DATABASE IF NOT EXISTS `%s`;'; private const string FLUSH_PRIVILEGES = 'FLUSH PRIVILEGES;'; private function __construct() @@ -22,7 +22,7 @@ public static function setupDatabase(string $database, array $grantedHosts, stri $statements = []; if ($database !== '') { - $statements[] = sprintf(self::CREATE_DATABASE, $database); + $statements[] = sprintf(self::CREATE_DATABASE, str_replace('`', '``', $database)); } foreach ($grantedHosts as $host) { diff --git a/src/Internal/Containers/Drivers/MySQL/MySQLStartup.php b/src/Internal/Containers/Drivers/MySQL/MySQLStartup.php index 4fb40f2..0409de3 100644 --- a/src/Internal/Containers/Drivers/MySQL/MySQLStartup.php +++ b/src/Internal/Containers/Drivers/MySQL/MySQLStartup.php @@ -5,6 +5,7 @@ namespace TinyBlocks\DockerContainer\Internal\Containers\Drivers\MySQL; use TinyBlocks\DockerContainer\ContainerStarted; +use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\Waits\Conditions\MySQL\MySQLReady; use TinyBlocks\DockerContainer\Waits\ContainerWaitForDependency; use TinyBlocks\Time\Duration; @@ -12,20 +13,18 @@ final readonly class MySQLStartup { private const array EPHEMERAL_SERVER_ARGUMENTS = ['--skip-log-bin']; - private const int DEFAULT_READINESS_TIMEOUT_IN_SECONDS = 30; + private const int DEFAULT_READINESS_TIMEOUT_IN_SECONDS = 60; private function __construct( - private array $grantedHosts, - private array $serverArguments, - private Duration $readinessTimeout + private Duration $readinessTimeout, + private array $grantedHosts = [], + private array $serverArguments = [] ) { } public static function create(): MySQLStartup { return new MySQLStartup( - grantedHosts: [], - serverArguments: [], readinessTimeout: Duration::fromSeconds(seconds: self::DEFAULT_READINESS_TIMEOUT_IN_SECONDS) ); } @@ -39,13 +38,19 @@ public function complete(ContainerStarted $containerStarted): void $environmentVariables = $containerStarted->getEnvironmentVariables(); $database = $environmentVariables->getValueBy(key: 'MYSQL_DATABASE'); - if ($database !== '' || !empty($this->grantedHosts)) { - $setup = MySQLCommands::setupDatabase( - database: $database, - grantedHosts: $this->grantedHosts, - rootPassword: $environmentVariables->getValueBy(key: 'MYSQL_ROOT_PASSWORD') - ); - $containerStarted->executeAfterStarted(commands: $setup); + if ($database === '' && empty($this->grantedHosts)) { + return; + } + + $setup = MySQLCommands::setupDatabase( + database: $database, + grantedHosts: $this->grantedHosts, + rootPassword: $environmentVariables->getValueBy(key: 'MYSQL_ROOT_PASSWORD') + ); + $execution = $containerStarted->executeAfterStarted(commands: $setup); + + if (!$execution->isSuccessful()) { + throw DockerCommandExecutionFailed::from(reason: $execution->getOutput(), command: implode(' ', $setup)); } } @@ -56,28 +61,16 @@ public function commandsFor(array $commands): array public function withGrantedHosts(array $hosts): MySQLStartup { - return new MySQLStartup( - grantedHosts: $hosts, - serverArguments: $this->serverArguments, - readinessTimeout: $this->readinessTimeout - ); + return clone($this, ['grantedHosts' => $hosts]); } public function withEphemeralStorage(): MySQLStartup { - return new MySQLStartup( - grantedHosts: $this->grantedHosts, - serverArguments: self::EPHEMERAL_SERVER_ARGUMENTS, - readinessTimeout: $this->readinessTimeout - ); + return clone($this, ['serverArguments' => self::EPHEMERAL_SERVER_ARGUMENTS]); } public function withReadinessTimeout(Duration $timeout): MySQLStartup { - return new MySQLStartup( - grantedHosts: $this->grantedHosts, - serverArguments: $this->serverArguments, - readinessTimeout: $timeout - ); + return clone($this, ['readinessTimeout' => $timeout]); } } diff --git a/src/Internal/Containers/Environment/EnvironmentVariables.php b/src/Internal/Containers/Environment/EnvironmentVariables.php index c927fbe..99598b7 100644 --- a/src/Internal/Containers/Environment/EnvironmentVariables.php +++ b/src/Internal/Containers/Environment/EnvironmentVariables.php @@ -4,7 +4,6 @@ namespace TinyBlocks\DockerContainer\Internal\Containers\Environment; -use TinyBlocks\Collection\Collection; use TinyBlocks\DockerContainer\EnvironmentVariables as ContainerEnvironmentVariables; final readonly class EnvironmentVariables implements ContainerEnvironmentVariables @@ -13,9 +12,9 @@ private function __construct(private array $variables) { } - public static function from(Collection $variables): EnvironmentVariables + public static function from(array $variables): EnvironmentVariables { - return new EnvironmentVariables(variables: $variables->toArray()); + return new EnvironmentVariables(variables: $variables); } public function getValueBy(string $key): string diff --git a/src/Internal/Containers/OneShotAttempt.php b/src/Internal/Containers/OneShotAttempt.php new file mode 100644 index 0000000..231ab70 --- /dev/null +++ b/src/Internal/Containers/OneShotAttempt.php @@ -0,0 +1,44 @@ +client->executeWithTimeout( + command: DockerStartAttached::from(id: $id, timeout: $this->timeout) + ); + + if ($execution->isSuccessful()) { + return $execution; + } + + if ($retryable && new ContainerLookup(client: $this->client)->wasNeverStarted(id: $id)) { + return null; + } + + throw new ContainerExitUnsuccessful(name: $this->name->value, output: $execution->getOutput()); + } catch (DockerCommandExecutionFailed) { + throw ContainerWaitTimeout::forExit(name: $this->name->value, timeout: $this->timeout); + } finally { + $this->client->execute(command: DockerRemove::from(id: $id)); + } + } +} diff --git a/src/Internal/Containers/OneShotContainer.php b/src/Internal/Containers/OneShotContainer.php index 2d536aa..00b5d75 100644 --- a/src/Internal/Containers/OneShotContainer.php +++ b/src/Internal/Containers/OneShotContainer.php @@ -5,12 +5,7 @@ namespace TinyBlocks\DockerContainer\Internal\Containers; use TinyBlocks\DockerContainer\DockerClient; -use TinyBlocks\DockerContainer\Exceptions\ContainerExitUnsuccessful; -use TinyBlocks\DockerContainer\Exceptions\ContainerWaitTimeout; -use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\ExecutionCompleted; -use TinyBlocks\DockerContainer\Internal\Commands\DockerRemove; -use TinyBlocks\DockerContainer\Internal\Commands\DockerStartAttached; use TinyBlocks\DockerContainer\Internal\Containers\Definitions\ContainerDefinition; use TinyBlocks\Time\Duration; @@ -23,21 +18,15 @@ public function __construct(private DockerClient $client) public function run(Duration $timeout, array $commands, ContainerDefinition $definition): ExecutionCompleted { $launcher = new ContainerLauncher(client: $this->client); - $id = $launcher->create(commands: $commands, definition: $definition->withoutAutoRemove()); - $startAttached = DockerStartAttached::from(id: $id, timeout: $timeout); + $attempt = new OneShotAttempt(name: $definition->name, client: $this->client, timeout: $timeout); + $attempts = $definition->startAttempts(); - try { - $execution = $this->client->executeWithTimeout(command: $startAttached); + do { + $attempts--; + $id = $launcher->create(commands: $commands, definition: $definition->withoutAutoRemove()); + $execution = $attempt->run(id: $id, retryable: $attempts > 0); + } while (is_null($execution)); - if (!$execution->isSuccessful()) { - throw new ContainerExitUnsuccessful(name: $definition->name->value, output: $execution->getOutput()); - } - - return $execution; - } catch (DockerCommandExecutionFailed) { - throw ContainerWaitTimeout::forExit(name: $definition->name->value, timeout: $timeout); - } finally { - $this->client->execute(command: DockerRemove::from(id: $id)); - } + return $execution; } } diff --git a/src/Internal/Containers/SharedStart.php b/src/Internal/Containers/SharedStart.php new file mode 100644 index 0000000..a4ac1fd --- /dev/null +++ b/src/Internal/Containers/SharedStart.php @@ -0,0 +1,31 @@ +startup->launch(commands: $commands); + } catch (DockerCommandExecutionFailed $failure) { + $winner = $this->lookup->byName(name: $this->name); + + if (is_null($winner)) { + throw $failure; + } + + return Shared::reused(containerStarted: $winner); + } + + return Shared::created(containerStarted: $this->startup->handOver(id: $id)); + } +} diff --git a/src/Internal/Containers/Started.php b/src/Internal/Containers/Started.php index 2970b66..a7cefc4 100644 --- a/src/Internal/Containers/Started.php +++ b/src/Internal/Containers/Started.php @@ -17,7 +17,7 @@ final readonly class Started implements DisposableContainer { - public function __construct( + private function __construct( private ContainerId $id, private Name $name, private DockerClient $client, @@ -26,6 +26,21 @@ public function __construct( ) { } + public static function from( + ContainerId $id, + Name $name, + DockerClient $client, + ContainerInspection $inspection + ): Started { + return new Started( + id: $id, + name: $name, + client: $client, + address: $inspection->toAddress(), + environmentVariables: $inspection->toEnvironmentVariables() + ); + } + public function stop(Duration $gracePeriod): ExecutionCompleted { return $this->client->executeWithTimeout(command: DockerStop::from(id: $this->id, gracePeriod: $gracePeriod)); diff --git a/src/MySQLDockerContainer.php b/src/MySQLDockerContainer.php index e05e4c7..cfea7e8 100644 --- a/src/MySQLDockerContainer.php +++ b/src/MySQLDockerContainer.php @@ -4,6 +4,7 @@ namespace TinyBlocks\DockerContainer; +use Throwable; use TinyBlocks\DockerContainer\Exceptions\ContainerWaitTimeout; use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\Exceptions\ImageNameEmpty; @@ -53,18 +54,25 @@ public static function from( * Starts the container and waits until MySQL accepts connections. * *

Once MySQL answers, the database is created and root is granted access from the granted hosts, when - * either was configured.

+ * either was configured. A container that never accepts connections, or whose setup fails, is removed.

* * @param array $commands The arguments passed to the MySQL server on startup. * @return MySQLContainerStarted&DisposableContainer The started container, owned by this process and ready for * connections. - * @throws DockerCommandExecutionFailed If a Docker command fails. + * @throws DockerCommandExecutionFailed If a Docker command fails, or MySQL rejects the database setup. * @throws ContainerWaitTimeout If MySQL does not accept connections within the readiness timeout. */ public function run(array $commands = []): MySQLContainerStarted&DisposableContainer { $containerStarted = $this->container->run(commands: $this->startup->commandsFor(commands: $commands)); - $this->startup->complete(containerStarted: $containerStarted); + + try { + $this->startup->complete(containerStarted: $containerStarted); + } catch (Throwable $failure) { + $containerStarted->remove(); + + throw $failure; + } return MySQLStarted::from(containerStarted: $containerStarted); } @@ -79,7 +87,7 @@ public function run(array $commands = []): MySQLContainerStarted&DisposableConta */ public function withName(string $name): MySQLDockerContainer { - return new MySQLDockerContainer(startup: $this->startup, container: $this->container->withName(name: $name)); + return clone($this, ['container' => $this->container->withName(name: $name)]); } /** @@ -90,7 +98,7 @@ public function withName(string $name): MySQLDockerContainer */ public function withNetwork(string $name): MySQLDockerContainer { - return new MySQLDockerContainer(startup: $this->startup, container: $this->container->withNetwork(name: $name)); + return clone($this, ['container' => $this->container->withNetwork(name: $name)]); } /** @@ -147,7 +155,7 @@ public function withUsername(string $user): MySQLDockerContainer * * @param array $commands The arguments passed to a new MySQL server on startup. * @return MySQLContainerStarted&SharedContainer The existing or newly started container, ready for connections. - * @throws DockerCommandExecutionFailed If a Docker command fails. + * @throws DockerCommandExecutionFailed If a Docker command fails, or MySQL rejects the database setup. * @throws ContainerWaitTimeout If MySQL does not accept connections within the readiness timeout. */ public function runIfNotExists(array $commands = []): MySQLContainerStarted&SharedContainer @@ -169,10 +177,9 @@ public function runIfNotExists(array $commands = []): MySQLContainerStarted&Shar */ public function copyToContainer(string $pathOnHost, string $pathOnContainer): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup, - container: $this->container->copyToContainer(pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer) - ); + return clone($this, [ + 'container' => $this->container->copyToContainer(pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer) + ]); } /** @@ -184,10 +191,23 @@ public function copyToContainer(string $pathOnHost, string $pathOnContainer): My */ public function withPortMapping(int $portOnHost, int $portOnContainer): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup, - container: $this->container->withPortMapping(portOnHost: $portOnHost, portOnContainer: $portOnContainer) - ); + return clone($this, [ + 'container' => $this->container->withPortMapping(portOnHost: $portOnHost, portOnContainer: $portOnContainer) + ]); + } + + /** + * Returns a copy of the MySQLDockerContainer with the image pull timeout replaced. + * + *

The timeout bounds how long creating the container may take, which includes pulling the image when it + * is not available locally. It defaults to 300 seconds.

+ * + * @param Duration $timeout The longest time creating the container, image pull included, may take. + * @return MySQLDockerContainer The copy with the new image pull timeout. + */ + public function withPullTimeout(Duration $timeout): MySQLDockerContainer + { + return clone($this, ['container' => $this->container->withPullTimeout(timeout: $timeout)]); } /** @@ -198,10 +218,7 @@ public function withPortMapping(int $portOnHost, int $portOnContainer): MySQLDoc */ public function withGrantedHosts(array $hosts = ['%', '172.%']): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup->withGrantedHosts(hosts: $hosts), - container: $this->container - ); + return clone($this, ['startup' => $this->startup->withGrantedHosts(hosts: $hosts)]); } /** @@ -224,10 +241,12 @@ public function withRootPassword(string $rootPassword): MySQLDockerContainer */ public function withVolumeMapping(string $pathOnHost, string $pathOnContainer): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup, - container: $this->container->withVolumeMapping(pathOnHost: $pathOnHost, pathOnContainer: $pathOnContainer) - ); + return clone($this, [ + 'container' => $this->container->withVolumeMapping( + pathOnHost: $pathOnHost, + pathOnContainer: $pathOnContainer + ) + ]); } /** @@ -238,10 +257,7 @@ public function withVolumeMapping(string $pathOnHost, string $pathOnContainer): */ public function withWaitBeforeRun(ContainerWaitBeforeStarted $wait): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup, - container: $this->container->withWaitBeforeRun(wait: $wait) - ); + return clone($this, ['container' => $this->container->withWaitBeforeRun(wait: $wait)]); } /** @@ -251,7 +267,7 @@ public function withWaitBeforeRun(ContainerWaitBeforeStarted $wait): MySQLDocker */ public function withoutAutoRemove(): MySQLDockerContainer { - return new MySQLDockerContainer(startup: $this->startup, container: $this->container->withoutAutoRemove()); + return clone($this, ['container' => $this->container->withoutAutoRemove()]); } /** @@ -265,27 +281,24 @@ public function withoutAutoRemove(): MySQLDockerContainer */ public function withEphemeralStorage(): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup->withEphemeralStorage(), - container: $this->container->withTmpfsMount(pathOnContainer: self::DATA_DIRECTORY) - ); + return clone($this, [ + 'startup' => $this->startup->withEphemeralStorage(), + 'container' => $this->container->withTmpfsMount(pathOnContainer: self::DATA_DIRECTORY) + ]); } /** * Returns a copy of the MySQLDockerContainer with the readiness timeout replaced. * *

The readiness timeout bounds how long run() and runIfNotExists() wait for MySQL to accept connections. - * It defaults to 30 seconds.

+ * It defaults to 60 seconds.

* * @param Duration $timeout The longest time to wait for MySQL to accept connections. * @return MySQLDockerContainer The copy with the new readiness timeout. */ public function withReadinessTimeout(Duration $timeout): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup->withReadinessTimeout(timeout: $timeout), - container: $this->container - ); + return clone($this, ['startup' => $this->startup->withReadinessTimeout(timeout: $timeout)]); } /** @@ -297,9 +310,6 @@ public function withReadinessTimeout(Duration $timeout): MySQLDockerContainer */ public function withEnvironmentVariable(string $key, string $value): MySQLDockerContainer { - return new MySQLDockerContainer( - startup: $this->startup, - container: $this->container->withEnvironmentVariable(key: $key, value: $value) - ); + return clone($this, ['container' => $this->container->withEnvironmentVariable(key: $key, value: $value)]); } } diff --git a/src/Waits/ContainerWaitForDependency.php b/src/Waits/ContainerWaitForDependency.php index d23115b..77fed12 100644 --- a/src/Waits/ContainerWaitForDependency.php +++ b/src/Waits/ContainerWaitForDependency.php @@ -11,12 +11,12 @@ /** * Wait strategy that polls a readiness condition until it holds or the timeout elapses. * - *

The condition is checked every 250 milliseconds and at least once, even when the timeout is zero. The timeout - * defaults to 30 seconds.

+ *

The condition is checked at least once, even when the timeout is zero, and again 250 milliseconds after each + * check that fails. The time each check takes counts toward the timeout, which defaults to 30 seconds.

*/ final readonly class ContainerWaitForDependency implements ContainerWaitBeforeStarted { - private const int MICROSECONDS_PER_SECOND = 1_000_000; + private const int NANOSECONDS_PER_SECOND = 1_000_000_000; private const int DEFAULT_TIMEOUT_IN_SECONDS = 30; private const int POLL_INTERVAL_IN_MICROSECONDS = 250_000; @@ -40,16 +40,15 @@ public static function untilReady(ContainerReady $condition): ContainerWaitForDe public function waitBefore(): void { - $budgetInMicroseconds = ($this->timeout->toSeconds() * self::MICROSECONDS_PER_SECOND); - $attempts = max(1, intdiv($budgetInMicroseconds, self::POLL_INTERVAL_IN_MICROSECONDS)); + $deadline = (hrtime(true) + ($this->timeout->toSeconds() * self::NANOSECONDS_PER_SECOND)); - for ($attempt = 0; $attempt < $attempts; $attempt++) { + do { if ($this->condition->isReady()) { return; } usleep(self::POLL_INTERVAL_IN_MICROSECONDS); - } + } while (hrtime(true) < $deadline); throw ContainerWaitTimeout::forReadiness(timeout: $this->timeout); } @@ -62,6 +61,6 @@ public function waitBefore(): void */ public function withTimeout(Duration $timeout): ContainerWaitForDependency { - return new ContainerWaitForDependency(timeout: $timeout, condition: $this->condition); + return clone($this, ['timeout' => $timeout]); } } diff --git a/tests/Integration/DockerContainerTest.php b/tests/Integration/DockerContainerTest.php index dc593f7..b9e7b1e 100644 --- a/tests/Integration/DockerContainerTest.php +++ b/tests/Integration/DockerContainerTest.php @@ -57,7 +57,7 @@ public function testMySQLWhenStartedThenAcceptsConnectionsToItsDatabase(): void public function testRunToCompletionWhenCommandSucceedsThenReturnsItsOutput(): void { /** @Given a container whose command prints a line and exits successfully */ - $container = GenericDockerContainer::from(image: 'php:fpm-alpine'); + $container = GenericDockerContainer::from(image: 'alpine:3.22'); /** @When the container runs to completion */ $execution = $container->runToCompletion( @@ -75,17 +75,17 @@ public function testRunIfNotExistsWhenCalledTwiceThenTheSameContainerIsReused(): $name = sprintf('test-container-%s', gethostname()); /** @And a container that sleeps once started */ - $container = GenericDockerContainer::from(image: 'php:fpm-alpine') + $container = GenericDockerContainer::from(image: 'alpine:3.22') ->withName(name: $name) ->withNetwork(name: 'tiny-blocks') ->withWaitBeforeRun(wait: ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 1))) ->withEnvironmentVariable(key: 'TEST', value: '123'); /** @And the container started for the first time */ - $firstRun = $container->runIfNotExists(); + $firstRun = $container->runIfNotExists(commands: ['sleep', '60']); /** @When the same container is asked for again */ - $secondRun = GenericDockerContainer::from(image: 'php:fpm-alpine') + $secondRun = GenericDockerContainer::from(image: 'alpine:3.22') ->withName(name: $name) ->runIfNotExists(); @@ -101,7 +101,7 @@ public function testRunWhenFilesAreCopiedThenTheyExistBeforeTheContainerStarts() $template = '%s/Files'; /** @And a container whose command exits at once unless the marker file is already present */ - $container = GenericDockerContainer::from(image: 'php:fpm-alpine') + $container = GenericDockerContainer::from(image: 'alpine:3.22') ->withNetwork(name: 'tiny-blocks') ->copyToContainer(pathOnHost: sprintf($template, __DIR__), pathOnContainer: '/copied'); @@ -164,7 +164,7 @@ public function testCleanAndMigrateWhenMigrationsAreGivenThenDatabaseIsPopulated public function testRunToCompletionWhenCommandFailsThenContainerExitUnsuccessfulCarriesItsError(): void { /** @Given a container whose command reports an error and exits with a non-zero status */ - $container = GenericDockerContainer::from(image: 'php:fpm-alpine'); + $container = GenericDockerContainer::from(image: 'alpine:3.22'); /** @Then an exception carrying the error the container wrote should be thrown */ $this->expectException(ContainerExitUnsuccessful::class); diff --git a/tests/Models/InspectResponseFixture.php b/tests/Models/InspectResponseFixture.php index bc8befd..85ae89a 100644 --- a/tests/Models/InspectResponseFixture.php +++ b/tests/Models/InspectResponseFixture.php @@ -12,6 +12,7 @@ private function __construct() public static function build( string $id = '6acae5967be05d8441b4109eea3e4dec5e775068a2a99d95808afb21b2e0a2c8', + string $status = 'running', string $hostname = 'alpine', string $ipAddress = '172.22.0.2', array $environment = [], @@ -22,6 +23,10 @@ public static function build( return [ 'Id' => $id, 'Name' => sprintf('/%s', $hostname), + 'State' => [ + 'Status' => $status, + 'Running' => $status === 'running' + ], 'Config' => [ 'Hostname' => $hostname, 'ExposedPorts' => $exposedPorts, diff --git a/tests/Unit/ClientMock.php b/tests/Unit/ClientMock.php index 13c451c..e653b80 100644 --- a/tests/Unit/ClientMock.php +++ b/tests/Unit/ClientMock.php @@ -13,25 +13,29 @@ final class ClientMock implements DockerClient { private const array UNANSWERED = [ - 'docker ps' => ['', false], - 'docker exec' => ['', true], - 'docker stop' => ['', true], - 'docker start' => ['', true], - 'docker create' => ['', true], - 'docker inspect' => ['[null]', false], - 'docker start --attach' => ['', true], - '' => ['', true] + 'docker cp' => ['', true], + 'docker ps' => ['', false], + 'docker exec' => ['', true], + 'docker stop' => ['', true], + 'docker start' => ['', true], + 'docker create' => ['', true], + 'docker inspect' => ['[null]', false], + 'docker start --attach' => ['', true], + 'docker inspect --type container' => ['', false], + '' => ['', true] ]; private array $responses = [ - 'docker start --attach' => [], - 'docker inspect' => [], - 'docker create' => [], - 'docker start' => [], - 'docker stop' => [], - 'docker exec' => [], - 'docker ps' => [], - '' => [] + 'docker inspect --type container' => [], + 'docker start --attach' => [], + 'docker inspect' => [], + 'docker create' => [], + 'docker start' => [], + 'docker stop' => [], + 'docker exec' => [], + 'docker cp' => [], + 'docker ps' => [], + '' => [] ]; private array $executedArguments = []; @@ -76,6 +80,11 @@ public function getRequestedTimeouts(): array return $this->requestedTimeouts; } + public function withDockerCopyResponse(string $output, bool $isSuccessful = true): void + { + $this->responses['docker cp'][] = [$output, $isSuccessful]; + } + public function withDockerListResponse(string $output): void { $this->responses['docker ps'][] = [$output, !empty($output)]; @@ -101,6 +110,16 @@ public function withDockerCreateResponse(string $output, bool $isSuccessful = tr $this->responses['docker create'][] = [$output, $isSuccessful]; } + public function withDockerLookupResponse(array $inspectResult): void + { + $this->responses['docker inspect --type container'][] = [json_encode([$inspectResult]), true]; + } + + public function withDockerStartException(Throwable $exception): void + { + $this->responses['docker start'][] = $exception; + } + public function withDockerExecuteResponse(string $output, bool $isSuccessful = true): void { $this->responses['docker exec'][] = [$output, $isSuccessful]; diff --git a/tests/Unit/ClockMock.php b/tests/Unit/ClockMock.php new file mode 100644 index 0000000..87dd980 --- /dev/null +++ b/tests/Unit/ClockMock.php @@ -0,0 +1,55 @@ +client = new ClientMock(); } + protected function tearDown(): void + { + ClockMock::release(); + } + public function testMigrateThenFlywayCleanIsNotEnabled(): void { /** @Given a Flyway container */ @@ -299,7 +306,7 @@ public function testMigrateWhenTimeoutIsGivenThenWaitsUpToThatTimeout(): void $flyway->migrate(); /** @Then the wait for Flyway to exit should be bounded by the given timeout */ - self::assertSame([45], $this->client->getRequestedTimeouts()); + self::assertSame([300, 45], $this->client->getRequestedTimeouts()); } public function testWithEnvironmentVariableThenPassesTheFlywaySetting(): void @@ -423,7 +430,7 @@ public function testMigrateWhenTimeoutIsNotGivenThenWaitsUpToTwoMinutes(): void $flyway->migrate(); /** @Then the wait for Flyway to exit should be bounded by 120 seconds */ - self::assertSame([120], $this->client->getRequestedTimeouts()); + self::assertSame([300, 120], $this->client->getRequestedTimeouts()); } public function testWithTimeoutThenLeavesTheOriginalDefinitionUntouched(): void @@ -441,7 +448,7 @@ public function testWithTimeoutThenLeavesTheOriginalDefinitionUntouched(): void $flyway->migrate(); /** @Then it should still wait up to the default timeout */ - self::assertSame([120], $this->client->getRequestedTimeouts()); + self::assertSame([300, 120], $this->client->getRequestedTimeouts()); } public function testWithMigrationNamingValidationThenEnablesTheValidation(): void @@ -515,8 +522,10 @@ public function testMigrateWhenTwoFlywayContainersRunThenEachHasItsOwnName(): vo /** @And another Flyway container from the same image, as a parallel test run would create */ $parallelFlyway = FlywayDockerContainer::from(image: 'flyway/flyway:12-alpine', client: $this->client); - /** @And the Docker daemon creates a Flyway container for each run */ + /** @And the Docker daemon creates the container, for the first time */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon creates the container, for the second time */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); /** @And the first Flyway container has migrated */ @@ -600,6 +609,22 @@ public function testMigrateWhenFlywayOutlastsTimeoutThenFlywayContainerIsRemoved } } + public function testMigrateWhenPullTimeoutIsGivenThenContainerCreationIsBoundedByIt(): void + { + /** @Given a Flyway container whose image may take up to ten minutes to pull */ + $flyway = FlywayDockerContainer::from(image: 'flyway/flyway:12-alpine', client: $this->client) + ->withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)); + + /** @And the Docker daemon creates the Flyway container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @When migrate is called */ + $flyway->migrate(); + + /** @Then the creation should be bounded by the pull timeout, and the run by the default timeout */ + self::assertSame([600, 120], $this->client->getRequestedTimeouts()); + } + public function testMigrateWhenFlywayCannotBeCreatedThenDockerCommandExecutionFailed(): void { /** @Given a Flyway container */ diff --git a/tests/Unit/GenericDockerContainerTest.php b/tests/Unit/GenericDockerContainerTest.php index b2783b9..1f58212 100644 --- a/tests/Unit/GenericDockerContainerTest.php +++ b/tests/Unit/GenericDockerContainerTest.php @@ -5,9 +5,9 @@ namespace Test\Unit; use InvalidArgumentException; -use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use Test\Models\InspectResponseFixture; +use TinyBlocks\DockerContainer\Exceptions\ContainerExitUnsuccessful; use TinyBlocks\DockerContainer\Exceptions\ContainerWaitTimeout; use TinyBlocks\DockerContainer\Exceptions\DockerCommandExecutionFailed; use TinyBlocks\DockerContainer\GenericDockerContainer; @@ -24,102 +24,141 @@ final class GenericDockerContainerTest extends TestCase protected function setUp(): void { + ClockMock::freeze(); + $this->client = new ClientMock(); } - public function testStopContainer(): void + protected function tearDown(): void { - /** @Given a running container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-test'); + HostMock::reset(); + ClockMock::release(); + } - /** @And the Docker daemon returns valid responses */ + public function testRunWhenNoNameIsGivenThenANameIsGenerated(): void + { + /** @Given a container without a name */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client); + + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-test')); - $this->client->withDockerStopResponse(output: ''); - /** @And the container is started */ + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'auto-generated' + ) + ); + + /** @When the container is started */ $started = $container->run(); - /** @When the container is stopped */ - $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); + /** @Then the container should have an auto-generated name (non-empty) */ + self::assertNotEmpty($started->getName()); + } - /** @Then the stop should be successful */ - self::assertTrue($stopped->isSuccessful()); + public function testFromWhenImageNameIsEmptyThenImageNameEmpty(): void + { + /** @Then an InvalidArgumentException should be thrown */ + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Image name cannot be empty.'); + + /** @When creating a container with an empty image name */ + GenericDockerContainer::from(image: ''); } - public function testExecuteAfterStarted(): void + public function testRemoveWhenCalledTwiceThenNoFailureIsRaised(): void { /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'exec-test'); + ->withName(name: 'already-removed'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-test')); - $this->client->withDockerExecuteResponse(output: 'command output'); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'already-removed') + ); /** @And the container is started */ $started = $container->run(); - /** @When commands are executed inside the running container */ - $execution = $started->executeAfterStarted(commands: ['ls', '-la']); + /** @When remove is called twice */ + $started->remove(); + $started->remove(); - /** @Then the execution should be successful */ - self::assertTrue($execution->isSuccessful()); - self::assertSame('command output', $execution->getOutput()); + /** @Then both removals should have been issued without any failure */ + self::assertCount( + 2, + array_filter( + $this->client->getExecutedCommandLines(), + static fn(string $commandLine): bool => str_starts_with($commandLine, 'docker rm') + ) + ); } - public function testExceptionWhenRunFails(): void + public function testRunWhenBindingHasNoHostPortThenItIsSkipped(): void { - /** @Given a container that will fail to start */ - $container = GenericDockerContainer::from(image: 'invalid:image', client: $this->client) - ->withName(name: 'fail-test'); + /** @Given a container whose inspect payload includes a binding with no HostPort key */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'no-host-port-key'); - /** @And the Docker daemon returns a failure */ - $this->client->withDockerCreateResponse(output: 'Cannot connect to the Docker daemon.', isSuccessful: false); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @Then a DockerCommandExecutionFailed exception should be thrown */ - $this->expectException(DockerCommandExecutionFailed::class); - $this->expectExceptionMessageMatches('/Cannot connect to the Docker daemon/'); + /** @And the Docker daemon returns an inspect response with a partial binding */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'no-host-port-key', + exposedPorts: ['80/tcp' => (object)[]], + hostPortBindings: [ + '80/tcp' => [['HostIp' => '0.0.0.0']] + ] + ) + ); /** @When the container is started */ - $container->run(); + $started = $container->run(); + + /** @Then bindings lacking HostPort should be skipped without errors */ + self::assertEmpty($started->getAddress()->getPorts()->hostPorts()); } - public function testRunContainerSuccessfully(): void + public function testRunWhenNoPortIsExposedThenFirstPortsAreNull(): void { - /** @Given a container configured with an image and a name */ + /** @Given a container with no exposed ports */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'test-alpine'); + ->withName(name: 'no-ports'); - /** @And the Docker daemon returns a valid container ID and inspect response */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'test-alpine', - environment: ['PATH=/usr/local/bin'] - ) - ); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'no-ports')); /** @When the container is started */ $started = $container->run(); - /** @Then the container should be running with the expected properties */ - self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); - self::assertSame('test-alpine', $started->getName()); - self::assertSame('test-alpine', $started->getAddress()->getHostname()); - self::assertSame('172.22.0.2', $started->getAddress()->getIp()); + /** @Then firstExposedPort should return null */ + self::assertNull($started->getAddress()->getPorts()->firstExposedPort()); + self::assertEmpty($started->getAddress()->getPorts()->exposedPorts()); + + /** @And firstHostPort should return null */ + self::assertNull($started->getAddress()->getPorts()->firstHostPort()); + self::assertEmpty($started->getAddress()->getPorts()->hostPorts()); } - public function testRunContainerWithCommands(): void + public function testRunWhenCommandsAreGivenThenContainerIsStarted(): void { /** @Given a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) ->withName(name: 'cmd-test'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'cmd-test')); /** @When the container is started with commands */ @@ -129,15 +168,37 @@ public function testRunContainerWithCommands(): void self::assertSame('cmd-test', $started->getName()); } - public function testContainerWithHostPortMapping(): void + public function testRunWhenAFileIsRegisteredThenContainerIsStarted(): void + { + /** @Given a container with files to copy */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'copy-test') + ->copyToContainer(pathOnHost: '/host/config', pathOnContainer: '/app/config'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'copy-test')); + + /** @When the container is started (docker cp is automatically called) */ + $started = $container->run(); + + /** @Then the container should be running */ + self::assertSame('copy-test', $started->getName()); + } + + public function testRunWhenHostPortIsMappedThenBothPortsAreExposed(): void { /** @Given a container with a host port mapping */ $container = GenericDockerContainer::from(image: 'mysql:8.4', client: $this->client) ->withName(name: 'host-port') ->withPortMapping(portOnHost: 33060, portOnContainer: 3306); - /** @And the Docker daemon returns a response with host port bindings */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon returns a response with host port bindings */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'host-port', @@ -159,587 +220,511 @@ public function testContainerWithHostPortMapping(): void self::assertSame([33060], $started->getAddress()->getPorts()->hostPorts()); } - public function testExceptionWhenImageNameIsEmpty(): void - { - /** @Then an InvalidArgumentException should be thrown */ - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Image name cannot be empty.'); - - /** @When creating a container with an empty image name */ - GenericDockerContainer::from(image: ''); - } - - public function testRunCommandLineIncludesNetwork(): void + public function testRunWhenHostPortIsZeroThenItIsDroppedFromResult(): void { - /** @Given a container with a network */ + /** @Given a container whose inspect payload reports a binding with HostPort equal to zero */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'net-cmd') - ->withNetwork(name: 'my-network'); + ->withName(name: 'zero-host-port'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'net-cmd')); - - /** @When the container is started */ - $container->run(); - /** @Then the first command should be the network creation */ - $networkCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString( - 'docker network create --label tiny-blocks.docker-container=true my-network', - $networkCommand + /** @And the Docker daemon returns an inspect response with HostPort zero alongside a valid binding */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'zero-host-port', + exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]], + hostPortBindings: [ + '80/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '0']], + '443/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8443']] + ] + ) ); - /** @And the docker run command should contain the network argument */ - $runCommand = $this->client->getExecutedCommandLines()[2]; - self::assertStringContainsString('--network=my-network', $runCommand); - } - - public function testRunContainerWithWaitBeforeRun(): void - { - /** @Given a condition that is immediately ready */ - $condition = $this->createMock(ContainerReady::class); - $condition->expects(self::once())->method('isReady')->willReturn(true); - - /** @And a container with a wait-before-run condition */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'wait-test') - ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $condition)); - - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-test')); - /** @When the container is started */ $started = $container->run(); - /** @Then the container should be running (wait was called) */ - self::assertSame('wait-test', $started->getName()); + /** @Then only strictly positive host ports should be retained */ + self::assertSame([8443], $started->getAddress()->getPorts()->hostPorts()); } - public function testRunContainerWithoutAutoRemove(): void + public function testStopWhenContainerIsRunningThenStopIsSuccessful(): void { - /** @Given a container with auto-remove disabled */ + /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'persistent') - ->withoutAutoRemove(); + ->withName(name: 'stop-test'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'persistent')); - - /** @When the container is started */ - $started = $container->run(); - - /** @Then the container should be running */ - self::assertSame('persistent', $started->getName()); - } - public function testStopExecutesDockerStopCommand(): void - { - /** @Given a running container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-cmd'); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-test')); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-cmd')); + /** @And the Docker daemon stops the container */ $this->client->withDockerStopResponse(output: ''); /** @And the container is started */ $started = $container->run(); /** @When the container is stopped */ - $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); + $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); - /** @Then a docker stop command should have been executed with the container ID */ - $stopCommand = $this->client->getExecutedCommandLines()[3]; - self::assertStringStartsWith('docker stop', $stopCommand); - self::assertStringContainsString(InspectResponseFixture::shortContainerId(), $stopCommand); + /** @Then the stop should be successful */ + self::assertTrue($stopped->isSuccessful()); } - public function testRemoveCanBeCalledMultipleTimes(): void + public function testStopWhenGracePeriodIsGivenThenStopIsSuccessful(): void { /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'already-removed'); + ->withName(name: 'stop-timeout'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'already-removed') + inspectResult: InspectResponseFixture::build(hostname: 'stop-timeout') ); + /** @And the Docker daemon stops the container */ + $this->client->withDockerStopResponse(output: ''); + /** @And the container is started */ $started = $container->run(); - /** @When remove is called twice */ - $started->remove(); - $started->remove(); + /** @When the container is stopped with a custom timeout */ + $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); - /** @Then no exception should be thrown */ - self::assertTrue(true); + /** @Then the stop should be successful */ + self::assertTrue($stopped->isSuccessful()); } - public function testRunCommandLineIncludesCommands(): void + public function testRunWhenPortIsMappedThenCreateCommandPublishesIt(): void { - /** @Given a container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'args-cmd'); + /** @Given a container with a port mapping */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'port-cmd') + ->withPortMapping(portOnHost: 8080, portOnContainer: 80); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'args-cmd')); - /** @When the container is started with commands */ - $container->run(commands: ['-connectRetries=15', 'clean', 'migrate']); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'port-cmd')); - /** @Then the docker run command should end with the commands */ + /** @When the container is started */ + $container->run(); + + /** @Then the executed docker run command should contain the port mapping argument */ $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('-connectRetries=15 clean migrate', $runCommand); + self::assertStringContainsString('--publish 8080:80', $runCommand); } - public function testStopContainerWithCustomTimeout(): void + public function testRunContainerThenInspectCommandTargetsContainerId(): void { - /** @Given a running container */ + /** @Given a container configured with an image and a name */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-timeout'); + ->withName(name: 'inspect-cmd'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'stop-timeout') - ); - $this->client->withDockerStopResponse(output: ''); - /** @And the container is started */ - $started = $container->run(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'inspect-cmd')); - /** @When the container is stopped with a custom timeout */ - $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); + /** @When the container is started */ + $container->run(); - /** @Then the stop should be successful */ - self::assertTrue($stopped->isSuccessful()); + /** @Then a docker inspect command should have been executed for the container ID */ + $inspectCommand = $this->client->getExecutedCommandLines()[2]; + self::assertSame(sprintf('docker inspect %s', InspectResponseFixture::shortContainerId()), $inspectCommand); } - public function testRunContainerWithCopyToContainer(): void + public function testRunWhenNetworkIsSetThenNetworkIsCreatedAndJoined(): void { - /** @Given a container with files to copy */ + /** @Given a container with a network */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'copy-test') - ->copyToContainer(pathOnHost: '/host/config', pathOnContainer: '/app/config'); + ->withName(name: 'net-cmd') + ->withNetwork(name: 'my-network'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'copy-test')); - /** @When the container is started (docker cp is automatically called) */ + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'net-cmd')); + + /** @When the container is started */ + $container->run(); + + /** @Then the first command should be the network creation */ + $networkCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString( + 'docker network create --label tiny-blocks.docker-container=true my-network', + $networkCommand + ); + + /** @And the docker run command should contain the network argument */ + $runCommand = $this->client->getExecutedCommandLines()[2]; + self::assertStringContainsString('--network=my-network', $runCommand); + } + + public function testRunWhenAutoRemoveIsDisabledThenContainerIsStarted(): void + { + /** @Given a container with auto-remove disabled */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'persistent') + ->withoutAutoRemove(); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'persistent')); + + /** @When the container is started */ $started = $container->run(); /** @Then the container should be running */ - self::assertSame('copy-test', $started->getName()); + self::assertSame('persistent', $started->getName()); } - public function testRunIfNotExistsWithWaitBeforeRun(): void + public function testRunWhenDockerReturnsAnEmptyIdThenContainerIdEmpty(): void { - /** @Given a condition that is immediately ready */ - $condition = $this->createMock(ContainerReady::class); - $condition->expects(self::once())->method('isReady')->willReturn(true); - - /** @And a container with a wait-before-run that does not exist */ + /** @Given a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'wait-new') - ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $condition)); - - /** @And the Docker list returns empty */ - $this->client->withDockerListResponse(output: ''); + ->withName(name: 'empty-id'); - /** @And the Docker daemon returns valid run and inspect responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-new')); + /** @And the Docker daemon returns an empty container ID */ + $this->client->withDockerCreateResponse(output: ' '); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @Then an InvalidArgumentException should be thrown */ + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Container ID cannot be empty.'); - /** @Then the wait-before-run should have been evaluated and the container created */ - self::assertSame('wait-new', $started->getName()); + /** @When the container is started */ + $container->run(); } - public function testRunContainerWithWaitAfterStarted(): void + public function testRunWhenStartFailsThenDockerCommandExecutionFailed(): void { /** @Given a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'wait-after') - ->withWaitAfterStarted( - wait: ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 1)) - ); + ->withName(name: 'start-fails'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-after')); - /** @When the container is started with a wait-after condition */ - $start = microtime(true); - $started = $container->run(); - $elapsed = (microtime(true) - $start); + /** @And the Docker daemon fails to start it */ + $this->client->withDockerStartResponse(output: 'port is already allocated', isSuccessful: false); - /** @Then the container should have waited after starting */ - self::assertSame('wait-after', $started->getName()); - self::assertGreaterThanOrEqual(0.9, $elapsed); + /** @Then the failure should name the start command and carry the reason reported by Docker */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches("/<'docker' 'start' '6acae5967be0'>.*Reason: port is already allocated/"); + + /** @When the container is started */ + $container->run(); } - public function testExecuteAfterStartedReturnsFailure(): void + public function testGetValueByWhenKeyIsMissingThenReturnsAnEmptyString(): void { - /** @Given a running container */ + /** @Given a running container with known environment variables */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'exec-fail'); + ->withName(name: 'env-test'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-fail')); - $this->client->withDockerExecuteResponse(output: 'command not found', isSuccessful: false); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'env-test', + environment: ['KNOWN=value'] + ) + ); /** @And the container is started */ $started = $container->run(); - /** @When an invalid command is executed */ - $execution = $started->executeAfterStarted(commands: ['invalid-command']); + /** @When querying for a missing environment variable */ + $missingValue = $started->getEnvironmentVariables()->getValueBy(key: 'MISSING'); - /** @Then the result should indicate failure */ - self::assertFalse($execution->isSuccessful()); - self::assertSame('command not found', $execution->getOutput()); + /** @Then it should return an empty string */ + self::assertSame('', $missingValue); } - public function testRunCommandLineIncludesPortMapping(): void + public function testRunWhenInsideDockerThenHostIsConnectedToTheNetwork(): void { - /** @Given a container with a port mapping */ - $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) - ->withName(name: 'port-cmd') - ->withPortMapping(portOnHost: 8080, portOnContainer: 80); + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container configured with a network, running inside a Docker environment */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'inside-docker') + ->withNetwork(name: 'my-network'); /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'port-cmd')); + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the hostname */ + $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'inside-docker')); /** @When the container is started */ $container->run(); - /** @Then the executed docker run command should contain the port mapping argument */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('--publish 8080:80', $runCommand); + /** @Then a docker network connect command should connect the host to the network */ + $connectCommand = $client->getExecutedCommandLines()[1]; + self::assertStringStartsWith('docker network connect my-network', $connectCommand); } - public function testRunCommandLineIncludesTmpfsMounts(): void + public function testRunWhenTwoWaitsBeforeRunAreAddedThenBothAreApplied(): void { - /** @Given a container with two tmpfs mounts */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'tmpfs-cmd') - ->withTmpfsMount(pathOnContainer: '/app/cache') - ->withTmpfsMount(pathOnContainer: '/app/sessions'); + /** @Given a first condition that is immediately ready */ + $first = $this->createMock(ContainerReady::class); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'tmpfs-cmd')); + /** @And the condition holds on its only check */ + $first->expects(self::once())->method('isReady')->willReturn(true); - /** @When the container is started */ - $container->run(); + /** @And a second condition that is immediately ready */ + $second = $this->createMock(ContainerReady::class); - /** @Then the docker create command should mount both directories in memory */ - self::assertStringContainsString( - '--tmpfs /app/cache --tmpfs /app/sessions', - $this->client->getExecutedCommandLines()[0] - ); - } + /** @And the condition holds on its only check */ + $second->expects(self::once())->method('isReady')->willReturn(true); - public function testRunContainerWithAutoGeneratedName(): void - { - /** @Given a container without a name */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client); + /** @And a container that waits for both conditions before it runs */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'two-waits-before') + ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $first)) + ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $second)); - /** @And the Docker daemon returns valid responses (with any hostname from KSUID) */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'auto-generated' - ) + inspectResult: InspectResponseFixture::build(hostname: 'two-waits-before') ); /** @When the container is started */ $started = $container->run(); - /** @Then the container should have an auto-generated name (non-empty) */ - self::assertNotEmpty($started->getName()); + /** @Then the container should be running after both conditions held */ + self::assertSame('two-waits-before', $started->getName()); } - public function testRunContainerWithFullConfiguration(): void + public function testRunWhenVolumesAreMappedThenCreateCommandMountsThem(): void { - /** @Given a fully configured container */ - $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) - ->withName(name: 'web-server') - ->withNetwork(name: 'my-network') - ->withPortMapping(portOnHost: 8080, portOnContainer: 80) - ->withVolumeMapping(pathOnHost: '/var/www', pathOnContainer: '/usr/share/nginx/html') - ->withEnvironmentVariable(key: 'NGINX_HOST', value: 'localhost') - ->withEnvironmentVariable(key: 'NGINX_PORT', value: '80'); + /** @Given a container with two volume mappings */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'vol-cmd') + ->withVolumeMapping(pathOnHost: '/host/data', pathOnContainer: '/app/data') + ->withVolumeMapping(pathOnHost: '/host/logs', pathOnContainer: '/app/logs'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'web-server', - environment: ['NGINX_HOST=localhost', 'NGINX_PORT=80'], - networkName: 'my-network', - exposedPorts: ['80/tcp' => (object)[]] - ) - ); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'vol-cmd')); /** @When the container is started */ - $started = $container->run(); + $container->run(); - /** @Then the container should expose the configured environment variables */ - self::assertSame( - 'localhost', - $started->getEnvironmentVariables()->getValueBy( - key: 'NGINX_HOST' - ) - ); - self::assertSame('80', $started->getEnvironmentVariables()->getValueBy(key: 'NGINX_PORT')); + /** @Then the docker run command should contain the first volume mapping argument */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString('--volume /host/data:/app/data', $runCommand); - /** @And the address should reflect the exposed port */ - self::assertSame(80, $started->getAddress()->getPorts()->firstExposedPort()); - self::assertSame([80], $started->getAddress()->getPorts()->exposedPorts()); + /** @And the docker run command should contain the second volume mapping argument */ + self::assertStringContainsString('--volume /host/logs:/app/logs', $runCommand); } - public function testRunIfNotExistsCreatesNewContainer(): void + public function testRunWhenWaitAfterStartedFailsThenItsFailureIsThrown(): void { - /** @Given a container that does not exist */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'new-container') - ->withEnvironmentVariable(key: 'APP_ENV', value: 'test'); + /** @Given a wait strategy that fails once the container has started */ + $wait = $this->createStub(ContainerWaitAfterStarted::class); - /** @And the Docker list returns empty (container does not exist) */ - $this->client->withDockerListResponse(output: ''); - - /** @And the Docker daemon returns valid run and inspect responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'new-container', - environment: ['APP_ENV=test'] - ) + /** @And the wait strategy times out */ + $wait->method('waitAfter')->willThrowException( + ContainerWaitTimeout::forReadiness(timeout: Duration::fromSeconds(seconds: 1)) ); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); - - /** @Then a new container should be created */ - self::assertSame('new-container', $started->getName()); - self::assertSame('test', $started->getEnvironmentVariables()->getValueBy(key: 'APP_ENV')); - } + /** @And a container that applies that wait strategy after it starts */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'orphan-failure') + ->withWaitAfterStarted(wait: $wait); - public function testExceptionWhenWaitBeforeRunTimesOut(): void - { - /** @Given a condition that never becomes ready */ - $condition = $this->createStub(ContainerReady::class); - $condition->method('isReady')->willReturn(false); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And a container with a wait-before-run that has a short timeout */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'timeout-wait') - ->withWaitBeforeRun( - wait: ContainerWaitForDependency::untilReady(condition: $condition) - ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) - ); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'orphan-failure') + ); - /** @Then a ContainerWaitTimeout exception should be thrown */ + /** @Then the failure of the wait strategy should be thrown */ $this->expectException(ContainerWaitTimeout::class); + $this->expectExceptionMessage('Container readiness check timed out after <1> seconds.'); /** @When the container is started */ $container->run(); } - public function testRunCommandLineIncludesVolumeMapping(): void + public function testStopContainerWhenTimeoutIsZeroThenStopIsSuccessful(): void { - /** @Given a container with two volume mappings */ + /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'vol-cmd') - ->withVolumeMapping(pathOnHost: '/host/data', pathOnContainer: '/app/data') - ->withVolumeMapping(pathOnHost: '/host/logs', pathOnContainer: '/app/logs'); + ->withName(name: 'stop-zero'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'vol-cmd')); - - /** @When the container is started */ - $container->run(); - /** @Then the docker run command should contain the first volume mapping argument */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('--volume /host/data:/app/data', $runCommand); - - /** @And the docker run command should contain the second volume mapping argument */ - self::assertStringContainsString('--volume /host/logs:/app/logs', $runCommand); - } - - public function testRunContainerWithMultiplePortMappings(): void - { - /** @Given a container with multiple port mappings */ - $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) - ->withName(name: 'multi-port') - ->withPortMapping(portOnHost: 8080, portOnContainer: 80) - ->withPortMapping(portOnHost: 8443, portOnContainer: 443); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-zero')); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'multi-port', - exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]] - ) - ); + /** @And the Docker daemon stops the container */ + $this->client->withDockerStopResponse(output: ''); - /** @When the container is started */ + /** @And the container is started */ $started = $container->run(); - /** @Then both ports should be exposed */ - self::assertSame([80, 443], $started->getAddress()->getPorts()->exposedPorts()); - self::assertSame(80, $started->getAddress()->getPorts()->firstExposedPort()); + /** @When the container is stopped with a zero graceful timeout */ + $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 0)); + + /** @Then the stop should be successful */ + self::assertTrue($stopped->isSuccessful()); } - public function testAddressDefaultsWhenNetworkInfoIsEmpty(): void + public function testRunWhenAutoRemoveIsDisabledThenCreateCommandOmitsRm(): void { - /** @Given a container with empty network info */ + /** @Given a container with auto-remove disabled */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'no-net'); + ->withName(name: 'no-rm-cmd') + ->withoutAutoRemove(); - /** @And the Docker daemon returns a response with empty address data */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: '', - ipAddress: '' - ) - ); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'no-rm-cmd')); /** @When the container is started */ - $started = $container->run(); + $container->run(); - /** @Then the address should fall back to defaults */ - self::assertSame('127.0.0.1', $started->getAddress()->getIp()); - self::assertSame('localhost', $started->getAddress()->getHostname()); + /** @Then the docker run command should NOT contain --rm */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringNotContainsString('--rm', $runCommand); } - public function testContainerWithMultipleHostPortMappings(): void + public function testRunWhenInspectionIsEmptyThenDockerContainerNotFound(): void { - /** @Given a container with multiple host port mappings */ - $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) - ->withName(name: 'multi-host-port') - ->withPortMapping(portOnHost: 8080, portOnContainer: 80) - ->withPortMapping(portOnHost: 8443, portOnContainer: 443); + /** @Given a container whose inspect returns empty data */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'ghost'); - /** @And the Docker daemon returns a response with multiple host port bindings */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'multi-host-port', - exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]], - hostPortBindings: [ - '80/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8080']], - '443/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8443']] - ] - ) - ); - /** @When the container is started */ - $started = $container->run(); + /** @And the Docker daemon returns a valid ID but empty inspect */ + $this->client->withDockerInspectResponse(inspectResult: []); - /** @Then both exposed and host ports should be available */ - self::assertSame([80, 443], $started->getAddress()->getPorts()->exposedPorts()); - self::assertSame([8080, 8443], $started->getAddress()->getPorts()->hostPorts()); - self::assertSame(8080, $started->getAddress()->getPorts()->firstHostPort()); + /** @Then a DockerContainerNotFound exception should be thrown */ + $this->expectException(DockerContainerNotFound::class); + $this->expectExceptionMessage('Docker container with name was not found.'); + + /** @When the container is started */ + $container->run(); } - public function testRemoveExecutesDockerRmAndNetworkPrune(): void + public function testRunWhenCommandsAreGivenThenCreateCommandEndsWithThem(): void { - /** @Given a running container */ + /** @Given a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'force-remove'); + ->withName(name: 'args-cmd'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'force-remove') - ); - /** @And the container is started */ - $started = $container->run(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'args-cmd')); - /** @When remove is called */ - $started->remove(); + /** @When the container is started with commands */ + $container->run(commands: ['-connectRetries=15', 'clean', 'migrate']); - /** @Then a docker rm command should have been executed with the container ID */ - $commandLines = $this->client->getExecutedCommandLines(); - $removeCommand = $commandLines[3]; + /** @Then the docker run command should end with the commands */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString('-connectRetries=15 clean migrate', $runCommand); + } - self::assertStringContainsString('docker rm --force --volumes', $removeCommand); - self::assertStringContainsString( - InspectResponseFixture::shortContainerId(), - $removeCommand - ); + public function testRunWhenCreationFailsThenDockerCommandExecutionFailed(): void + { + /** @Given a container that will fail to start */ + $container = GenericDockerContainer::from(image: 'invalid:image', client: $this->client) + ->withName(name: 'fail-test'); - /** @And a docker network prune command should have been executed with the managed label */ - $pruneCommand = $commandLines[4]; + /** @And the Docker daemon returns a failure */ + $this->client->withDockerCreateResponse(output: 'Cannot connect to the Docker daemon.', isSuccessful: false); - self::assertStringContainsString( - 'docker network prune --force --filter label=tiny-blocks.docker-container=true', - $pruneCommand - ); + /** @Then a DockerCommandExecutionFailed exception should be thrown */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches('/Cannot connect to the Docker daemon/'); + + /** @When the container is started */ + $container->run(); } - public function testContainerWithNoExposedPortsReturnsNull(): void + public function testRunWhenExposedPortHasNoHostBindingThenHostPortIsNull(): void { - /** @Given a container with no exposed ports */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'no-ports'); + /** @Given a container with an exposed port but no host binding */ + $container = GenericDockerContainer::from(image: 'redis:latest', client: $this->client) + ->withName(name: 'no-host-bind'); - /** @And the Docker daemon returns valid responses without exposed ports */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'no-ports')); + + /** @And the Docker daemon returns a response with exposed port but null host bindings */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'no-host-bind', + exposedPorts: ['6379/tcp' => (object)[]], + hostPortBindings: ['6379/tcp' => null] + ) + ); /** @When the container is started */ $started = $container->run(); - /** @Then firstExposedPort should return null */ - self::assertNull($started->getAddress()->getPorts()->firstExposedPort()); - self::assertEmpty($started->getAddress()->getPorts()->exposedPorts()); + /** @Then the exposed port should be available */ + self::assertSame(6379, $started->getAddress()->getPorts()->firstExposedPort()); - /** @And firstHostPort should return null */ + /** @And the host port should be null since there is no binding */ self::assertNull($started->getAddress()->getPorts()->firstHostPort()); self::assertEmpty($started->getAddress()->getPorts()->hostPorts()); } - public function testCopyToContainerExecutesDockerCpCommand(): void + public function testRunWhenFileCopyFailsThenDockerCommandExecutionFailed(): void { - /** @Given a container with a copy instruction */ + /** @Given a container with a file to copy */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'cp-cmd') - ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql'); + ->withName(name: 'copy-fails') + ->copyToContainer(pathOnHost: '/host/missing', pathOnContainer: '/app/config'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'cp-cmd')); + + /** @And the Docker daemon fails to copy the file */ + $this->client->withDockerCopyResponse(output: 'lstat /host/missing: no such file', isSuccessful: false); + + /** @Then the failure should name the copy command and carry the reason reported by Docker */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches("/<'docker' 'cp' .*Reason: lstat \/host\/missing: no such file/"); /** @When the container is started */ $container->run(); - - /** @Then the second executed command should be a docker cp with the correct arguments */ - $copyCommand = $this->client->getExecutedCommandLines()[1]; - self::assertStringStartsWith('docker cp', $copyCommand); - self::assertStringContainsString('/host/sql', $copyCommand); - self::assertStringContainsString('/app/sql', $copyCommand); } - public function testRunContainerWithMultipleVolumeMappings(): void + public function testRunWhenSeveralVolumesAreMappedThenContainerIsStarted(): void { /** @Given a container with multiple volume mappings */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) @@ -747,8 +732,10 @@ public function testRunContainerWithMultipleVolumeMappings(): void ->withVolumeMapping(pathOnHost: '/data', pathOnContainer: '/app/data') ->withVolumeMapping(pathOnHost: '/config', pathOnContainer: '/app/config'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'multi-vol')); /** @When the container is started */ @@ -758,666 +745,583 @@ public function testRunContainerWithMultipleVolumeMappings(): void self::assertSame('multi-vol', $started->getName()); } - public function testRunIfNotExistsReturnsExistingContainer(): void + public function testRunWhenWaitBeforeRunTimesOutThenContainerWaitTimeout(): void { - /** @Given a container that already exists */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'existing'); + /** @Given a condition that never becomes ready */ + $condition = $this->createStub(ContainerReady::class); - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); + /** @And the condition never holds */ + $condition->method('isReady')->willReturn(false); - /** @And the Docker inspect returns the container details */ - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'existing', - environment: ['EXISTING=true'] - ) - ); + /** @And a container with a wait-before-run that has a short timeout */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'timeout-wait') + ->withWaitBeforeRun( + wait: ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) + ); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @Then a ContainerWaitTimeout exception should be thrown */ + $this->expectException(ContainerWaitTimeout::class); - /** @Then the existing container should be returned */ - self::assertSame('existing', $started->getName()); - self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); - self::assertSame('true', $started->getEnvironmentVariables()->getValueBy(key: 'EXISTING')); + /** @When the container is started */ + $container->run(); } - public function testContainerWithExposedPortButNoHostBinding(): void + public function testStopOnShutdownWhenProcessExitsThenContainerIsRemoved(): void { - /** @Given a container with an exposed port but no host binding */ - $container = GenericDockerContainer::from(image: 'redis:latest', client: $this->client) - ->withName(name: 'no-host-bind'); + /** @Given shutdown callbacks are captured instead of being registered */ + HostMock::captureShutdown(); - /** @And the Docker daemon returns a response with exposed port but null host bindings */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'no-host-bind', - exposedPorts: ['6379/tcp' => (object)[]], - hostPortBindings: ['6379/tcp' => null] - ) - ); + /** @And a Docker client */ + $client = new ClientMock(); - /** @When the container is started */ - $started = $container->run(); + /** @And a container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'shutdown-run'); - /** @Then the exposed port should be available */ - self::assertSame(6379, $started->getAddress()->getPorts()->firstExposedPort()); + /** @And the Docker daemon returns valid responses */ + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the host port should be null since there is no binding */ - self::assertNull($started->getAddress()->getPorts()->firstHostPort()); - self::assertEmpty($started->getAddress()->getPorts()->hostPorts()); + /** @And the inspect response carries the container details */ + $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shutdown-run')); + + /** @And the container is started and registered for removal on shutdown */ + $container->run()->stopOnShutdown(); + + /** @When the registered shutdown callback runs */ + HostMock::runShutdown(); + + /** @Then the container should have been removed */ + self::assertContains( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + $client->getExecutedCommandLines() + ); } - public function testExecuteAfterStartedRunsDockerExecCommand(): void + public function testStopWhenContainerIsRunningThenDockerStopTargetsItsId(): void { /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'exec-cmd'); + ->withName(name: 'stop-cmd'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-cmd')); - $this->client->withDockerExecuteResponse(output: ''); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-cmd')); + + /** @And the Docker daemon stops the container */ + $this->client->withDockerStopResponse(output: ''); /** @And the container is started */ $started = $container->run(); - /** @When executing commands inside the container */ - $started->executeAfterStarted(commands: ['ls', '-la', '/tmp']); + /** @When the container is stopped */ + $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); - /** @Then a docker exec command should have been executed with the container name and commands */ - $execCommand = $this->client->getExecutedCommandLines()[3]; - self::assertSame('docker exec exec-cmd ls -la /tmp', $execCommand); + /** @Then a docker stop command should have been executed with the container ID */ + $stopCommand = $this->client->getExecutedCommandLines()[3]; + self::assertStringStartsWith('docker stop', $stopCommand); + self::assertStringContainsString(InspectResponseFixture::shortContainerId(), $stopCommand); } - public function testRunContainerWithMultipleCopyInstructions(): void + public function testRunIfNotExistsWhenContainerExistsThenStartedWasReused(): void { - /** @Given a container with multiple copy instructions */ + /** @Given a container that already exists */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'multi-copy') - ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql') - ->copyToContainer(pathOnHost: '/host/config', pathOnContainer: '/app/config'); + ->withName(name: 'reused-flag'); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'multi-copy')); + /** @And the Docker inspect returns the container details */ + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reused-flag')); - /** @When the container is started */ - $started = $container->run(); + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); - /** @Then the container should be running (both docker cp calls were made) */ - self::assertSame('multi-copy', $started->getName()); + /** @Then the started container should report that it was reused */ + self::assertTrue($started->wasReused()); } - public function testExceptionWhenContainerInspectReturnsEmpty(): void + public function testRunWhenTmpfsMountsAreAddedThenCreateCommandMountsThem(): void { - /** @Given a container whose inspect returns empty data */ + /** @Given a container with two tmpfs mounts */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'ghost'); + ->withName(name: 'tmpfs-cmd') + ->withTmpfsMount(pathOnContainer: '/app/cache') + ->withTmpfsMount(pathOnContainer: '/app/sessions'); - /** @And the Docker daemon returns a valid ID but empty inspect */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: []); - /** @Then a DockerContainerNotFound exception should be thrown */ - $this->expectException(DockerContainerNotFound::class); - $this->expectExceptionMessage('Docker container with name was not found.'); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'tmpfs-cmd')); /** @When the container is started */ $container->run(); + + /** @Then the docker create command should mount both directories in memory */ + self::assertStringContainsString( + '--tmpfs /app/cache --tmpfs /app/sessions', + $this->client->getExecutedCommandLines()[0] + ); } - public function testRunCommandLineIncludesAutoRemoveByDefault(): void + public function testRunIfNotExistsWhenOutsideDockerThenSkipsReaperCreation(): void { - /** @Given a container with default configuration */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'rm-cmd'); - - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'rm-cmd')); - - /** @When the container is started */ - $container->run(); + /** @Given the code runs on the host, outside Docker */ + HostMock::outsideDocker(); - /** @Then the docker run command should contain --rm */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('--rm', $runCommand); - } + /** @And a Docker client */ + $client = new ClientMock(); - public function testRunCommandLineIncludesEnvironmentVariable(): void - { - /** @Given a container with an environment variable */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'env-cmd') - ->withEnvironmentVariable(key: 'APP_ENV', value: 'production'); + /** @And a container that already exists, running outside a Docker environment */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'reaper-outside'); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'env-cmd')); + /** @And the Docker inspect returns the container details */ + $client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-outside')); - /** @When the container is started */ - $container->run(); + /** @When runIfNotExists is called */ + $container->runIfNotExists(); - /** @Then the docker run command should contain the environment variable argument */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('--env APP_ENV=production', $runCommand); + /** @Then no reaper container should have been started */ + self::assertStringNotContainsString( + 'tiny-blocks-reaper', + implode(PHP_EOL, $client->getExecutedCommandLines()) + ); } - public function testContainerWithZeroHostPortDropsItFromResult(): void + public function testRunWhenAFileIsRegisteredThenDockerCopyCarriesBothPaths(): void { - /** @Given a container whose inspect payload reports a binding with HostPort equal to zero */ + /** @Given a container with a copy instruction */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'zero-host-port'); + ->withName(name: 'cp-cmd') + ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql'); - /** @And the Docker daemon returns an inspect response with HostPort zero alongside a valid binding */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'zero-host-port', - exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]], - hostPortBindings: [ - '80/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '0']], - '443/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8443']] - ] - ) - ); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'cp-cmd')); /** @When the container is started */ - $started = $container->run(); + $container->run(); - /** @Then only strictly positive host ports should be retained */ - self::assertSame([8443], $started->getAddress()->getPorts()->hostPorts()); + /** @Then the second executed command should be a docker cp with the correct arguments */ + $copyCommand = $this->client->getExecutedCommandLines()[1]; + self::assertStringStartsWith('docker cp', $copyCommand); + self::assertStringContainsString('/host/sql', $copyCommand); + self::assertStringContainsString('/app/sql', $copyCommand); } - public function testExceptionWhenDockerReturnsEmptyContainerId(): void + public function testRunWhenDockerReturnsATooShortIdThenContainerIdTooShort(): void { /** @Given a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'empty-id'); + ->withName(name: 'short-id'); - /** @And the Docker daemon returns an empty container ID */ - $this->client->withDockerCreateResponse(output: ' '); + /** @And the Docker daemon returns a too-short container ID */ + $this->client->withDockerCreateResponse(output: 'abc123'); /** @Then an InvalidArgumentException should be thrown */ $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Container ID cannot be empty.'); + $this->expectExceptionMessage('Container ID is too short. Minimum length is <12> characters.'); /** @When the container is started */ $container->run(); } - public function testRunCommandLineIncludesMultiplePortMappings(): void + public function testRunWhenOutsideDockerThenHostIsNotConnectedToTheNetwork(): void { - /** @Given a container with multiple port mappings */ - $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) - ->withName(name: 'multi-port-cmd') - ->withPortMapping(portOnHost: 8080, portOnContainer: 80) - ->withPortMapping(portOnHost: 8443, portOnContainer: 443); - - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'multi-port-cmd' - ) - ); + /** @Given the code runs on the host, outside Docker */ + HostMock::outsideDocker(); - /** @When the container is started */ - $container->run(); + /** @And a Docker client */ + $client = new ClientMock(); - /** @Then the docker run command should contain both port mapping arguments */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringContainsString('--publish 8080:80', $runCommand); - self::assertStringContainsString('--publish 8443:443', $runCommand); - } + /** @And a container configured with a network, running outside a Docker environment */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'outside-docker') + ->withNetwork(name: 'my-network'); - public function testContainerWithBindingMissingHostPortIsSkipped(): void - { - /** @Given a container whose inspect payload includes a binding with no HostPort key */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'no-host-port-key'); + /** @And the Docker daemon creates the container */ + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker daemon returns an inspect response with a partial binding */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'no-host-port-key', - exposedPorts: ['80/tcp' => (object)[]], - hostPortBindings: [ - '80/tcp' => [['HostIp' => '0.0.0.0']] - ] - ) + /** @And the inspect response carries the container details */ + $client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'outside-docker') ); /** @When the container is started */ $started = $container->run(); - /** @Then bindings lacking HostPort should be skipped without errors */ - self::assertEmpty($started->getAddress()->getPorts()->hostPorts()); + /** @Then the container should be running */ + self::assertSame('outside-docker', $started->getName()); + + /** @And no network connect command should have been executed for the host */ + $commandLines = $client->getExecutedCommandLines(); + + foreach ($commandLines as $commandLine) { + self::assertStringNotContainsString( + 'docker network connect', + $commandLine + ); + } } - public function testRunCommandLineExcludesAutoRemoveWhenDisabled(): void + public function testRunWhenSeveralFilesAreRegisteredThenContainerIsStarted(): void { - /** @Given a container with auto-remove disabled */ + /** @Given a container with multiple copy instructions */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'no-rm-cmd') - ->withoutAutoRemove(); + ->withName(name: 'multi-copy') + ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql') + ->copyToContainer(pathOnHost: '/host/config', pathOnContainer: '/app/config'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'no-rm-cmd')); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'multi-copy')); /** @When the container is started */ - $container->run(); + $started = $container->run(); - /** @Then the docker run command should NOT contain --rm */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - self::assertStringNotContainsString('--rm', $runCommand); + /** @Then the container should be running (both docker cp calls were made) */ + self::assertSame('multi-copy', $started->getName()); } - public function testRunContainerWithMultipleEnvironmentVariables(): void + public function testRunWhenFullyConfiguredThenEnvironmentAndPortsAreExposed(): void { - /** @Given a container with multiple environment variables */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'multi-env') - ->withEnvironmentVariable(key: 'DB_HOST', value: 'localhost') - ->withEnvironmentVariable(key: 'DB_PORT', value: '5432') - ->withEnvironmentVariable(key: 'DB_NAME', value: 'mydb'); + /** @Given a fully configured container */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'web-server') + ->withNetwork(name: 'my-network') + ->withPortMapping(portOnHost: 8080, portOnContainer: 80) + ->withVolumeMapping(pathOnHost: '/var/www', pathOnContainer: '/usr/share/nginx/html') + ->withEnvironmentVariable(key: 'NGINX_HOST', value: 'localhost') + ->withEnvironmentVariable(key: 'NGINX_PORT', value: '80'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'multi-env', - environment: ['DB_HOST=localhost', 'DB_PORT=5432', 'DB_NAME=mydb'] + hostname: 'web-server', + environment: ['NGINX_HOST=localhost', 'NGINX_PORT=80'], + networkName: 'my-network', + exposedPorts: ['80/tcp' => (object)[]] ) ); /** @When the container is started */ $started = $container->run(); - /** @Then all environment variables should be accessible */ + /** @Then the container should expose the configured environment variables */ self::assertSame( 'localhost', - $started->getEnvironmentVariables()->getValueBy(key: 'DB_HOST') + $started->getEnvironmentVariables()->getValueBy( + key: 'NGINX_HOST' + ) ); - self::assertSame('5432', $started->getEnvironmentVariables()->getValueBy(key: 'DB_PORT')); - self::assertSame('mydb', $started->getEnvironmentVariables()->getValueBy(key: 'DB_NAME')); + self::assertSame('80', $started->getEnvironmentVariables()->getValueBy(key: 'NGINX_PORT')); + + /** @And the address should reflect the exposed port */ + self::assertSame(80, $started->getAddress()->getPorts()->firstExposedPort()); + self::assertSame([80], $started->getAddress()->getPorts()->exposedPorts()); } - public function testExceptionWhenDockerReturnsTooShortContainerId(): void + public function testWithPullTimeoutThenLeavesTheOriginalDefinitionUntouched(): void { - /** @Given a container */ + /** @Given a container with the default pull timeout */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'short-id'); + ->withName(name: 'untouched-pull'); - /** @And the Docker daemon returns a too-short container ID */ - $this->client->withDockerCreateResponse(output: 'abc123'); + /** @And a copy of it with a pull timeout of ten minutes, which is discarded */ + $container->withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)); - /** @Then an InvalidArgumentException should be thrown */ - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Container ID is too short. Minimum length is <12> characters.'); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @When the container is started */ + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'untouched-pull') + ); + + /** @When the original container is started */ $container->run(); + + /** @Then the creation of the container should still be bounded by the default pull timeout */ + self::assertSame([300], $this->client->getRequestedTimeouts()); } - public function testRunContainerThenInspectCommandTargetsContainerId(): void + public function testExecuteAfterStartedWhenCommandFailsThenReturnsTheFailure(): void { - /** @Given a container configured with an image and a name */ + /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'inspect-cmd'); + ->withName(name: 'exec-fail'); - /** @And the Docker daemon returns a valid container ID and inspect response */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'inspect-cmd')); - /** @When the container is started */ - $container->run(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-fail')); - /** @Then a docker inspect command should have been executed for the container ID */ - $inspectCommand = $this->client->getExecutedCommandLines()[2]; - self::assertSame(sprintf('docker inspect %s', InspectResponseFixture::shortContainerId()), $inspectCommand); + /** @And the command executed inside the container fails */ + $this->client->withDockerExecuteResponse(output: 'command not found', isSuccessful: false); + + /** @And the container is started */ + $started = $container->run(); + + /** @When an invalid command is executed */ + $execution = $started->executeAfterStarted(commands: ['invalid-command']); + + /** @Then the result should indicate failure */ + self::assertFalse($execution->isSuccessful()); + self::assertSame('command not found', $execution->getOutput()); } - public function testRunWhenStartFailsThenDockerCommandExecutionFailed(): void + public function testRunIfNotExistsWhenContainerIsMissingThenANewOneIsStarted(): void { - /** @Given a container */ + /** @Given a container that does not exist */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'start-fails'); + ->withName(name: 'new-container') + ->withEnvironmentVariable(key: 'APP_ENV', value: 'test'); /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker daemon fails to start it */ - $this->client->withDockerStartResponse(output: 'port is already allocated', isSuccessful: false); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'new-container', + environment: ['APP_ENV=test'] + ) + ); - /** @Then the failure should name the start command and carry the reason reported by Docker */ - $this->expectException(DockerCommandExecutionFailed::class); - $this->expectExceptionMessageMatches("/<'docker' 'start' '6acae5967be0'>.*Reason: port is already allocated/"); + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); - /** @When the container is started */ - $container->run(); + /** @Then a new container should be created */ + self::assertSame('new-container', $started->getName()); + self::assertSame('test', $started->getEnvironmentVariables()->getValueBy(key: 'APP_ENV')); } - public function testEnvironmentVariableReturnsEmptyStringForMissingKey(): void + public function testRunWhenAutoRemoveIsNotDisabledThenCreateCommandCarriesRm(): void { - /** @Given a running container with known environment variables */ + /** @Given a container with default configuration */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'env-test'); + ->withName(name: 'rm-cmd'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'env-test', - environment: ['KNOWN=value'] - ) - ); - /** @And the container is started */ - $started = $container->run(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'rm-cmd')); - /** @When querying for a missing environment variable */ - $missingValue = $started->getEnvironmentVariables()->getValueBy(key: 'MISSING'); + /** @When the container is started */ + $container->run(); - /** @Then it should return an empty string */ - self::assertSame('', $missingValue); + /** @Then the docker run command should contain --rm */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString('--rm', $runCommand); } - public function testRunWhenTwoWaitsBeforeRunAreAddedThenBothAreApplied(): void + public function testRunWhenSeveralHostPortsAreBoundThenAllHostPortsAreListed(): void { - /** @Given a first condition that is immediately ready */ - $first = $this->createMock(ContainerReady::class); - $first->expects(self::once())->method('isReady')->willReturn(true); - - /** @And a second condition that is immediately ready */ - $second = $this->createMock(ContainerReady::class); - $second->expects(self::once())->method('isReady')->willReturn(true); - - /** @And a container that waits for both conditions before it runs */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'two-waits-before') - ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $first)) - ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $second)); + /** @Given a container with multiple host port mappings */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'multi-host-port') + ->withPortMapping(portOnHost: 8080, portOnContainer: 80) + ->withPortMapping(portOnHost: 8443, portOnContainer: 443); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon returns a response with multiple host port bindings */ $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'two-waits-before') + inspectResult: InspectResponseFixture::build( + hostname: 'multi-host-port', + exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]], + hostPortBindings: [ + '80/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8080']], + '443/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '8443']] + ] + ) ); /** @When the container is started */ $started = $container->run(); - /** @Then the container should be running after both conditions held */ - self::assertSame('two-waits-before', $started->getName()); + /** @Then both exposed and host ports should be available */ + self::assertSame([80, 443], $started->getAddress()->getPorts()->exposedPorts()); + self::assertSame([8080, 8443], $started->getAddress()->getPorts()->hostPorts()); + self::assertSame(8080, $started->getAddress()->getPorts()->firstHostPort()); } - public function testStopContainerWhenTimeoutIsZeroThenStopIsSuccessful(): void + public function testRunWhenSeveralPortsAreMappedThenAllExposedPortsAreListed(): void { - /** @Given a running container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-zero'); + /** @Given a container with multiple port mappings */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'multi-port') + ->withPortMapping(portOnHost: 8080, portOnContainer: 80) + ->withPortMapping(portOnHost: 8443, portOnContainer: 443); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-zero')); - $this->client->withDockerStopResponse(output: ''); - /** @And the container is started */ - $started = $container->run(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'multi-port', + exposedPorts: ['80/tcp' => (object)[], '443/tcp' => (object)[]] + ) + ); - /** @When the container is stopped with a zero graceful timeout */ - $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 0)); + /** @When the container is started */ + $started = $container->run(); - /** @Then the stop should be successful */ - self::assertTrue($stopped->isSuccessful()); + /** @Then both ports should be exposed */ + self::assertSame([80, 443], $started->getAddress()->getPorts()->exposedPorts()); + self::assertSame(80, $started->getAddress()->getPorts()->firstExposedPort()); } - #[RunInSeparateProcess] - public function testStopOnShutdownWhenProcessExitsThenContainerIsRemoved(): void + public function testStopOnShutdownWhenCalledThenRegistersOneShutdownCallback(): void { - $template = '%s/Internal/Containers/Overrides/register_shutdown_function_spy.php'; - require_once sprintf($template, __DIR__); + /** @Given shutdown callbacks are captured instead of being registered */ + HostMock::captureShutdown(); - /** @Given a Docker client */ + /** @And a Docker client */ $client = new ClientMock(); /** @And a container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'shutdown-run'); + ->withName(name: 'shutdown-test'); /** @And the Docker daemon returns valid responses */ $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); /** @And the inspect response carries the container details */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shutdown-run')); + $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shutdown-test')); - /** @And the container is started and registered for removal on shutdown */ - $container->run()->stopOnShutdown(); + /** @And the container is started */ + $started = $container->run(); - /** @When the registered shutdown callback runs */ - $GLOBALS['registeredShutdownCallbacks'][0](); + /** @When stopOnShutdown is called */ + $started->stopOnShutdown(); - /** @Then the container should have been removed */ - self::assertContains( - sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), - $client->getExecutedCommandLines() - ); + /** @Then exactly one shutdown callback should have been registered */ + self::assertSame(1, HostMock::shutdownCallbackCount()); } - public function testRunIfNotExistsWhenContainerExistsThenStartedWasReused(): void + public function testStopWhenContainerIsSharedThenStopsTheUnderlyingContainer(): void { /** @Given a container that already exists */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'reused-flag'); - - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); + ->withName(name: 'shared-stop'); /** @And the Docker inspect returns the container details */ - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'reused-flag')); + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'shared-stop')); - /** @When runIfNotExists is called */ + /** @And the shared container is obtained */ $started = $container->runIfNotExists(); - /** @Then the started container should report that it was reused */ - self::assertTrue($started->wasReused()); + /** @When the shared container is stopped with a grace period of 30 seconds */ + $started->stop(gracePeriod: Duration::fromSeconds(seconds: 30)); + + /** @Then the underlying container should be stopped with that grace period */ + self::assertContains( + sprintf('docker stop --time 30 %s', InspectResponseFixture::shortContainerId()), + $this->client->getExecutedCommandLines() + ); } - #[RunInSeparateProcess] - public function testGetPortForConnectionWhenInsideDockerReturnsExposedPort(): void + public function testRunWhenContainerStartsThenItsIdentityAndAddressAreExposed(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); + /** @Given a container configured with an image and a name */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'test-alpine'); - /** @Given a Docker client */ - $client = new ClientMock(); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And a container with a host port mapping */ - $container = GenericDockerContainer::from(image: 'mysql:8.4', client: $client) - ->withName(name: 'conn-port') - ->withPortMapping(portOnHost: 33060, portOnContainer: 3306); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'test-alpine', + environment: ['PATH=/usr/local/bin'] + ) + ); - /** @And the Docker daemon returns valid responses */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + /** @When the container is started */ + $started = $container->run(); - /** @And the inspect response carries exposed and host-mapped ports */ - $client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'conn-port', - exposedPorts: ['3306/tcp' => (object)[]], - hostPortBindings: ['3306/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '33060']]] - ) - ); - - /** @And the container is started */ - $started = $container->run(); - - /** @When the connection port is resolved inside Docker */ - $port = $started->getAddress()->getPorts()->getPortForConnection(); - - /** @Then it should be the container-internal exposed port */ - self::assertSame(3306, $port); - } - - #[RunInSeparateProcess] - public function testRunIfNotExistsWhenOutsideDockerThenSkipsReaperCreation(): void - { - $template = '%s/Internal/Containers/Overrides/file_exists_outside_docker.php'; - require_once sprintf($template, __DIR__); - - /** @Given a Docker client */ - $client = new ClientMock(); - - /** @And a container that already exists, running outside a Docker environment */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'reaper-outside'); - - /** @And the Docker list returns an existing container */ - $client->withDockerListResponse(output: InspectResponseFixture::containerId()); - - /** @And the Docker inspect returns the container details */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-outside')); - - /** @When runIfNotExists is called */ - $container->runIfNotExists(); - - /** @Then no reaper container should have been started */ - self::assertStringNotContainsString( - 'tiny-blocks-reaper', - implode(PHP_EOL, $client->getExecutedCommandLines()) - ); + /** @Then the container should be running with the expected properties */ + self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); + self::assertSame('test-alpine', $started->getName()); + self::assertSame('test-alpine', $started->getAddress()->getHostname()); + self::assertSame('172.22.0.2', $started->getAddress()->getIp()); } - #[RunInSeparateProcess] - public function testRunIfNotExistsSkipsReaperCreationWhenReaperAlreadyExists(): void + public function testRunWhenSeveralPortsAreMappedThenCreateCommandPublishesAll(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); - - /** @Given a container that already exists */ - $client = new ClientMock(); - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'reaper-skip'); + /** @Given a container with multiple port mappings */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'multi-port-cmd') + ->withPortMapping(portOnHost: 8080, portOnContainer: 80) + ->withPortMapping(portOnHost: 8443, portOnContainer: 443); - /** @And the Docker list returns an existing container */ - $client->withDockerListResponse(output: InspectResponseFixture::containerId()); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker inspect returns the container details */ - $client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'reaper-skip') + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'multi-port-cmd' + ) ); - /** @And the reaper container already exists */ - $client->withDockerListResponse(output: 'existing-reaper-id'); - - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); - - /** @Then the container should be returned */ - self::assertSame('reaper-skip', $started->getName()); - - /** @And the reused container should have probed for the reaper list to exist */ - $commandLines = $client->getExecutedCommandLines(); - $reaperListed = false; + /** @When the container is started */ + $container->run(); - foreach ($commandLines as $commandLine) { - $reaperListed = $reaperListed || str_contains($commandLine, 'tiny-blocks-reaper-reaper-skip'); - self::assertStringNotContainsString( - 'docker run --rm -d --name tiny-blocks-reaper', - $commandLine - ); - } - self::assertTrue($reaperListed); + /** @Then the docker run command should contain both port mapping arguments */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString('--publish 8080:80', $runCommand); + self::assertStringContainsString('--publish 8443:443', $runCommand); } - public function testRunIfNotExistsThenListCommandFiltersByExactContainerName(): void + public function testExecuteAfterStartedWhenCommandSucceedsThenReturnsItsOutput(): void { - /** @Given a container that already exists */ + /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'list-cmd'); - - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); - - /** @And the Docker inspect returns the container details */ - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'list-cmd')); - - /** @When runIfNotExists is called */ - $container->runIfNotExists(); - - /** @Then the first command should list containers filtered by the exact name */ - $listCommand = $this->client->getExecutedCommandLines()[0]; - self::assertSame('docker ps --all --quiet --filter name=^list-cmd$', $listCommand); - } - - #[RunInSeparateProcess] - public function testStopOnShutdownWhenCalledThenRegistersOneShutdownCallback(): void - { - $template = '%s/Internal/Containers/Overrides/register_shutdown_function_spy.php'; - require_once sprintf($template, __DIR__); - - /** @Given a Docker client */ - $client = new ClientMock(); - - /** @And a container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'shutdown-test'); + ->withName(name: 'exec-test'); - /** @And the Docker daemon returns valid responses */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); /** @And the inspect response carries the container details */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shutdown-test')); + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-test')); + + /** @And the command executed inside the container succeeds */ + $this->client->withDockerExecuteResponse(output: 'command output'); /** @And the container is started */ $started = $container->run(); - /** @When stopOnShutdown is called */ - $started->stopOnShutdown(); - - /** @Then exactly one shutdown callback should have been registered */ - self::assertCount(1, $GLOBALS['registeredShutdownCallbacks']); - } - - public function testStopWhenContainerIsSharedThenStopsTheUnderlyingContainer(): void - { - /** @Given a container that already exists */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'shared-stop'); - - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); - - /** @And the Docker inspect returns the container details */ - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shared-stop')); - - /** @And the shared container is obtained */ - $started = $container->runIfNotExists(); - - /** @When the shared container is stopped with a grace period of 30 seconds */ - $started->stop(gracePeriod: Duration::fromSeconds(seconds: 30)); + /** @When commands are executed inside the running container */ + $execution = $started->executeAfterStarted(commands: ['ls', '-la']); - /** @Then the underlying container should be stopped with that grace period */ - self::assertContains( - sprintf('docker stop --time 30 %s', InspectResponseFixture::shortContainerId()), - $this->client->getExecutedCommandLines() - ); + /** @Then the execution should be successful */ + self::assertTrue($execution->isSuccessful()); + self::assertSame('command output', $execution->getOutput()); } - #[RunInSeparateProcess] - public function testGetPortForConnectionWhenOutsideDockerReturnsHostMappedPort(): void + public function testGetPortForConnectionWhenInsideDockerThenReturnsExposedPort(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_outside_docker.php'; - require_once sprintf($template, __DIR__); + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); - /** @Given a Docker client */ + /** @And a Docker client */ $client = new ClientMock(); /** @And a container with a host port mapping */ @@ -1440,11 +1344,11 @@ public function testGetPortForConnectionWhenOutsideDockerReturnsHostMappedPort() /** @And the container is started */ $started = $container->run(); - /** @When the connection port is resolved outside Docker */ + /** @When the connection port is resolved inside Docker */ $port = $started->getAddress()->getPorts()->getPortForConnection(); - /** @Then it should be the host-mapped port */ - self::assertSame(33060, $port); + /** @Then it should be the container-internal exposed port */ + self::assertSame(3306, $port); } public function testRunContainerWhenExposedPortIsZeroThenItIsDroppedFromResult(): void @@ -1453,8 +1357,10 @@ public function testRunContainerWhenExposedPortIsZeroThenItIsDroppedFromResult() $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) ->withName(name: 'zero-exposed'); - /** @And the Docker daemon returns an inspect response with a zero exposed port alongside a valid one */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon returns an inspect response with a zero exposed port alongside a valid one */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'zero-exposed', @@ -1469,24 +1375,43 @@ public function testRunContainerWhenExposedPortIsZeroThenItIsDroppedFromResult() self::assertSame([3306], $started->getAddress()->getPorts()->exposedPorts()); } - #[RunInSeparateProcess] + public function testRunIfNotExistsWhenContainerExistsThenItsDetailsAreReturned(): void + { + /** @Given a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'existing'); + + /** @And the Docker inspect returns the container details */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'existing', + environment: ['EXISTING=true'] + ) + ); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then the existing container should be returned */ + self::assertSame('existing', $started->getName()); + self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); + self::assertSame('true', $started->getEnvironmentVariables()->getValueBy(key: 'EXISTING')); + } + public function testRunIfNotExistsWhenReaperIsMissingThenStartsReaperContainer(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); - /** @Given a Docker client */ + /** @And a Docker client */ $client = new ClientMock(); /** @And a container that already exists */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) ->withName(name: 'reaper-start'); - /** @And the Docker list returns an existing container */ - $client->withDockerListResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker inspect returns the container details */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-start')); + $client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-start')); /** @And no reaper container is currently listed */ $client->withDockerListResponse(output: ''); @@ -1502,7 +1427,65 @@ public function testRunIfNotExistsWhenReaperIsMissingThenStartsReaperContainer() self::assertStringContainsString('while docker inspect', $commandLines); } - public function testContainerWithMixedValidAndNullHostBindingsRetainsValidPorts(): void + public function testRunIfNotExistsThenLookupCommandTargetsTheExactContainerName(): void + { + /** @Given a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'list-cmd'); + + /** @And the Docker inspect returns the container details */ + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'list-cmd')); + + /** @When runIfNotExists is called */ + $container->runIfNotExists(); + + /** @Then the first command should look the container up by its exact name */ + self::assertSame('docker inspect --type container list-cmd', $this->client->getExecutedCommandLines()[0]); + } + + public function testRunIfNotExistsWhenContainerIsMissingThenStartedWasNotReused(): void + { + /** @Given a container that does not exist */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'fresh-flag'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'fresh-flag')); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then the started container should report that it was not reused */ + self::assertFalse($started->wasReused()); + } + + public function testRunToCompletionWhenContainerRanAndFailedThenItIsNotRunAgain(): void + { + /** @Given a one-shot container that joins a network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withNetwork(name: 'my-network'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the container runs and exits with a non-zero status */ + $this->client->withDockerAttachedStartResponse(output: 'migration failed', isSuccessful: false); + + /** @And the inspection shows the container did run and exit */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(status: 'exited')); + + /** @Then the error the container wrote should be thrown, without a second attempt */ + $this->expectException(ContainerExitUnsuccessful::class); + $this->expectExceptionMessageMatches('/Output: \.$/'); + + /** @When the container runs to completion */ + $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); + } + + public function testRunWhenBindingsMixValidAndNullThenValidHostPortsAreRetained(): void { /** @Given a container whose inspect payload mixes valid and null host bindings */ $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) @@ -1510,8 +1493,10 @@ public function testContainerWithMixedValidAndNullHostBindingsRetainsValidPorts( ->withPortMapping(portOnHost: 8080, portOnContainer: 80) ->withPortMapping(portOnHost: 8443, portOnContainer: 443); - /** @And the Docker daemon returns an inspect response with a trailing null binding */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon returns an inspect response with a trailing null binding */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'mixed-bindings', @@ -1531,368 +1516,1236 @@ public function testContainerWithMixedValidAndNullHostBindingsRetainsValidPorts( self::assertSame([8080, 8443], $started->getAddress()->getPorts()->hostPorts()); } - #[RunInSeparateProcess] - public function testGetHostForConnectionWhenOutsideDockerReturnsLoopbackAddress(): void + public function testRunWhenCreationFailsThenFailureRendersShellEscapedArguments(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_outside_docker.php'; - require_once sprintf($template, __DIR__); + /** @Given a container that will fail to start */ + $container = GenericDockerContainer::from(image: 'invalid:image', client: $this->client) + ->withName(name: 'fail-render-test'); - /** @Given a Docker client */ - $client = new ClientMock(); + /** @And the Docker daemon returns a failure */ + $this->client->withDockerCreateResponse(output: 'boom', isSuccessful: false); - /** @And a container with a known hostname */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'conn-host'); + /** @Then the failure message should render each argument shell-escaped */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches("/'docker' 'create'/"); - /** @And the Docker daemon returns valid responses */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + /** @When the container is started */ + $container->run(); + } - /** @And the inspect response carries the hostname */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'conn-host')); + public function testRunWhenEnvironmentVariableIsAddedThenCreateCommandCarriesIt(): void + { + /** @Given a container with an environment variable */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'env-cmd') + ->withEnvironmentVariable(key: 'APP_ENV', value: 'production'); - /** @And the container is started */ - $started = $container->run(); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @When the connection host is resolved outside Docker */ - $host = $started->getAddress()->getHostForConnection(); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'env-cmd')); - /** @Then it should be the loopback address */ - self::assertSame('127.0.0.1', $host); + /** @When the container is started */ + $container->run(); + + /** @Then the docker run command should contain the environment variable argument */ + $runCommand = $this->client->getExecutedCommandLines()[0]; + self::assertStringContainsString('--env APP_ENV=production', $runCommand); + } + + public function testRunWhenNetworkDetailsAreEmptyThenAddressFallsBackToDefaults(): void + { + /** @Given a container with empty network info */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'no-net'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon returns a response with empty address data */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: '', + ipAddress: '' + ) + ); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the address should fall back to defaults */ + self::assertSame('127.0.0.1', $started->getAddress()->getIp()); + self::assertSame('localhost', $started->getAddress()->getHostname()); + } + + public function testRunWhenPullTimeoutIsGivenThenContainerCreationIsBoundedByIt(): void + { + /** @Given a container whose image may take up to ten minutes to pull */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'slow-pull') + ->withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'slow-pull')); + + /** @When the container is started */ + $container->run(); + + /** @Then the creation of the container should be bounded by the given pull timeout */ + self::assertSame([600], $this->client->getRequestedTimeouts()); + } + + public function testRunWhenSeveralEnvironmentVariablesAreAddedThenAllAreExposed(): void + { + /** @Given a container with multiple environment variables */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'multi-env') + ->withEnvironmentVariable(key: 'DB_HOST', value: 'localhost') + ->withEnvironmentVariable(key: 'DB_PORT', value: '5432') + ->withEnvironmentVariable(key: 'DB_NAME', value: 'mydb'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'multi-env', + environment: ['DB_HOST=localhost', 'DB_PORT=5432', 'DB_NAME=mydb'] + ) + ); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then all environment variables should be accessible */ + self::assertSame( + 'localhost', + $started->getEnvironmentVariables()->getValueBy(key: 'DB_HOST') + ); + self::assertSame('5432', $started->getEnvironmentVariables()->getValueBy(key: 'DB_PORT')); + self::assertSame('mydb', $started->getEnvironmentVariables()->getValueBy(key: 'DB_NAME')); } - #[RunInSeparateProcess] - public function testRunContainerWithNetworkWhenOutsideDockerSkipsHostConnection(): void + public function testRunIfNotExistsWhenReaperAlreadyExistsThenSkipsReaperCreation(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_outside_docker.php'; - require_once sprintf($template, __DIR__); + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); - /** @Given a container configured with a network, running outside a Docker environment */ + /** @And a Docker client */ $client = new ClientMock(); + + /** @And a container that already exists */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'outside-docker') - ->withNetwork(name: 'my-network'); + ->withName(name: 'reaper-skip'); + + /** @And the Docker inspect returns the container details */ + $client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(hostname: 'reaper-skip') + ); + + /** @And the reaper container already exists */ + $client->withDockerListResponse(output: 'existing-reaper-id'); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then the container should be returned */ + self::assertSame('reaper-skip', $started->getName()); + + /** @And the reused container should have probed for the reaper list to exist */ + $commandLines = $client->getExecutedCommandLines(); + $reaperListed = false; + + foreach ($commandLines as $commandLine) { + $reaperListed = $reaperListed || str_contains($commandLine, 'tiny-blocks-reaper-reaper-skip'); + self::assertStringNotContainsString( + 'docker run --rm -d --name tiny-blocks-reaper', + $commandLine + ); + } + self::assertTrue($reaperListed); + } + + public function testRunWhenWaitAfterStartedFailsThenTheStartedContainerIsRemoved(): void + { + /** @Given a wait strategy that fails once the container has started */ + $wait = $this->createStub(ContainerWaitAfterStarted::class); + + /** @And the wait strategy times out */ + $wait->method('waitAfter')->willThrowException( + ContainerWaitTimeout::forReadiness(timeout: Duration::fromSeconds(seconds: 1)) + ); + + /** @And a container that applies that wait strategy after it starts */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'orphan') + ->withWaitAfterStarted(wait: $wait); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'orphan')); + + try { + /** @When the container is started */ + $container->run(); + } catch (ContainerWaitTimeout) { + /** @Then the started container should be removed, since no one holds it */ + self::assertSame( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + array_last($this->client->getExecutedCommandLines()) + ); + } + } + + public function testRunWhenWaitAfterStartedIsRegisteredThenItPausesAfterStarting(): void + { + /** @Given a container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'wait-after') + ->withWaitAfterStarted( + wait: ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 1)) + ); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-after')); + + /** @When the container is started with a wait-after condition */ + $started = $container->run(); + + /** @Then the container should have waited one second after starting */ + self::assertSame('wait-after', $started->getName()); + self::assertSame(1.0, ClockMock::elapsedInSeconds()); + } + + public function testRunWhenStartCommandCannotRunThenTheLeftoverContainerIsRemoved(): void + { + /** @Given a container that joins no network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'start-timeout'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the start command exceeds the timeout of the client */ + $this->client->withDockerStartException( + exception: DockerCommandExecutionFailed::from(reason: 'exceeded the timeout', command: 'docker start') + ); + + try { + /** @When the container is started */ + $container->run(); + } catch (DockerCommandExecutionFailed) { + /** @Then the leftover container should be removed */ + self::assertSame( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + array_last($this->client->getExecutedCommandLines()) + ); + } + } + + public function testGetPortForConnectionWhenOutsideDockerThenReturnsHostMappedPort(): void + { + /** @Given the code runs on the host, outside Docker */ + HostMock::outsideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container with a host port mapping */ + $container = GenericDockerContainer::from(image: 'mysql:8.4', client: $client) + ->withName(name: 'conn-port') + ->withPortMapping(portOnHost: 33060, portOnContainer: 3306); /** @And the Docker daemon returns valid responses */ $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries exposed and host-mapped ports */ $client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'outside-docker') + inspectResult: InspectResponseFixture::build( + hostname: 'conn-port', + exposedPorts: ['3306/tcp' => (object)[]], + hostPortBindings: ['3306/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '33060']]] + ) ); - /** @When the container is started */ + /** @And the container is started */ $started = $container->run(); - /** @Then the container should be running */ - self::assertSame('outside-docker', $started->getName()); + /** @When the connection port is resolved outside Docker */ + $port = $started->getAddress()->getPorts()->getPortForConnection(); - /** @And no network connect command should have been executed for the host */ - $commandLines = $client->getExecutedCommandLines(); + /** @Then it should be the host-mapped port */ + self::assertSame(33060, $port); + } + + public function testRunIfNotExistsWhenContainerIsMissingThenWaitBeforeRunIsApplied(): void + { + /** @Given a condition that is immediately ready */ + $condition = $this->createMock(ContainerReady::class); + + /** @And the condition holds on its only check */ + $condition->expects(self::once())->method('isReady')->willReturn(true); + + /** @And a container with a wait-before-run that does not exist */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'wait-new') + ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $condition)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-new')); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then the wait-before-run should have been evaluated and the container created */ + self::assertSame('wait-new', $started->getName()); + } + + public function testRunWhenFilesAreCopiedThenTheyAreCopiedBeforeTheContainerStarts(): void + { + /** @Given a container with a copy instruction */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'cp-before-start') + ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'cp-before-start') + ); + + /** @When the container is started */ + $container->run(); + + /** @Then the container should be created, receive the files, be started, and only then be inspected */ + self::assertSame( + ['docker create', 'docker cp', 'docker start', 'docker inspect'], + array_map( + static fn(array $arguments): string => implode(' ', array_slice($arguments, 0, 2)), + $this->client->getExecutedArguments() + ) + ); + } + + public function testRunWhenTwoWaitsAfterStartedAreAddedThenBothReceiveTheContainer(): void + { + /** @Given a first wait strategy applied after the container starts */ + $first = $this->createMock(ContainerWaitAfterStarted::class); + + /** @And the wait strategy is applied exactly once */ + $first->expects(self::once())->method('waitAfter'); + + /** @And a second wait strategy applied after the container starts */ + $second = $this->createMock(ContainerWaitAfterStarted::class); + + /** @And the wait strategy is applied exactly once */ + $second->expects(self::once())->method('waitAfter'); + + /** @And a container that applies both wait strategies after it starts */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'two-waits-after') + ->withWaitAfterStarted(wait: $first) + ->withWaitAfterStarted(wait: $second); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'two-waits-after') + ); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the container should be running after both wait strategies were applied */ + self::assertSame('two-waits-after', $started->getName()); + } + + public function testGetHostForConnectionWhenOutsideDockerThenReturnsLoopbackAddress(): void + { + /** @Given the code runs on the host, outside Docker */ + HostMock::outsideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container with a known hostname */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'conn-host'); + + /** @And the Docker daemon returns valid responses */ + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the hostname */ + $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'conn-host')); + + /** @And the container is started */ + $started = $container->run(); + + /** @When the connection host is resolved outside Docker */ + $host = $started->getAddress()->getHostForConnection(); + + /** @Then it should be the loopback address */ + self::assertSame('127.0.0.1', $host); + } + + public function testRunWhenNetworkVanishesBeforeStartThenTheContainerIsStartedAgain(): void + { + /** @Given a container that joins a network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'network-retry') + ->withNetwork(name: 'my-network'); + + /** @And the Docker daemon creates the container on the first attempt */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon fails to start it because the network was pruned meanwhile */ + $this->client->withDockerStartResponse(output: 'network my-network not found', isSuccessful: false); + + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'network-retry') + ); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the container of the second attempt should be the one handed over */ + self::assertSame('f1e2d3c4b5a6', $started->getId()); + } + + public function testRunWhenStartFailsOnBothAttemptsThenDockerCommandExecutionFailed(): void + { + /** @Given a container that joins a network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'network-gone') + ->withNetwork(name: 'my-network'); + + /** @And the Docker daemon creates the container on the first attempt */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon fails to start it */ + $this->client->withDockerStartResponse(output: 'first failure', isSuccessful: false); + + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the Docker daemon fails to start it again */ + $this->client->withDockerStartResponse(output: 'second failure', isSuccessful: false); + + /** @Then the failure of the second attempt should be thrown */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches("/<'docker' 'start' 'f1e2d3c4b5a6'>.*Reason: second failure/"); + + /** @When the container is started */ + $container->run(); + } + + public function testGetHostForConnectionWhenInsideDockerThenReturnsContainerHostname(): void + { + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container with a known hostname */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'conn-host'); + + /** @And the Docker daemon returns valid responses */ + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the hostname */ + $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'conn-host')); + + /** @And the container is started */ + $started = $container->run(); + + /** @When the connection host is resolved inside Docker */ + $host = $started->getAddress()->getHostForConnection(); + + /** @Then it should be the container hostname */ + self::assertSame('conn-host', $host); + } + + public function testRunIfNotExistsWhenExistingContainerIsStoppedThenItIsReusedAsItIs(): void + { + /** @Given a container that exists but has exited */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'stopped'); + + /** @And the lookup finds the container exited */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'exited', hostname: 'stopped') + ); + + /** @When the container is asked for */ + $started = $container->runIfNotExists(); + + /** @Then the container should be handed over at once, without waiting for it to run */ + self::assertTrue($started->wasReused()); + self::assertSame(0.0, ClockMock::elapsedInSeconds()); + } + + public function testRunIfNotExistsWhenInsideDockerThenReaperIsLookedUpByItsExactName(): void + { + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'reaper-list'); + + /** @And the lookup returns the container details */ + $client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-list')); + + /** @When the container is asked for */ + $container->runIfNotExists(); + + /** @Then the reaper should be listed by its exact name */ + self::assertContains( + 'docker ps --all --quiet --filter name=^tiny-blocks-reaper-reaper-list$', + $client->getExecutedCommandLines() + ); + } + + public function testRunContainerWhenContainerIdIsExactlyMinimumLengthThenIdIsAccepted(): void + { + /** @Given a container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'min-id'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: '123456789012'); + + /** @And the Docker daemon returns a container ID exactly at the minimum length */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'min-id')); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the full minimum-length ID should be accepted and preserved */ + self::assertSame('123456789012', $started->getId()); + } + + public function testRunIfNotExistsWhenReaperListIsWhitespaceThenStartsReaperContainer(): void + { + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'reaper-blank'); + + /** @And the Docker inspect returns the container details */ + $client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-blank')); + + /** @And the reaper list response contains only whitespace */ + $client->withDockerListResponse(output: " \n\t "); + + /** @When runIfNotExists is called */ + $container->runIfNotExists(); + + /** @Then a reaper container should have been started because the whitespace list is treated as empty */ + self::assertStringContainsString( + 'docker run --rm -d --name tiny-blocks-reaper-reaper-blank', + implode(PHP_EOL, $client->getExecutedCommandLines()) + ); + } + + public function testRunWhenNetworkVanishesBeforeStartThenTheNetworkIsProvisionedAgain(): void + { + /** @Given a container that joins a network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'network-again') + ->withNetwork(name: 'my-network'); + + /** @And the Docker daemon creates the container on the first attempt */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon fails to start it because the network was pruned meanwhile */ + $this->client->withDockerStartResponse(output: 'network my-network not found', isSuccessful: false); + + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'network-again') + ); + + /** @When the container is started */ + $container->run(); + + /** @Then the leftover should be removed and the network created again before the second attempt */ + self::assertSame( + [ + 'docker network create', + 'docker create', + 'docker start', + 'docker rm', + 'docker network create', + 'docker create', + 'docker start', + 'docker inspect' + ], + array_values( + array_filter( + array_map( + static fn(string $commandLine): string => str_starts_with($commandLine, 'docker network') + ? implode(' ', array_slice(explode(' ', $commandLine), 0, 3)) + : implode(' ', array_slice(explode(' ', $commandLine), 0, 2)), + $this->client->getExecutedCommandLines() + ), + static fn(string $commandLine): bool => $commandLine !== 'docker network connect' + ) + ) + ); + } + + public function testRunWhenStartFailsThenTheLeftoverContainerIsRemovedWithoutRetrying(): void + { + /** @Given a container that joins no network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'start-cleanup'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon fails to start it */ + $this->client->withDockerStartResponse(output: 'port is already allocated', isSuccessful: false); + + try { + /** @When the container is started */ + $container->run(); + } catch (DockerCommandExecutionFailed) { + /** @Then the leftover container should be removed and no second attempt should be made */ + self::assertSame( + [ + 'docker create', + 'docker start', + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()) + ], + array_map( + static fn(string $commandLine): string => str_starts_with($commandLine, 'docker rm') + ? $commandLine + : implode(' ', array_slice(explode(' ', $commandLine), 0, 2)), + $this->client->getExecutedCommandLines() + ) + ); + } + } + + public function testRunIfNotExistsWhenContainerIsReusedThenWaitsAfterStartedAreSkipped(): void + { + /** @Given a wait strategy applied after a new container starts */ + $wait = $this->createMock(ContainerWaitAfterStarted::class); + + /** @And the wait strategy is never applied */ + $wait->expects(self::never())->method('waitAfter'); + + /** @And a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'reused-waits') + ->withWaitAfterStarted(wait: $wait); + + /** @And the Docker inspect returns the container details */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(hostname: 'reused-waits') + ); + + /** @When the container is asked for */ + $started = $container->runIfNotExists(); + + /** @Then the existing container should be reused without applying the wait strategy */ + self::assertTrue($started->wasReused()); + } + + public function testStopContainerWhenCustomTimeoutThenProcessTimeoutExceedsGracePeriod(): void + { + /** @Given a running container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'stop-buffer'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'stop-buffer') + ); + + /** @And the Docker daemon stops the container */ + $this->client->withDockerStopResponse(output: ''); + + /** @And the container is started */ + $started = $container->run(); + + /** @When the container is stopped with a custom graceful timeout */ + $started->stop(gracePeriod: Duration::fromSeconds(seconds: 45)); + + /** @Then the process timeout requested exceeds the graceful period by the safety buffer */ + self::assertSame([300, 55], $this->client->getRequestedTimeouts()); + } + + public function testRunIfNotExistsWhenWaitAfterStartedFailsThenTheSharedContainerIsKept(): void + { + /** @Given a wait strategy that fails once the container has started */ + $wait = $this->createStub(ContainerWaitAfterStarted::class); + + /** @And the wait strategy times out */ + $wait->method('waitAfter')->willThrowException( + ContainerWaitTimeout::forReadiness(timeout: Duration::fromSeconds(seconds: 1)) + ); + + /** @And a shared container that applies that wait strategy after it starts */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'shared-kept') + ->withWaitAfterStarted(wait: $wait); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'shared-kept')); + + try { + /** @When the container is asked for */ + $container->runIfNotExists(); + } catch (ContainerWaitTimeout) { + /** @Then the shared container should not be removed, since other processes may already use it */ + self::assertNotContains( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + $this->client->getExecutedCommandLines() + ); + } + } + + public function testRunWhenFileCopyFailsThenTheCreatedContainerIsRemovedAndNeverStarted(): void + { + /** @Given a container with a file to copy */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'copy-cleanup') + ->copyToContainer(pathOnHost: '/host/missing', pathOnContainer: '/app/config'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the Docker daemon fails to copy the file */ + $this->client->withDockerCopyResponse(output: 'lstat /host/missing: no such file', isSuccessful: false); + + try { + /** @When the container is started */ + $container->run(); + } catch (DockerCommandExecutionFailed) { + /** @Then the created container should be removed without ever being started */ + self::assertSame( + ['docker create', 'docker cp', 'docker rm'], + array_map( + static fn(array $arguments): string => implode(' ', array_slice($arguments, 0, 2)), + $this->client->getExecutedArguments() + ) + ); + } + } + + public function testRunToCompletionWhenFailedContainerIsNoLongerFoundThenItIsNotRunAgain(): void + { + /** @Given a one-shot container that joins a network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withNetwork(name: 'my-network'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the container exits with a non-zero status, and its inspection finds nothing */ + $this->client->withDockerAttachedStartResponse(output: 'gone', isSuccessful: false); + + /** @Then the error should be thrown, without a second attempt */ + $this->expectException(ContainerExitUnsuccessful::class); + $this->expectExceptionMessageMatches('/Output: \.$/'); + + /** @When the container runs to completion */ + $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); + } + + public function testRunWhenWaitBeforeRunIsRegisteredThenConditionIsCheckedBeforeStarting(): void + { + /** @Given a condition that is immediately ready */ + $condition = $this->createMock(ContainerReady::class); + + /** @And the condition holds on its only check */ + $condition->expects(self::once())->method('isReady')->willReturn(true); + + /** @And a container with a wait-before-run condition */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'wait-test') + ->withWaitBeforeRun(wait: ContainerWaitForDependency::untilReady(condition: $condition)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'wait-test')); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the container should be running (wait was called) */ + self::assertSame('wait-test', $started->getName()); + } + + public function testRemoveWhenContainerIsRunningThenContainerIsRemovedAndNetworksArePruned(): void + { + /** @Given a running container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'force-remove'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'force-remove') + ); + + /** @And the container is started */ + $started = $container->run(); + + /** @When remove is called */ + $started->remove(); + + /** @Then a docker rm command should have been executed with the container ID */ + $commandLines = $this->client->getExecutedCommandLines(); + $removeCommand = $commandLines[3]; + + self::assertStringContainsString('docker rm --force --volumes', $removeCommand); + self::assertStringContainsString( + InspectResponseFixture::shortContainerId(), + $removeCommand + ); + + /** @And a docker network prune command should have been executed with the managed label */ + $pruneCommand = $commandLines[4]; + + self::assertStringContainsString( + 'docker network prune --force --filter label=tiny-blocks.docker-container=true', + $pruneCommand + ); + } + + public function testRunIfNotExistsWhenAnotherProcessCreatesTheContainerFirstThenItIsReused(): void + { + /** @Given a container that does not exist when it is looked up */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'raced'); + + /** @And another process creates a container with the same name first, so the creation conflicts */ + $this->client->withDockerCreateResponse( + output: 'Conflict. The container name "/raced" is already in use by container "6acae5967be0".', + isSuccessful: false + ); + + /** @And the container of the other process is found once the creation fails */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(hostname: 'raced', environment: ['WINNER=true']) + ); + + /** @When the container is asked for */ + $started = $container->runIfNotExists(); + + /** @Then the container of the other process should be reused */ + self::assertTrue($started->wasReused()); + self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); + self::assertSame('true', $started->getEnvironmentVariables()->getValueBy(key: 'WINNER')); + } + + public function testRunIfNotExistsWhenExistingContainerIsNotRunningYetThenWaitsUntilItRuns(): void + { + /** @Given a container another process has created but not started yet */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'starting'); + + /** @And the first lookup finds the container in the created state, without any host port */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'starting') + ); + + /** @And the container is still in the created state on the first readiness check */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'starting') + ); + + /** @And the container is running on the second readiness check */ + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'starting')); + + /** @And the lookup that follows carries the host port Docker assigned on start */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'starting', + exposedPorts: ['80/tcp' => (object)[]], + hostPortBindings: ['80/tcp' => [['HostIp' => '0.0.0.0', 'HostPort' => '32768']]] + ) + ); + + /** @When the container is asked for */ + $started = $container->runIfNotExists(); + + /** @Then the reused container should carry the address it got once it was running */ + self::assertTrue($started->wasReused()); + self::assertSame(32768, $started->getAddress()->getPorts()->firstHostPort()); + } + + public function testRunToCompletionWhenContainerJoinsNoNetworkThenAFailureIsNeverInspected(): void + { + /** @Given a one-shot container that joins no network */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - foreach ($commandLines as $commandLine) { - self::assertStringNotContainsString( - 'docker network connect', - $commandLine + /** @And the container exits with a non-zero status */ + $this->client->withDockerAttachedStartResponse(output: 'failed', isSuccessful: false); + + try { + /** @When the container runs to completion */ + $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); + } catch (ContainerExitUnsuccessful) { + /** @Then the container should be removed without being inspected */ + self::assertSame( + ['docker create', 'docker start', 'docker rm'], + array_map( + static fn(array $arguments): string => implode(' ', array_slice($arguments, 0, 2)), + $this->client->getExecutedArguments() + ) ); } } - public function testRunIfNotExistsWhenContainerIsMissingThenStartedWasNotReused(): void + public function testRunToCompletionWhenNetworkVanishesBeforeStartThenTheContainerRunsAgain(): void { - /** @Given a container that does not exist */ + /** @Given a one-shot container that joins a network */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'fresh-flag'); - - /** @And the Docker list returns empty so the container is created */ - $this->client->withDockerListResponse(output: ''); + ->withNetwork(name: 'my-network'); - /** @And the Docker daemon returns valid run and inspect responses */ + /** @And the Docker daemon creates the container on the first attempt */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'fresh-flag')); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @And the Docker daemon fails to start it because the network was pruned meanwhile */ + $this->client->withDockerAttachedStartResponse(output: 'network my-network not found', isSuccessful: false); - /** @Then the started container should report that it was not reused */ - self::assertFalse($started->wasReused()); + /** @And the inspection shows the container was never started */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(status: 'created')); + + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the container runs and exits successfully on the second attempt */ + $this->client->withDockerAttachedStartResponse(output: 'completed'); + + /** @When the container runs to completion */ + $execution = $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); + + /** @Then the outcome of the second attempt should be returned */ + self::assertSame('completed', $execution->getOutput()); } - public function testExceptionWhenRunFailsRendersCommandWithShellEscapedArguments(): void + public function testRunWhenPullTimeoutIsNotGivenThenContainerCreationIsBoundedByFiveMinutes(): void { - /** @Given a container that will fail to start */ - $container = GenericDockerContainer::from(image: 'invalid:image', client: $this->client) - ->withName(name: 'fail-render-test'); + /** @Given a container with the default pull timeout */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'default-pull'); - /** @And the Docker daemon returns a failure */ - $this->client->withDockerCreateResponse(output: 'boom', isSuccessful: false); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @Then the failure message should render each argument shell-escaped */ - $this->expectException(DockerCommandExecutionFailed::class); - $this->expectExceptionMessageMatches("/'docker' 'create'/"); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build(hostname: 'default-pull') + ); /** @When the container is started */ $container->run(); + + /** @Then the creation of the container should be bounded by 300 seconds */ + self::assertSame([300], $this->client->getRequestedTimeouts()); } - #[RunInSeparateProcess] - public function testGetHostForConnectionWhenInsideDockerReturnsContainerHostname(): void + public function testStopContainerWhenCustomTimeoutThenCommandCarriesTimeoutAsStringArgument(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); - - /** @Given a Docker client */ - $client = new ClientMock(); + /** @Given a running container */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'stop-args'); - /** @And a container with a known hostname */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'conn-host'); + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker daemon returns valid responses */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-args')); - /** @And the inspect response carries the hostname */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'conn-host')); + /** @And the Docker daemon stops the container */ + $this->client->withDockerStopResponse(output: ''); /** @And the container is started */ $started = $container->run(); - /** @When the connection host is resolved inside Docker */ - $host = $started->getAddress()->getHostForConnection(); + /** @When the container is stopped with a custom timeout */ + $started->stop(gracePeriod: Duration::fromSeconds(seconds: 45)); - /** @Then it should be the container hostname */ - self::assertSame('conn-host', $host); + /** @Then the stop command arguments should carry the timeout as a string */ + $stopArguments = $this->client->getExecutedArguments()[3]; + self::assertSame( + ['docker', 'stop', '--time', '45', InspectResponseFixture::shortContainerId()], + $stopArguments + ); } - #[RunInSeparateProcess] - public function testRunContainerWithNetworkWhenInsideDockerConnectsHostToNetwork(): void + public function testRunIfNotExistsWhenInspectionCarriesNoStateThenTheContainerIsReusedAtOnce(): void { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); - - /** @Given a Docker client */ - $client = new ClientMock(); - - /** @And a container configured with a network, running inside a Docker environment */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'inside-docker') - ->withNetwork(name: 'my-network'); - - /** @And the Docker daemon returns valid responses */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + /** @Given a container that already exists */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) + ->withName(name: 'stateless'); - /** @And the inspect response carries the hostname */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'inside-docker')); + /** @And the lookup returns the container details without any state */ + $this->client->withDockerLookupResponse( + inspectResult: array_diff_key(InspectResponseFixture::build(hostname: 'stateless'), ['State' => true]) + ); - /** @When the container is started */ - $container->run(); + /** @When the container is asked for */ + $started = $container->runIfNotExists(); - /** @Then a docker network connect command should connect the host to the network */ - $connectCommand = $client->getExecutedCommandLines()[1]; - self::assertStringStartsWith('docker network connect my-network', $connectCommand); + /** @Then the container should be reused without waiting */ + self::assertTrue($started->wasReused()); + self::assertSame(0.0, ClockMock::elapsedInSeconds()); } - public function testRunIfNotExistsTreatsWhitespaceOnlyListOutputAsMissingContainer(): void + public function testRunIfNotExistsWhenExistingContainerIsNeverStartedThenContainerWaitTimeout(): void { - /** @Given a container that does not exist according to a whitespace-only docker list response */ + /** @Given a container another process created and never started */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'whitespace-list'); - - /** @And the Docker list returns only whitespace */ - $this->client->withDockerListResponse(output: " \n\t "); + ->withName(name: 'stuck'); - /** @And the Docker daemon returns valid run and inspect responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'whitespace-list') - ); + /** @And every lookup finds the container still in the created state */ + for ($index = 0; $index < 200; $index++) { + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'stuck') + ); + } - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @Then a timeout exception should be thrown once the default thirty seconds elapse */ + $this->expectException(ContainerWaitTimeout::class); + $this->expectExceptionMessage('Container readiness check timed out after <30> seconds.'); - /** @Then a new container should be created because the whitespace list output is trimmed */ - self::assertSame('whitespace-list', $started->getName()); + /** @When the container is asked for */ + $container->runIfNotExists(); } - public function testRunWhenFilesAreCopiedThenTheyAreCopiedBeforeTheContainerStarts(): void + public function testRunToCompletionWhenNetworkVanishesBeforeStartThenBothContainersAreRemoved(): void { - /** @Given a container with a copy instruction */ + /** @Given a one-shot container that joins a network */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'cp-before-start') - ->copyToContainer(pathOnHost: '/host/sql', pathOnContainer: '/app/sql'); + ->withNetwork(name: 'my-network'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container on the first attempt */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'cp-before-start') - ); - /** @When the container is started */ - $container->run(); + /** @And the Docker daemon fails to start it because the network was pruned meanwhile */ + $this->client->withDockerAttachedStartResponse(output: 'network my-network not found', isSuccessful: false); - /** @Then the container should be created, receive the files, be started, and only then be inspected */ + /** @And the inspection shows the container was never started */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(status: 'created')); + + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the container runs and exits successfully on the second attempt */ + $this->client->withDockerAttachedStartResponse(output: 'completed'); + + /** @When the container runs to completion */ + $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); + + /** @Then the container of each attempt should have been removed */ self::assertSame( - ['docker create', 'docker cp', 'docker start', 'docker inspect'], - array_map( - static fn(array $arguments): string => implode(' ', array_slice($arguments, 0, 2)), - $this->client->getExecutedArguments() + [ + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + 'docker rm --force --volumes f1e2d3c4b5a6' + ], + array_values( + array_filter( + $this->client->getExecutedCommandLines(), + static fn(string $commandLine): bool => str_starts_with($commandLine, 'docker rm') + ) ) ); } - public function testRunWhenTwoWaitsAfterStartedAreAddedThenBothReceiveTheContainer(): void + public function testRunIfNotExistsWhenReaperIsStartedThenItsImagePullIsBoundedByThePullTimeout(): void { - /** @Given a first wait strategy applied after the container starts */ - $first = $this->createMock(ContainerWaitAfterStarted::class); - $first->expects(self::once())->method('waitAfter'); + /** @Given the code runs inside Docker */ + HostMock::insideDocker(); - /** @And a second wait strategy applied after the container starts */ - $second = $this->createMock(ContainerWaitAfterStarted::class); - $second->expects(self::once())->method('waitAfter'); + /** @And a Docker client */ + $client = new ClientMock(); - /** @And a container that applies both wait strategies after it starts */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'two-waits-after') - ->withWaitAfterStarted(wait: $first) - ->withWaitAfterStarted(wait: $second); + /** @And a container that already exists, with a pull timeout of ten minutes */ + $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) + ->withName(name: 'reaper-pull') + ->withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'two-waits-after') - ); + /** @And the lookup returns the container details */ + $client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-pull')); - /** @When the container is started */ - $started = $container->run(); + /** @When the container is asked for */ + $container->runIfNotExists(); - /** @Then the container should be running after both wait strategies were applied */ - self::assertSame('two-waits-after', $started->getName()); + /** @Then starting the reaper should be bounded by the pull timeout */ + self::assertSame([600], $client->getRequestedTimeouts()); } - public function testRunContainerWhenContainerIdIsExactlyMinimumLengthThenIdIsAccepted(): void + public function testRunToCompletionWhenNeverStartedOnBothAttemptsThenContainerExitUnsuccessful(): void { - /** @Given a container */ + /** @Given a one-shot container that joins a network */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'min-id'); - - /** @And the Docker daemon returns a container ID exactly at the minimum length */ - $this->client->withDockerCreateResponse(output: '123456789012'); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'min-id')); - - /** @When the container is started */ - $started = $container->run(); - - /** @Then the full minimum-length ID should be accepted and preserved */ - self::assertSame('123456789012', $started->getId()); - } + ->withNetwork(name: 'my-network'); - #[RunInSeparateProcess] - public function testRunIfNotExistsWhenReaperListIsWhitespaceThenStartsReaperContainer(): void - { - $template = '%s/Internal/Containers/Overrides/file_exists_inside_docker.php'; - require_once sprintf($template, __DIR__); + /** @And the Docker daemon creates the container on the first attempt */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @Given a Docker client */ - $client = new ClientMock(); + /** @And the Docker daemon fails to start it */ + $this->client->withDockerAttachedStartResponse(output: 'first failure', isSuccessful: false); - /** @And a container that already exists */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $client) - ->withName(name: 'reaper-blank'); + /** @And the inspection shows the container was never started */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(status: 'created')); - /** @And the Docker list returns an existing container */ - $client->withDockerListResponse(output: InspectResponseFixture::containerId()); + /** @And the Docker daemon creates the container again on the second attempt */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); - /** @And the Docker inspect returns the container details */ - $client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'reaper-blank')); + /** @And the Docker daemon fails to start it again */ + $this->client->withDockerAttachedStartResponse(output: 'second failure', isSuccessful: false); - /** @And the reaper list response contains only whitespace */ - $client->withDockerListResponse(output: " \n\t "); + /** @And an inspection of the second container would also show it was never started */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(status: 'created')); - /** @When runIfNotExists is called */ - $container->runIfNotExists(); + /** @Then the failure of the second attempt should be thrown, without a third attempt */ + $this->expectException(ContainerExitUnsuccessful::class); + $this->expectExceptionMessageMatches('/Output: \.$/'); - /** @Then a reaper container should have been started because the whitespace list is treated as empty */ - self::assertStringContainsString( - 'docker run --rm -d --name tiny-blocks-reaper-reaper-blank', - implode(PHP_EOL, $client->getExecutedCommandLines()) - ); + /** @When the container runs to completion */ + $container->runToCompletion(timeout: Duration::fromSeconds(seconds: 10)); } - public function testRunIfNotExistsWhenContainerIsReusedThenWaitsAfterStartedAreSkipped(): void + public function testRunIfNotExistsWhenExistingContainerVanishesWhileWaitingThenANewOneIsStarted(): void { - /** @Given a wait strategy applied after a new container starts */ - $wait = $this->createMock(ContainerWaitAfterStarted::class); - $wait->expects(self::never())->method('waitAfter'); - - /** @And a container that already exists */ + /** @Given a container another process created, then removed before starting it */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'reused-waits') - ->withWaitAfterStarted(wait: $wait); + ->withName(name: 'vanished'); - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); - - /** @And the Docker inspect returns the container details */ - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'reused-waits') + /** @And the first lookup finds the container in the created state */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'vanished') ); + /** @And the Docker daemon creates a new container */ + $this->client->withDockerCreateResponse(output: 'f1e2d3c4b5a6f1e2d3c4b5a6'); + + /** @And the inspect response carries the details of the new container */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'vanished')); + /** @When the container is asked for */ $started = $container->runIfNotExists(); - /** @Then the existing container should be reused without applying the wait strategy */ - self::assertTrue($started->wasReused()); + /** @Then a new container should have been started rather than reused */ + self::assertFalse($started->wasReused()); + self::assertSame('f1e2d3c4b5a6', $started->getId()); } - public function testStopContainerWhenCustomTimeoutThenProcessTimeoutExceedsGracePeriod(): void + public function testExecuteAfterStartedWhenCommandsAreGivenThenDockerExecTargetsTheContainerName(): void { /** @Given a running container */ $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-buffer'); + ->withName(name: 'exec-cmd'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build(hostname: 'stop-buffer') - ); - $this->client->withDockerStopResponse(output: ''); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'exec-cmd')); + + /** @And the command executed inside the container succeeds */ + $this->client->withDockerExecuteResponse(output: ''); /** @And the container is started */ $started = $container->run(); - /** @When the container is stopped with a custom graceful timeout */ - $started->stop(gracePeriod: Duration::fromSeconds(seconds: 45)); + /** @When executing commands inside the container */ + $started->executeAfterStarted(commands: ['ls', '-la', '/tmp']); - /** @Then the process timeout requested exceeds the graceful period by the safety buffer */ - self::assertSame([55], $this->client->getRequestedTimeouts()); + /** @Then a docker exec command should have been executed with the container name and commands */ + $execCommand = $this->client->getExecutedCommandLines()[3]; + self::assertSame('docker exec exec-cmd ls -la /tmp', $execCommand); } - public function testStopContainerWhenCustomTimeoutThenCommandCarriesTimeoutAsStringArgument(): void + public function testRunIfNotExistsWhenExistingContainerIsNotRunningYetThenPollsEveryQuarterSecond(): void { - /** @Given a running container */ - $container = GenericDockerContainer::from(image: 'alpine:latest', client: $this->client) - ->withName(name: 'stop-args'); + /** @Given a container another process has created but not started yet */ + $container = GenericDockerContainer::from(image: 'nginx:latest', client: $this->client) + ->withName(name: 'polled'); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse(inspectResult: InspectResponseFixture::build(hostname: 'stop-args')); - $this->client->withDockerStopResponse(output: ''); + /** @And the first lookup finds the container in the created state */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'polled') + ); - /** @And the container is started */ - $started = $container->run(); + /** @And the container is still in the created state on the first readiness check */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build(status: 'created', hostname: 'polled') + ); - /** @When the container is stopped with a custom timeout */ - $started->stop(gracePeriod: Duration::fromSeconds(seconds: 45)); + /** @And the container is running on the second readiness check */ + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'polled')); - /** @Then the stop command arguments should carry the timeout as a string */ - $stopArguments = $this->client->getExecutedArguments()[3]; - self::assertSame( - ['docker', 'stop', '--time', '45', InspectResponseFixture::shortContainerId()], - $stopArguments - ); + /** @And the lookup that follows finds it running */ + $this->client->withDockerLookupResponse(inspectResult: InspectResponseFixture::build(hostname: 'polled')); + + /** @When the container is asked for */ + $container->runIfNotExists(); + + /** @Then a single poll interval should have been spent waiting */ + self::assertSame(0.25, ClockMock::elapsedInSeconds()); } public function testRunToCompletionWhenWaitBeforeRunIsRegisteredThenWaitsBeforeCreatingTheContainer(): void { /** @Given a condition that is immediately ready */ $condition = $this->createMock(ContainerReady::class); + + /** @And the condition holds on its only check */ $condition->expects(self::once())->method('isReady')->willReturn(true); /** @And a container with a wait-before-run condition */ @@ -1908,4 +2761,21 @@ public function testRunToCompletionWhenWaitBeforeRunIsRegisteredThenWaitsBeforeC /** @Then the container should be created once the wait is satisfied */ self::assertStringStartsWith('docker create', $this->client->getExecutedCommandLines()[0]); } + + public function testRunIfNotExistsWhenCreationFailsAndNoContainerExistsThenDockerCommandExecutionFailed(): void + { + /** @Given a container that does not exist */ + $container = GenericDockerContainer::from(image: 'invalid:image', client: $this->client) + ->withName(name: 'never-created'); + + /** @And the Docker daemon fails to create it for a reason other than a name conflict */ + $this->client->withDockerCreateResponse(output: 'pull access denied', isSuccessful: false); + + /** @Then the failure reported by Docker should be thrown */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches('/Reason: pull access denied/'); + + /** @When the container is asked for */ + $container->runIfNotExists(); + } } diff --git a/tests/Unit/HostMock.php b/tests/Unit/HostMock.php new file mode 100644 index 0000000..5ea4faf --- /dev/null +++ b/tests/Unit/HostMock.php @@ -0,0 +1,69 @@ +client->executeWithTimeout(command: $command); diff --git a/tests/Unit/Internal/Containers/Overrides/file_exists_inside_docker.php b/tests/Unit/Internal/Containers/Overrides/file_exists_inside_docker.php deleted file mode 100644 index ed0ea37..0000000 --- a/tests/Unit/Internal/Containers/Overrides/file_exists_inside_docker.php +++ /dev/null @@ -1,10 +0,0 @@ -client = new ClientMock(); } - public function testGetJdbcUrlWithoutOptions(): void + protected function tearDown(): void { - /** @Given a running MySQL container */ - $started = RunningMySQLContainer::startWith( - client: $this->client, - database: 'test_adm', - hostname: 'test-db', - port: 3306 - ); - - /** @When getting the JDBC URL with empty options */ - $jdbcUrl = $started->getJdbcUrl(options: []); - - /** @Then the URL should not include any query string */ - self::assertSame('jdbc:mysql://test-db:3306/test_adm', $jdbcUrl); + HostMock::reset(); + ClockMock::release(); } - public function testGetJdbcUrlWithCustomOptions(): void + public function testStopWhenMySQLIsStartedThenStopIsSuccessful(): void { /** @Given a running MySQL container */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'test-db', - port: 3306 - ); - - /** @When getting the JDBC URL with custom options */ - $jdbcUrl = $started->getJdbcUrl(options: ['connectTimeout' => '5000', 'useSSL' => 'true']); - - /** @Then the URL should include the custom options */ - self::assertSame( - 'jdbc:mysql://test-db:3306/test_adm?connectTimeout=5000&useSSL=true', - $jdbcUrl - ); - } - - public function testCustomReadinessTimeoutIsUsed(): void - { - /** @Given a MySQL container with a custom readiness timeout */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'timeout-db') - ->withDatabase(database: 'test_db') - ->withRootPassword(rootPassword: 'root') - ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 60)); - - /** @And the Docker daemon starts the container */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'timeout-db', - environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] - ) - ); - - /** @And the MySQL readiness check succeeds on first attempt */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - $this->client->withDockerExecuteResponse(output: ''); - - /** @When the MySQL container is started */ - $started = $container->run(); - - /** @Then the container should start successfully */ - self::assertSame('timeout-db', $started->getName()); - } - - public function testGetJdbcUrlWithDefaultOptions(): void - { - /** @Given a running MySQL container */ - $started = RunningMySQLContainer::startWith( - client: $this->client, - database: 'test_adm', - hostname: 'test-db', + hostname: 'stop-db', port: 3306 ); - /** @When getting the JDBC URL with default options */ - $jdbcUrl = $started->getJdbcUrl(); + /** @And the Docker stop command succeeds */ + $this->client->withDockerStopResponse(output: ''); - /** @Then the URL should include default JDBC options */ - $options = implode('&', [ - 'useSSL=false', - 'useUnicode=yes', - 'characterEncoding=UTF-8', - 'allowPublicKeyRetrieval=true' - ]); - $template = 'jdbc:mysql://test-db:3306/test_adm?%s'; + /** @When the container is stopped */ + $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); - self::assertSame(sprintf($template, $options), $jdbcUrl); + /** @Then the stop should be successful */ + self::assertTrue($stopped->isSuccessful()); } - public function testRunMySQLContainerSuccessfully(): void + public function testRunWhenFilesAreRegisteredThenMySQLContainerStarts(): void { - /** @Given a MySQL container with full configuration */ + /** @Given a MySQL container with files to copy */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'test-db') - ->withNetwork(name: 'my-net') - ->withDatabase(database: 'test_adm') - ->withPassword(password: 'secret') - ->withTimezone(timezone: 'America/Sao_Paulo') - ->withUsername(user: 'app_user') - ->withPortMapping(portOnHost: 3306, portOnContainer: 3306) - ->withGrantedHosts() - ->withRootPassword(rootPassword: 'root') - ->withoutAutoRemove() - ->withVolumeMapping(pathOnHost: '/var/lib/mysql', pathOnContainer: '/var/lib/mysql'); + ->withName(name: 'copy-db') + ->copyToContainer(pathOnHost: '/host/init', pathOnContainer: '/docker-entrypoint-initdb.d') + ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'test-db', - environment: [ - 'TZ=America/Sao_Paulo', - 'MYSQL_USER=app_user', - 'MYSQL_PASSWORD=secret', - 'MYSQL_DATABASE=test_adm', - 'MYSQL_ROOT_PASSWORD=root' - ], - networkName: 'my-net', - exposedPorts: ['3306/tcp' => (object)[]] + hostname: 'copy-db', + environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness check succeeds */ + /** @And the readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @And the database setup command succeeds */ - $this->client->withDockerExecuteResponse(output: ''); - - /** @When the MySQL container is started */ + /** @When the container is started */ $started = $container->run(); - /** @Then it should return a MySQLContainerStarted instance */ - self::assertSame('test-db', $started->getName()); - self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); - - /** @And the environment variables should be accessible */ - self::assertSame( - 'test_adm', - $started->getEnvironmentVariables()->getValueBy( - key: 'MYSQL_DATABASE' - ) - ); - self::assertSame( - 'app_user', - $started->getEnvironmentVariables()->getValueBy( - key: 'MYSQL_USER' - ) - ); - self::assertSame( - 'secret', - $started->getEnvironmentVariables()->getValueBy( - key: 'MYSQL_PASSWORD' - ) - ); - self::assertSame( - 'root', - $started->getEnvironmentVariables()->getValueBy( - key: 'MYSQL_ROOT_PASSWORD' - ) - ); - - /** @And the port should be exposed */ - self::assertSame(3306, $started->getAddress()->getPorts()->firstExposedPort()); + /** @Then the container should be running with copy instructions executed */ + self::assertSame('copy-db', $started->getName()); - /** @And the docker run command should reflect delegated configuration */ + /** @And the docker cp command should have been executed */ $commandLines = $this->client->getExecutedCommandLines(); - $runCommand = $commandLines[2]; - - self::assertStringNotContainsString('--rm', $runCommand); - self::assertStringContainsString('--volume /var/lib/mysql:/var/lib/mysql', $runCommand); - self::assertStringContainsString('--publish 3306:3306', $runCommand); - self::assertStringContainsString('TZ=America/Sao_Paulo', $runCommand); - self::assertStringContainsString('MYSQL_USER=app_user', $runCommand); - self::assertStringContainsString('MYSQL_PASSWORD=secret', $runCommand); - self::assertStringContainsString('MYSQL_DATABASE=test_adm', $runCommand); - self::assertStringContainsString('MYSQL_ROOT_PASSWORD=root', $runCommand); - - /** @And the readiness probe should execute env-prefixed mysqladmin ping via docker exec */ - $readinessCommand = $commandLines[5]; - - self::assertStringContainsString( - 'docker exec test-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', - $readinessCommand - ); - /** @And the database setup should include CREATE DATABASE, GRANT, and FLUSH */ - $setupCommand = $commandLines[6]; - - self::assertStringContainsString('CREATE DATABASE IF NOT EXISTS test_adm', $setupCommand); - self::assertStringContainsString('GRANT ALL PRIVILEGES', $setupCommand); - self::assertStringContainsString('FLUSH PRIVILEGES', $setupCommand); - - /** @And the GRANT statements should include both default hosts */ - self::assertStringContainsString("'root'@'%'", $setupCommand); - self::assertStringContainsString("'root'@'172.%'", $setupCommand); - } - - public function testRunMySQLContainerWithoutDatabase(): void - { - /** @Given a MySQL container without a database configured */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'no-db') - ->withRootPassword(rootPassword: 'root'); - - /** @And the Docker daemon returns valid responses with no MYSQL_DATABASE */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'no-db', - environment: ['MYSQL_ROOT_PASSWORD=root'] + self::assertNotEmpty( + array_filter( + $commandLines, + static fn(string $line): bool => str_contains($line, 'docker cp') && str_contains($line, '/host/init') ) ); - - /** @And the MySQL readiness check succeeds */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - - /** @When the MySQL container is started (no CREATE DATABASE should be called) */ - $started = $container->run(); - - /** @Then the container should start without errors */ - self::assertSame('no-db', $started->getName()); } - public function testMySQLContainerDelegatesGetAddress(): void + public function testRemoveWhenMySQLIsStartedThenDockerRemoveIsExecuted(): void { /** @Given a running MySQL container */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'address-db', + hostname: 'remove-db', port: 3306 ); - /** @When getting the container address */ - $address = $started->getAddress(); - - /** @Then the address should delegate correctly */ - self::assertSame('address-db', $address->getHostname()); - self::assertSame('172.22.0.2', $address->getIp()); - self::assertSame(3306, $address->getPorts()->firstExposedPort()); - self::assertSame([3306], $address->getPorts()->exposedPorts()); - } - - public function testRunMySQLContainerWithWaitBeforeRun(): void - { - /** @Given a MySQL container with a wait-before-run condition */ - $condition = $this->createMock(ContainerReady::class); - $condition->expects(self::once())->method('isReady')->willReturn(true); - - /** @And the container is configured */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'wait-db') - ->withRootPassword(rootPassword: 'root') - ->withWaitBeforeRun( - wait: ContainerWaitForDependency::untilReady(condition: $condition) - ); - - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'wait-db', - environment: ['MYSQL_ROOT_PASSWORD=root'] - ) - ); - - /** @And the MySQL readiness check succeeds */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + /** @When remove is called */ + $started->remove(); - /** @When the container is started */ - $started = $container->run(); + /** @Then the docker rm command should have been executed */ + $commandLines = $this->client->getExecutedCommandLines(); + $removeCommand = $commandLines[5]; - /** @Then the wait-before-run condition should have been evaluated */ - self::assertSame('wait-db', $started->getName()); + self::assertStringContainsString('docker rm --force --volumes', $removeCommand); } - public function testExceptionWhenMySQLNeverBecomesReady(): void + public function testGetJdbcUrlWhenNoPortIsExposedThenDefaultsToPort3306(): void { - /** @Given a MySQL container with a very short readiness timeout */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'stuck-db') - ->withDatabase(database: 'test_db') - ->withRootPassword(rootPassword: 'root') - ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); - - /** @And the Docker daemon starts the container */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'stuck-db', - environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] - ) + /** @Given a running MySQL container with no exposed ports */ + $started = RunningMySQLContainer::startWith( + client: $this->client, + database: 'test_adm', + hostname: 'test-db' ); - /** @And the MySQL readiness check always fails */ - for ($index = 0; $index < 100; $index++) { - $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); - } - - /** @Then a ContainerWaitTimeout exception should be thrown */ - $this->expectException(ContainerWaitTimeout::class); - $this->expectExceptionMessage('Container readiness check timed out after <1> seconds.'); + /** @When getting the JDBC URL */ + $jdbcUrl = $started->getJdbcUrl(options: []); - /** @When attempting to start the MySQL container */ - $container->run(); + /** @Then the URL should use the default MySQL port 3306 */ + self::assertSame('jdbc:mysql://test-db:3306/test_adm', $jdbcUrl); } - public function testMySQLContainerDelegatesStopCorrectly(): void + public function testStopWhenGracePeriodIsGivenThenMySQLStopIsSuccessful(): void { /** @Given a running MySQL container */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'stop-db', + hostname: 'stop-timeout-db', port: 3306 ); /** @And the Docker stop command succeeds */ $this->client->withDockerStopResponse(output: ''); - /** @When the container is stopped */ + /** @When the container is stopped with a custom timeout */ $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); /** @Then the stop should be successful */ self::assertTrue($stopped->isSuccessful()); } - public function testRemoveDelegatesToUnderlyingContainer(): void + public function testGetJdbcUrlWhenCustomOptionsAreGivenThenUrlCarriesThem(): void { /** @Given a running MySQL container */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'remove-db', + hostname: 'test-db', port: 3306 ); - /** @When remove is called */ - $started->remove(); - - /** @Then the docker rm command should have been executed */ - $commandLines = $this->client->getExecutedCommandLines(); - $removeCommand = $commandLines[5]; + /** @When getting the JDBC URL with custom options */ + $jdbcUrl = $started->getJdbcUrl(options: ['connectTimeout' => '5000', 'useSSL' => 'true']); - self::assertStringContainsString('docker rm --force --volumes', $removeCommand); + /** @Then the URL should include the custom options */ + self::assertSame( + 'jdbc:mysql://test-db:3306/test_adm?connectTimeout=5000&useSSL=true', + $jdbcUrl + ); } - public function testRunMySQLContainerWithCopyToContainer(): void + public function testRunIfNotExistsWhenContainerExistsThenStartedWasReused(): void { - /** @Given a MySQL container with files to copy */ + /** @Given a MySQL container that already exists */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'copy-db') - ->copyToContainer(pathOnHost: '/host/init', pathOnContainer: '/docker-entrypoint-initdb.d') + ->withName(name: 'reused-db') ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon returns valid responses */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( + /** @And the Docker inspect returns the container details */ + $this->client->withDockerLookupResponse( inspectResult: InspectResponseFixture::build( - hostname: 'copy-db', + hostname: 'reused-db', environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the readiness check succeeds */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - - /** @When the container is started */ - $started = $container->run(); - - /** @Then the container should be running with copy instructions executed */ - self::assertSame('copy-db', $started->getName()); - - /** @And the docker cp command should have been executed */ - $commandLines = $this->client->getExecutedCommandLines(); + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); - self::assertNotEmpty( - array_filter( - $commandLines, - static fn(string $line): bool => str_contains($line, 'docker cp') && str_contains($line, '/host/init') - ) - ); + /** @Then the started container should report that it was reused */ + self::assertTrue($started->wasReused()); } - public function testRunMySQLContainerWithoutGrantedHosts(): void + public function testRunWhenEphemeralStorageThenDataDirectoryIsATmpfsMount(): void { - /** @Given a MySQL container without granted hosts */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'no-grants') - ->withDatabase(database: 'test_db') - ->withRootPassword(rootPassword: 'root'); + /** @Given a MySQL container with ephemeral storage */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'ephemeral-db') + ->withRootPassword(rootPassword: 'root') + ->withEphemeralStorage(); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'no-grants', - environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'ephemeral-db', + environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness and CREATE DATABASE calls succeed */ + /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - $this->client->withDockerExecuteResponse(output: ''); - - /** @When the MySQL container is started (no GRANT PRIVILEGES should be called) */ - $started = $container->run(); - - /** @Then the container should start without errors */ - self::assertSame('no-grants', $started->getName()); - /** @And the setup should include CREATE DATABASE but no GRANT statements */ - $commandLines = $this->client->getExecutedCommandLines(); - $setupCommand = $commandLines[4]; + /** @When the MySQL container is started */ + $container->run(); - self::assertStringContainsString('CREATE DATABASE IF NOT EXISTS test_db', $setupCommand); - self::assertStringNotContainsString('GRANT ALL PRIVILEGES', $setupCommand); + /** @Then the MySQL data directory should be a tmpfs mount */ + self::assertStringContainsString('--tmpfs /var/lib/mysql', $this->client->getExecutedCommandLines()[0]); } - public function testRunIfNotExistsCreatesNewMySQLContainer(): void + public function testRunWhenMySQLNeverBecomesReadyThenContainerWaitTimeout(): void { - /** @Given a MySQL container that does not exist */ + /** @Given a MySQL container with a very short readiness timeout */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'new-db') - ->withDatabase(database: 'new_db') - ->withRootPassword(rootPassword: 'root'); - - /** @And the Docker list returns empty (container does not exist) */ - $this->client->withDockerListResponse(output: ''); + ->withName(name: 'stuck-db') + ->withDatabase(database: 'test_db') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); - /** @And the Docker daemon returns valid run and inspect responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'new-db', - environment: ['MYSQL_DATABASE=new_db', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'stuck-db', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness check and CREATE DATABASE succeed */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - $this->client->withDockerExecuteResponse(output: ''); + /** @And the MySQL readiness check always fails */ + for ($index = 0; $index < 100; $index++) { + $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + } - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @Then a ContainerWaitTimeout exception should be thrown */ + $this->expectException(ContainerWaitTimeout::class); + $this->expectExceptionMessage('Container readiness check timed out after <1> seconds.'); - /** @Then a new container should be created */ - self::assertSame('new-db', $started->getName()); + /** @When attempting to start the MySQL container */ + $container->run(); } - public function testRunMySQLContainerWithSingleGrantedHost(): void + public function testRunWhenNoDatabaseIsConfiguredThenMySQLContainerStarts(): void { - /** @Given a MySQL container with a single granted host */ + /** @Given a MySQL container without a database configured */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'single-grant') - ->withDatabase(database: 'test_db') - ->withGrantedHosts(hosts: ['%']) + ->withName(name: 'no-db') ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'single-grant', - environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'no-db', + environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And readiness and database setup succeed */ + /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - $this->client->withDockerExecuteResponse(output: ''); - /** @When the container is started */ + /** @When the MySQL container is started (no CREATE DATABASE should be called) */ $started = $container->run(); - /** @Then the container should start successfully */ - self::assertSame('single-grant', $started->getName()); + /** @Then the container should start without errors */ + self::assertSame('no-db', $started->getName()); } - public function testMySQLContainerDelegatesExecuteAfterStarted(): void + public function testGetJdbcUrlWhenNoOptionsAreGivenThenUrlHasNoQueryString(): void { /** @Given a running MySQL container */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'exec-db', + hostname: 'test-db', port: 3306 ); - /** @And a command execution returns output */ - $this->client->withDockerExecuteResponse(output: 'SHOW DATABASES output'); - - /** @When commands are executed inside the container */ - $execution = $started->executeAfterStarted(commands: ['mysql', '-e', 'SHOW DATABASES']); + /** @When getting the JDBC URL with empty options */ + $jdbcUrl = $started->getJdbcUrl(options: []); - /** @Then the execution should return the output */ - self::assertTrue($execution->isSuccessful()); - self::assertSame('SHOW DATABASES output', $execution->getOutput()); + /** @Then the URL should not include any query string */ + self::assertSame('jdbc:mysql://test-db:3306/test_adm', $jdbcUrl); } - public function testRunIfNotExistsReturnsMySQLContainerStarted(): void + public function testRunWhenMySQLNeverBecomesReadyThenTheContainerIsRemoved(): void { - /** @Given a MySQL container */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'existing-db') - ->withDatabase(database: 'my_db') - ->withRootPassword(rootPassword: 'root'); + /** @Given a MySQL container with a readiness timeout of one second */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'never-ready') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the container already exists */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); + /** @And the inspect response carries the root password */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'existing-db', - environment: ['MYSQL_DATABASE=my_db', 'MYSQL_ROOT_PASSWORD=root'], - exposedPorts: ['3306/tcp' => (object)[]] + hostname: 'never-ready', + environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @And the MySQL readiness check always fails */ + for ($index = 0; $index < 10; $index++) { + $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + } - /** @Then it should return a MySQLContainerStarted wrapping the existing container */ - self::assertSame('existing-db', $started->getName()); + try { + /** @When the container is started */ + $container->run(); + } catch (ContainerWaitTimeout) { + /** @Then the container should be removed, since no one holds it */ + self::assertContains( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + $this->client->getExecutedCommandLines() + ); + } } - public function testMySQLContainerDelegatesStopWithCustomTimeout(): void + public function testRunWhenReadinessTimeoutIsGivenThenMySQLContainerStarts(): void { - /** @Given a running MySQL container */ - $started = RunningMySQLContainer::startWith( - client: $this->client, - database: 'test_adm', - hostname: 'stop-timeout-db', - port: 3306 + /** @Given a MySQL container with a custom readiness timeout */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'timeout-db') + ->withDatabase(database: 'test_db') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 60)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'timeout-db', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + ) ); - /** @And the Docker stop command succeeds */ - $this->client->withDockerStopResponse(output: ''); + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @When the container is stopped with a custom timeout */ - $stopped = $started->stop(gracePeriod: Duration::fromSeconds(seconds: 10)); + /** @And the database setup succeeds */ + $this->client->withDockerExecuteResponse(output: ''); - /** @Then the stop should be successful */ - self::assertTrue($stopped->isSuccessful()); + /** @When the MySQL container is started */ + $started = $container->run(); + + /** @Then the container should start successfully */ + self::assertSame('timeout-db', $started->getName()); } - #[RunInSeparateProcess] - public function testStopOnShutdownDelegatesToUnderlyingContainer(): void + public function testRunWhenEphemeralStorageThenServerStartsWithoutBinaryLog(): void { - $template = '%s/Internal/Containers/Overrides/register_shutdown_function_spy.php'; - require_once sprintf($template, __DIR__); - - /** @Given a Docker client */ - $client = new ClientMock(); - - /** @And a MySQL container */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $client) - ->withName(name: 'shutdown-db') - ->withDatabase(database: 'test_adm') - ->withRootPassword(rootPassword: 'root'); + /** @Given a MySQL container with ephemeral storage */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'fast-db') + ->withRootPassword(rootPassword: 'root') + ->withEphemeralStorage(); /** @And the Docker daemon creates the container */ - $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the inspect response carries the MySQL settings */ - $client->withDockerInspectResponse( + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'shutdown-db', - environment: ['MYSQL_DATABASE=test_adm', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'fast-db', + environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the container is started */ - $started = $container->run(); + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @When stopOnShutdown is called */ - $started->stopOnShutdown(); + /** @When the MySQL container is started */ + $container->run(); - /** @Then exactly one shutdown callback should have been registered */ - self::assertCount(1, $GLOBALS['registeredShutdownCallbacks']); + /** @Then the MySQL server should start without the binary log */ + self::assertSame( + ['mysql:8.4', '--skip-log-bin'], + array_slice($this->client->getExecutedArguments()[0], -2) + ); } - public function testGetJdbcUrlDefaultsToPort3306WhenNoPortExposed(): void + public function testGetJdbcUrlWhenAnotherPortIsExposedThenUsesTheExposedPort(): void { - /** @Given a running MySQL container with no exposed ports */ + /** @Given a running MySQL container with a non-default port */ $started = RunningMySQLContainer::startWith( client: $this->client, database: 'test_adm', - hostname: 'test-db' + hostname: 'custom-port-db', + port: 3307 ); /** @When getting the JDBC URL */ $jdbcUrl = $started->getJdbcUrl(options: []); - /** @Then the URL should use the default MySQL port 3306 */ - self::assertSame('jdbc:mysql://test-db:3306/test_adm', $jdbcUrl); + /** @Then the URL should use the exposed port 3307 instead of the default 3306 */ + self::assertSame('jdbc:mysql://custom-port-db:3307/test_adm', $jdbcUrl); } - public function testMySQLContainerWithEnvironmentVariableDirectly(): void + public function testRunWhenMySQLBecomesReadyThenReturnsMySQLContainerStarted(): void { - /** @Given a MySQL container with a custom environment variable */ + /** @Given a MySQL container with full configuration */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'env-db') + ->withName(name: 'test-db') + ->withNetwork(name: 'my-net') + ->withDatabase(database: 'test_adm') + ->withPassword(password: 'secret') + ->withTimezone(timezone: 'America/Sao_Paulo') + ->withUsername(user: 'app_user') + ->withPortMapping(portOnHost: 3306, portOnContainer: 3306) + ->withGrantedHosts() ->withRootPassword(rootPassword: 'root') - ->withEnvironmentVariable(key: 'CUSTOM_KEY', value: 'custom_value'); + ->withoutAutoRemove() + ->withVolumeMapping(pathOnHost: '/var/lib/mysql', pathOnContainer: '/var/lib/mysql'); - /** @And the Docker daemon returns valid responses including the custom env var */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'env-db', - environment: ['MYSQL_ROOT_PASSWORD=root', 'CUSTOM_KEY=custom_value'] + hostname: 'test-db', + environment: [ + 'TZ=America/Sao_Paulo', + 'MYSQL_USER=app_user', + 'MYSQL_PASSWORD=secret', + 'MYSQL_DATABASE=test_adm', + 'MYSQL_ROOT_PASSWORD=root' + ], + networkName: 'my-net', + exposedPorts: ['3306/tcp' => (object)[]] ) ); /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + /** @And the database setup command succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + /** @When the MySQL container is started */ $started = $container->run(); - /** @Then the custom environment variable should be accessible */ + /** @Then it should return a MySQLContainerStarted instance */ + self::assertSame('test-db', $started->getName()); + self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); + + /** @And the environment variables should be accessible */ self::assertSame( - 'custom_value', + 'test_adm', $started->getEnvironmentVariables()->getValueBy( - key: 'CUSTOM_KEY' + key: 'MYSQL_DATABASE' ) ); - - /** @And the docker run command should include the custom environment variable */ - $runCommand = $this->client->getExecutedCommandLines()[0]; - - self::assertStringContainsString('CUSTOM_KEY=custom_value', $runCommand); - } - - public function testRunMySQLContainerWithGrantedHostsButNoDatabase(): void - { - /** @Given a MySQL container with granted hosts but no database */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'grants-only') - ->withGrantedHosts(hosts: ['%']) - ->withRootPassword(rootPassword: 'root'); - - /** @And the Docker daemon returns valid responses without MYSQL_DATABASE */ - $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - $this->client->withDockerInspectResponse( - inspectResult: InspectResponseFixture::build( - hostname: 'grants-only', - environment: ['MYSQL_ROOT_PASSWORD=root'] + self::assertSame( + 'app_user', + $started->getEnvironmentVariables()->getValueBy( + key: 'MYSQL_USER' + ) + ); + self::assertSame( + 'secret', + $started->getEnvironmentVariables()->getValueBy( + key: 'MYSQL_PASSWORD' + ) + ); + self::assertSame( + 'root', + $started->getEnvironmentVariables()->getValueBy( + key: 'MYSQL_ROOT_PASSWORD' ) ); - /** @And the MySQL readiness check and setup succeed */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - $this->client->withDockerExecuteResponse(output: ''); - - /** @When the MySQL container is started */ - $started = $container->run(); - - /** @Then the container should start successfully */ - self::assertSame('grants-only', $started->getName()); + /** @And the port should be exposed */ + self::assertSame(3306, $started->getAddress()->getPorts()->firstExposedPort()); - /** @And the setup should include GRANT and FLUSH but no CREATE DATABASE */ + /** @And the docker run command should reflect delegated configuration */ $commandLines = $this->client->getExecutedCommandLines(); - $setupCommand = $commandLines[4]; + $runCommand = $commandLines[2]; - self::assertStringNotContainsString('CREATE DATABASE', $setupCommand); - self::assertStringContainsString('GRANT ALL PRIVILEGES', $setupCommand); - self::assertStringContainsString('FLUSH PRIVILEGES', $setupCommand); - } + self::assertStringNotContainsString('--rm', $runCommand); + self::assertStringContainsString('--volume /var/lib/mysql:/var/lib/mysql', $runCommand); + self::assertStringContainsString('--publish 3306:3306', $runCommand); + self::assertStringContainsString('TZ=America/Sao_Paulo', $runCommand); + self::assertStringContainsString('MYSQL_USER=app_user', $runCommand); + self::assertStringContainsString('MYSQL_PASSWORD=secret', $runCommand); + self::assertStringContainsString('MYSQL_DATABASE=test_adm', $runCommand); + self::assertStringContainsString('MYSQL_ROOT_PASSWORD=root', $runCommand); - public function testGetJdbcUrlUsesExposedPortWhenDifferentFromDefault(): void - { - /** @Given a running MySQL container with a non-default port */ - $started = RunningMySQLContainer::startWith( - client: $this->client, - database: 'test_adm', - hostname: 'custom-port-db', - port: 3307 + /** @And the readiness probe should execute env-prefixed mysqladmin ping via docker exec */ + $readinessCommand = $commandLines[5]; + + self::assertStringContainsString( + 'docker exec test-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', + $readinessCommand ); - /** @When getting the JDBC URL */ - $jdbcUrl = $started->getJdbcUrl(options: []); + /** @And the database setup should include CREATE DATABASE, GRANT, and FLUSH */ + $setupCommand = $commandLines[6]; - /** @Then the URL should use the exposed port 3307 instead of the default 3306 */ - self::assertSame('jdbc:mysql://custom-port-db:3307/test_adm', $jdbcUrl); + self::assertStringContainsString('CREATE DATABASE IF NOT EXISTS `test_adm`', $setupCommand); + self::assertStringContainsString('GRANT ALL PRIVILEGES', $setupCommand); + self::assertStringContainsString('FLUSH PRIVILEGES', $setupCommand); + + /** @And the GRANT statements should include both default hosts */ + self::assertStringContainsString("'root'@'%'", $setupCommand); + self::assertStringContainsString("'root'@'172.%'", $setupCommand); } - public function testRunIfNotExistsWhenContainerExistsThenStartedWasReused(): void + public function testWithGrantedHostsThenLeavesTheOriginalDefinitionUntouched(): void { - /** @Given a MySQL container that already exists */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'reused-db') + /** @Given a MySQL container without granted hosts */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'plain-db') ->withRootPassword(rootPassword: 'root'); - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); + /** @And a copy of it granting root access from any host */ + $container->withGrantedHosts(); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the Docker inspect returns the container details */ + /** @And the inspect response carries the MySQL settings */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'reused-db', + hostname: 'plain-db', environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @When runIfNotExists is called */ - $started = $container->runIfNotExists(); + /** @When the original definition runs */ + $container->run(); - /** @Then the started container should report that it was reused */ - self::assertTrue($started->wasReused()); + /** @Then no grant should have been issued */ + self::assertStringNotContainsString('GRANT', implode(PHP_EOL, $this->client->getExecutedCommandLines())); } - public function testRunWhenEphemeralStorageThenDataDirectoryIsATmpfsMount(): void + public function testRunWhenDatabaseSetupFailsThenDockerCommandExecutionFailed(): void { - /** @Given a MySQL container with ephemeral storage */ + /** @Given a MySQL container with a database to create */ $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) - ->withName(name: 'ephemeral-db') - ->withRootPassword(rootPassword: 'root') - ->withEphemeralStorage(); + ->withName(name: 'setup-fails') + ->withDatabase(database: 'test_db') + ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the database and the root password */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'ephemeral-db', - environment: ['MYSQL_ROOT_PASSWORD=root'] + hostname: 'setup-fails', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] ) ); /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @When the MySQL container is started */ - $container->run(); + /** @And the database setup is rejected by MySQL */ + $this->client->withDockerExecuteResponse(output: 'ERROR 1064 (42000): syntax error', isSuccessful: false); - /** @Then the MySQL data directory should be a tmpfs mount */ - self::assertStringContainsString('--tmpfs /var/lib/mysql', $this->client->getExecutedCommandLines()[0]); + /** @Then the failure should name the setup command and carry the error reported by MySQL */ + $this->expectException(DockerCommandExecutionFailed::class); + $this->expectExceptionMessageMatches( + '/.*' + . 'Reason: ERROR 1064 \(42000\): syntax error$/' + ); + + /** @When the container is started */ + $container->run(); } - public function testExceptionWhenMySQLReadinessCheckAlwaysThrowsExceptions(): void + public function testRunWhenReadinessCheckAlwaysThrowsThenContainerWaitTimeout(): void { /** @Given a MySQL container with a very short readiness timeout */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) @@ -773,8 +595,10 @@ public function testExceptionWhenMySQLReadinessCheckAlwaysThrowsExceptions(): vo ->withRootPassword(rootPassword: 'root') ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); - /** @And the Docker daemon starts the container */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'crash-db', @@ -796,192 +620,255 @@ public function testExceptionWhenMySQLReadinessCheckAlwaysThrowsExceptions(): vo $container->run(); } - public function testRunMySQLContainerRetriesReadinessCheckBeforeSucceeding(): void + public function testGetAddressWhenMySQLIsStartedThenReturnsTheContainerAddress(): void { - /** @Given a MySQL container */ + /** @Given a running MySQL container */ + $started = RunningMySQLContainer::startWith( + client: $this->client, + database: 'test_adm', + hostname: 'address-db', + port: 3306 + ); + + /** @When getting the container address */ + $address = $started->getAddress(); + + /** @Then the address should delegate correctly */ + self::assertSame('address-db', $address->getHostname()); + self::assertSame('172.22.0.2', $address->getIp()); + self::assertSame(3306, $address->getPorts()->firstExposedPort()); + self::assertSame([3306], $address->getPorts()->exposedPorts()); + } + + public function testRunIfNotExistsWhenContainerIsNewThenWaitsUntilMySQLIsReady(): void + { + /** @Given a MySQL container that does not exist yet */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'booting-db') + ->withDatabase(database: 'booting_db') + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the MySQL settings */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'booting-db', + environment: ['MYSQL_DATABASE=booting_db', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And MySQL accepts connections only on the second ping */ + $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + + /** @When runIfNotExists is called */ + $container->runIfNotExists(); + + /** @Then MySQL should have been pinged until ready, and only then the database set up */ + self::assertSame( + [ + 'docker exec booting-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', + 'docker exec booting-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', + implode(' ', [ + 'docker exec booting-db env MYSQL_PWD=root mysql -uroot -e', + 'CREATE DATABASE IF NOT EXISTS `booting_db`; FLUSH PRIVILEGES;' + ]) + ], + array_values( + array_filter( + $this->client->getExecutedCommandLines(), + static fn(string $commandLine): bool => str_starts_with($commandLine, 'docker exec') + ) + ) + ); + } + + public function testRunWhenNoGrantedHostsAreConfiguredThenMySQLContainerStarts(): void + { + /** @Given a MySQL container without granted hosts */ $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'retry-db') + ->withName(name: 'no-grants') ->withDatabase(database: 'test_db') - ->withRootPassword(rootPassword: 'root') - ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 10)); + ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon starts the container */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'retry-db', + hostname: 'no-grants', environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness check fails twice before succeeding */ - $this->client->withDockerExecuteResponse(output: 'not ready', isSuccessful: false); - $this->client->withDockerExecuteResponse(output: 'not ready', isSuccessful: false); + /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @And the CREATE DATABASE command succeeds */ + /** @And the database setup succeeds */ $this->client->withDockerExecuteResponse(output: ''); - /** @When the MySQL container is started */ - $started = $container->run(); + /** @When the MySQL container is started (no GRANT PRIVILEGES should be called) */ + $started = $container->run(); + + /** @Then the container should start without errors */ + self::assertSame('no-grants', $started->getName()); + + /** @And the setup should include CREATE DATABASE but no GRANT statements */ + $commandLines = $this->client->getExecutedCommandLines(); + $setupCommand = $commandLines[4]; - /** @Then the container should start after retries */ - self::assertSame('retry-db', $started->getName()); + self::assertStringContainsString('CREATE DATABASE IF NOT EXISTS `test_db`', $setupCommand); + self::assertStringNotContainsString('GRANT ALL PRIVILEGES', $setupCommand); } - public function testRunWhenEphemeralStorageThenServerStartsWithoutBinaryLog(): void + public function testRunWhenReadinessTimeoutIsNotGivenThenWaitsUpToSixtySeconds(): void { - /** @Given a MySQL container with ephemeral storage */ + /** @Given a MySQL container with the default readiness timeout */ $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) - ->withName(name: 'fast-db') - ->withRootPassword(rootPassword: 'root') - ->withEphemeralStorage(); + ->withName(name: 'default-readiness') + ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the root password */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'fast-db', + hostname: 'default-readiness', environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness check succeeds */ - $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + /** @And the MySQL readiness check always fails */ + for ($index = 0; $index < 300; $index++) { + $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + } - /** @When the MySQL container is started */ + /** @Then a timeout exception carrying the default sixty seconds should be thrown */ + $this->expectException(ContainerWaitTimeout::class); + $this->expectExceptionMessage('Container readiness check timed out after <60> seconds.'); + + /** @When the container is started */ $container->run(); + } - /** @Then the MySQL server should start without the binary log */ - self::assertSame( - ['mysql:8.4', '--skip-log-bin'], - array_slice($this->client->getExecutedArguments()[0], -2) + public function testGetJdbcUrlWhenMySQLContainerIsSharedThenPointsToItsDatabase(): void + { + /** @Given a MySQL container reused from another process */ + $started = SharedMySQLContainer::reusedWith( + client: $this->client, + database: 'shared_adm', + hostname: 'shared-db' ); + + /** @When getting the JDBC URL */ + $jdbcUrl = $started->getJdbcUrl(options: []); + + /** @Then the URL should point to the database of the shared container */ + self::assertSame('jdbc:mysql://shared-db:3306/shared_adm', $jdbcUrl); } - public function testWithGrantedHostsThenLeavesTheOriginalDefinitionUntouched(): void + public function testRunWhenPullTimeoutIsGivenThenContainerCreationIsBoundedByIt(): void { - /** @Given a MySQL container without granted hosts */ + /** @Given a MySQL container whose image may take up to ten minutes to pull */ $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) - ->withName(name: 'plain-db') + ->withName(name: 'slow-pull-db') + ->withPullTimeout(timeout: Duration::fromSeconds(seconds: 600)) ->withRootPassword(rootPassword: 'root'); - /** @And a copy of it granting root access from any host */ - $container->withGrantedHosts(); - /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the inspect response carries the MySQL settings */ + /** @And the inspect response carries the root password */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'plain-db', + hostname: 'slow-pull-db', environment: ['MYSQL_ROOT_PASSWORD=root'] ) ); - /** @When the original definition runs */ + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @When the container is started */ $container->run(); - /** @Then no grant should have been issued */ - self::assertStringNotContainsString('GRANT', implode(PHP_EOL, $this->client->getExecutedCommandLines())); + /** @Then the creation of the container should be bounded by the given pull timeout */ + self::assertSame([600], $this->client->getRequestedTimeouts()); } - public function testRunMySQLContainerRetriesWhenReadinessCheckThrowsException(): void + public function testRunWhenDatabaseNameCarriesABacktickThenItIsEscapedInTheSetup(): void { - /** @Given a MySQL container */ - $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) - ->withName(name: 'exception-db') - ->withDatabase(database: 'test_db') - ->withRootPassword(rootPassword: 'root') - ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 10)); + /** @Given a MySQL container whose database name carries a hyphen and a backtick */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'quoted-db') + ->withDatabase(database: 'my-data`base') + ->withRootPassword(rootPassword: 'root'); - /** @And the Docker daemon starts the container */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the database and the root password */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'exception-db', - environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'quoted-db', + environment: ['MYSQL_DATABASE=my-data`base', 'MYSQL_ROOT_PASSWORD=root'] ) ); - /** @And the MySQL readiness check throws an exception first, then succeeds */ - $this->client->withDockerExecuteException( - exception: DockerCommandExecutionFailed::from(reason: 'container not running', command: 'docker exec') - ); + /** @And the MySQL readiness check succeeds */ $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @And the CREATE DATABASE command succeeds */ - $this->client->withDockerExecuteResponse(output: ''); - - /** @When the MySQL container is started */ - $started = $container->run(); + /** @When the container is started */ + $container->run(); - /** @Then the container should start after the exception was caught and retried */ - self::assertSame('exception-db', $started->getName()); + /** @Then the database name should be quoted as an identifier, with its backtick doubled */ + self::assertSame( + 'docker exec quoted-db env MYSQL_PWD=root mysql -uroot -e ' + . 'CREATE DATABASE IF NOT EXISTS `my-data``base`; FLUSH PRIVILEGES;', + array_last($this->client->getExecutedCommandLines()) + ); } - public function testRunIfNotExistsWhenContainerIsNewThenWaitsUntilMySQLIsReady(): void + public function testRunWhenEnvironmentVariableIsGivenThenMySQLContainerExposesIt(): void { - /** @Given a MySQL container that does not exist yet */ - $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) - ->withName(name: 'booting-db') - ->withDatabase(database: 'booting_db') - ->withRootPassword(rootPassword: 'root'); - - /** @And the Docker list returns empty */ - $this->client->withDockerListResponse(output: ''); + /** @Given a MySQL container with a custom environment variable */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'env-db') + ->withRootPassword(rootPassword: 'root') + ->withEnvironmentVariable(key: 'CUSTOM_KEY', value: 'custom_value'); /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); - /** @And the inspect response carries the MySQL settings */ + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( - hostname: 'booting-db', - environment: ['MYSQL_DATABASE=booting_db', 'MYSQL_ROOT_PASSWORD=root'] + hostname: 'env-db', + environment: ['MYSQL_ROOT_PASSWORD=root', 'CUSTOM_KEY=custom_value'] ) ); - /** @And MySQL accepts connections only on the second ping */ - $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); - /** @When runIfNotExists is called */ - $container->runIfNotExists(); + /** @When the MySQL container is started */ + $started = $container->run(); - /** @Then MySQL should have been pinged until ready, and only then the database set up */ + /** @Then the custom environment variable should be accessible */ self::assertSame( - [ - 'docker exec booting-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', - 'docker exec booting-db env MYSQL_PWD=root mysqladmin ping -h 127.0.0.1', - implode(' ', [ - 'docker exec booting-db env MYSQL_PWD=root mysql -uroot -e', - 'CREATE DATABASE IF NOT EXISTS booting_db; FLUSH PRIVILEGES;' - ]) - ], - array_values( - array_filter( - $this->client->getExecutedCommandLines(), - static fn(string $commandLine): bool => str_starts_with($commandLine, 'docker exec') - ) + 'custom_value', + $started->getEnvironmentVariables()->getValueBy( + key: 'CUSTOM_KEY' ) ); - } - - public function testGetJdbcUrlWhenMySQLContainerIsSharedThenPointsToItsDatabase(): void - { - /** @Given a MySQL container reused from another process */ - $started = SharedMySQLContainer::reusedWith( - client: $this->client, - database: 'shared_adm', - hostname: 'shared-db' - ); - /** @When getting the JDBC URL */ - $jdbcUrl = $started->getJdbcUrl(options: []); + /** @And the docker run command should include the custom environment variable */ + $runCommand = $this->client->getExecutedCommandLines()[0]; - /** @Then the URL should point to the database of the shared container */ - self::assertSame('jdbc:mysql://shared-db:3306/shared_adm', $jdbcUrl); + self::assertStringContainsString('CUSTOM_KEY=custom_value', $runCommand); } public function testExecuteAfterStartedWhenMySQLContainerIsSharedThenRunsInsideIt(): void @@ -1010,11 +897,8 @@ public function testRunIfNotExistsWhenContainerIsReusedThenWaitsUntilMySQLIsRead ->withName(name: 'shared-db') ->withRootPassword(rootPassword: 'root'); - /** @And the Docker list returns the existing container ID */ - $this->client->withDockerListResponse(output: InspectResponseFixture::containerId()); - /** @And the inspect response carries the MySQL settings */ - $this->client->withDockerInspectResponse( + $this->client->withDockerLookupResponse( inspectResult: InspectResponseFixture::build( hostname: 'shared-db', environment: ['MYSQL_ROOT_PASSWORD=root'] @@ -1039,6 +923,71 @@ public function testRunIfNotExistsWhenContainerIsReusedThenWaitsUntilMySQLIsRead ); } + public function testRunIfNotExistsWhenMySQLContainerIsMissingThenANewOneIsStarted(): void + { + /** @Given a MySQL container that does not exist */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'new-db') + ->withDatabase(database: 'new_db') + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'new-db', + environment: ['MYSQL_DATABASE=new_db', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @And the database setup succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then a new container should be created */ + self::assertSame('new-db', $started->getName()); + } + + public function testRunWhenASingleGrantedHostIsConfiguredThenMySQLContainerStarts(): void + { + /** @Given a MySQL container with a single granted host */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'single-grant') + ->withDatabase(database: 'test_db') + ->withGrantedHosts(hosts: ['%']) + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'single-grant', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @And the database setup succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the container should start successfully */ + self::assertSame('single-grant', $started->getName()); + } + public function testStopWhenMySQLContainerIsSharedThenStopsTheUnderlyingContainer(): void { /** @Given a MySQL container reused from another process */ @@ -1058,6 +1007,31 @@ public function testStopWhenMySQLContainerIsSharedThenStopsTheUnderlyingContaine ); } + public function testGetJdbcUrlWhenOptionsAreOmittedThenUrlCarriesTheDefaultOptions(): void + { + /** @Given a running MySQL container */ + $started = RunningMySQLContainer::startWith( + client: $this->client, + database: 'test_adm', + hostname: 'test-db', + port: 3306 + ); + + /** @When getting the JDBC URL with default options */ + $jdbcUrl = $started->getJdbcUrl(); + + /** @Then the URL should include default JDBC options */ + $options = implode('&', [ + 'useSSL=false', + 'useUnicode=yes', + 'characterEncoding=UTF-8', + 'allowPublicKeyRetrieval=true' + ]); + $template = 'jdbc:mysql://test-db:3306/test_adm?%s'; + + self::assertSame(sprintf($template, $options), $jdbcUrl); + } + public function testRunWhenGrantedHostsAndEphemeralStorageThenGrantsAreStillApplied(): void { /** @Given a MySQL container with granted hosts, then ephemeral storage */ @@ -1067,8 +1041,10 @@ public function testRunWhenGrantedHostsAndEphemeralStorageThenGrantsAreStillAppl ->withRootPassword(rootPassword: 'root') ->withEphemeralStorage(); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'grants-kept-db', @@ -1082,11 +1058,32 @@ public function testRunWhenGrantedHostsAndEphemeralStorageThenGrantsAreStillAppl /** @When the MySQL container is started */ $container->run(); - /** @Then the granted host should still be created */ - self::assertStringContainsString( - "CREATE USER IF NOT EXISTS 'root'@'10.%'", - array_last($this->client->getExecutedCommandLines()) - ); + /** @Then the granted host should still be created */ + self::assertStringContainsString( + "CREATE USER IF NOT EXISTS 'root'@'10.%'", + array_last($this->client->getExecutedCommandLines()) + ); + } + + public function testExecuteAfterStartedWhenMySQLIsStartedThenReturnsTheCommandOutput(): void + { + /** @Given a running MySQL container */ + $started = RunningMySQLContainer::startWith( + client: $this->client, + database: 'test_adm', + hostname: 'exec-db', + port: 3306 + ); + + /** @And a command execution returns output */ + $this->client->withDockerExecuteResponse(output: 'SHOW DATABASES output'); + + /** @When commands are executed inside the container */ + $execution = $started->executeAfterStarted(commands: ['mysql', '-e', 'SHOW DATABASES']); + + /** @Then the execution should return the output */ + self::assertTrue($execution->isSuccessful()); + self::assertSame('SHOW DATABASES output', $execution->getOutput()); } public function testRunIfNotExistsWhenMySQLNeverBecomesReadyThenContainerWaitTimeout(): void @@ -1097,9 +1094,6 @@ public function testRunIfNotExistsWhenMySQLNeverBecomesReadyThenContainerWaitTim ->withRootPassword(rootPassword: 'root') ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); - /** @And the Docker list returns empty */ - $this->client->withDockerListResponse(output: ''); - /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); @@ -1124,6 +1118,80 @@ public function testRunIfNotExistsWhenMySQLNeverBecomesReadyThenContainerWaitTim $container->runIfNotExists(); } + public function testStopOnShutdownWhenMySQLIsStartedThenRegistersOneShutdownCallback(): void + { + /** @Given shutdown callbacks are captured instead of being registered */ + HostMock::captureShutdown(); + + /** @And a Docker client */ + $client = new ClientMock(); + + /** @And a MySQL container */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $client) + ->withName(name: 'shutdown-db') + ->withDatabase(database: 'test_adm') + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the MySQL settings */ + $client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'shutdown-db', + environment: ['MYSQL_DATABASE=test_adm', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the container is started */ + $started = $container->run(); + + /** @When stopOnShutdown is called */ + $started->stopOnShutdown(); + + /** @Then exactly one shutdown callback should have been registered */ + self::assertSame(1, HostMock::shutdownCallbackCount()); + } + + public function testRunWhenReadinessCheckFailsAtFirstThenItIsRetriedUntilMySQLIsReady(): void + { + /** @Given a MySQL container */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'retry-db') + ->withDatabase(database: 'test_db') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 10)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'retry-db', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check fails, for the first time */ + $this->client->withDockerExecuteResponse(output: 'not ready', isSuccessful: false); + + /** @And the MySQL readiness check fails, for the second time */ + $this->client->withDockerExecuteResponse(output: 'not ready', isSuccessful: false); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @And the CREATE DATABASE command succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + + /** @When the MySQL container is started */ + $started = $container->run(); + + /** @Then the container should start after retries */ + self::assertSame('retry-db', $started->getName()); + } + public function testRunIfNotExistsWhenEphemeralStorageThenServerStartsWithoutBinaryLog(): void { /** @Given a MySQL container with ephemeral storage that does not exist yet */ @@ -1132,11 +1200,10 @@ public function testRunIfNotExistsWhenEphemeralStorageThenServerStartsWithoutBin ->withRootPassword(rootPassword: 'root') ->withEphemeralStorage(); - /** @And the Docker list returns empty (container does not exist) */ - $this->client->withDockerListResponse(output: ''); - - /** @And the Docker daemon returns valid run and inspect responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'shared-fast-db', @@ -1157,19 +1224,98 @@ public function testRunIfNotExistsWhenEphemeralStorageThenServerStartsWithoutBin ); } + public function testRunWhenReadinessCheckThrowsAtFirstThenItIsRetriedUntilMySQLIsReady(): void + { + /** @Given a MySQL container */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'exception-db') + ->withDatabase(database: 'test_db') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 10)); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'exception-db', + environment: ['MYSQL_DATABASE=test_db', 'MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check throws */ + $this->client->withDockerExecuteException( + exception: DockerCommandExecutionFailed::from(reason: 'container not running', command: 'docker exec') + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @And the CREATE DATABASE command succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + + /** @When the MySQL container is started */ + $started = $container->run(); + + /** @Then the container should start after the exception was caught and retried */ + self::assertSame('exception-db', $started->getName()); + } + + public function testRunWhenWaitBeforeRunIsRegisteredThenItIsEvaluatedBeforeMySQLStarts(): void + { + /** @Given a MySQL container with a wait-before-run condition */ + $condition = $this->createMock(ContainerReady::class); + + /** @And the condition holds on its only check */ + $condition->expects(self::once())->method('isReady')->willReturn(true); + + /** @And the container is configured */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'wait-db') + ->withRootPassword(rootPassword: 'root') + ->withWaitBeforeRun( + wait: ContainerWaitForDependency::untilReady(condition: $condition) + ); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'wait-db', + environment: ['MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @When the container is started */ + $started = $container->run(); + + /** @Then the wait-before-run condition should have been evaluated */ + self::assertSame('wait-db', $started->getName()); + } + public function testRunWhenEphemeralStorageAndGrantedHostsThenServerStillSkipsBinaryLog(): void { - /** @Given a MySQL container with ephemeral storage, then granted hosts and a readiness timeout */ + /** @Given a MySQL container with ephemeral storage */ $ephemeral = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) ->withName(name: 'granted-fast-db') ->withRootPassword(rootPassword: 'root') ->withEphemeralStorage(); + + /** @And granted hosts and a readiness timeout applied after the ephemeral storage */ $container = $ephemeral ->withGrantedHosts(hosts: ['%']) ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 5)); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'granted-fast-db', @@ -1192,15 +1338,19 @@ public function testRunWhenEphemeralStorageAndGrantedHostsThenServerStillSkipsBi public function testRunWhenReadinessTimeoutAndEphemeralStorageThenTimeoutIsStillApplied(): void { - /** @Given a MySQL container with a short readiness timeout, then ephemeral storage */ + /** @Given a MySQL container with a short readiness timeout */ $timed = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) ->withName(name: 'timeout-kept-db') ->withRootPassword(rootPassword: 'root') ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); + + /** @And ephemeral storage applied after the readiness timeout */ $container = $timed->withEphemeralStorage(); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'timeout-kept-db', @@ -1221,6 +1371,39 @@ public function testRunWhenReadinessTimeoutAndEphemeralStorageThenTimeoutIsStill $container->run(); } + public function testRunIfNotExistsWhenMySQLNeverBecomesReadyThenTheSharedContainerIsKept(): void + { + /** @Given a shared MySQL container with a readiness timeout of one second */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'shared-never-ready') + ->withRootPassword(rootPassword: 'root') + ->withReadinessTimeout(timeout: Duration::fromSeconds(seconds: 1)); + + /** @And the lookup finds the container another process started */ + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'shared-never-ready', + environment: ['MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check always fails */ + for ($index = 0; $index < 10; $index++) { + $this->client->withDockerExecuteResponse(output: 'mysqld is not ready', isSuccessful: false); + } + + try { + /** @When the container is asked for */ + $container->runIfNotExists(); + } catch (ContainerWaitTimeout) { + /** @Then the shared container should not be removed */ + self::assertNotContains( + sprintf('docker rm --force --volumes %s', InspectResponseFixture::shortContainerId()), + $this->client->getExecutedCommandLines() + ); + } + } + public function testRunWhenEphemeralStorageAndCommandsThenServerArgumentsFollowTheCommands(): void { /** @Given a MySQL container with ephemeral storage */ @@ -1229,8 +1412,10 @@ public function testRunWhenEphemeralStorageAndCommandsThenServerArgumentsFollowT ->withRootPassword(rootPassword: 'root') ->withEphemeralStorage(); - /** @And the Docker daemon returns valid responses */ + /** @And the Docker daemon creates the container */ $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ $this->client->withDockerInspectResponse( inspectResult: InspectResponseFixture::build( hostname: 'command-db', @@ -1251,6 +1436,46 @@ public function testRunWhenEphemeralStorageAndCommandsThenServerArgumentsFollowT ); } + public function testRunWhenGrantedHostsAreConfiguredWithoutDatabaseThenMySQLContainerStarts(): void + { + /** @Given a MySQL container with granted hosts but no database */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'grants-only') + ->withGrantedHosts(hosts: ['%']) + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries the container details */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'grants-only', + environment: ['MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @And the database setup succeeds */ + $this->client->withDockerExecuteResponse(output: ''); + + /** @When the MySQL container is started */ + $started = $container->run(); + + /** @Then the container should start successfully */ + self::assertSame('grants-only', $started->getName()); + + /** @And the setup should include GRANT and FLUSH but no CREATE DATABASE */ + $commandLines = $this->client->getExecutedCommandLines(); + $setupCommand = $commandLines[4]; + + self::assertStringNotContainsString('CREATE DATABASE', $setupCommand); + self::assertStringContainsString('GRANT ALL PRIVILEGES', $setupCommand); + self::assertStringContainsString('FLUSH PRIVILEGES', $setupCommand); + } + public function testGetAddressWhenMySQLContainerIsSharedThenIsTheAddressOfTheExistingContainer(): void { /** @Given a MySQL container reused from another process */ @@ -1268,4 +1493,61 @@ public function testGetAddressWhenMySQLContainerIsSharedThenIsTheAddressOfTheExi self::assertSame(InspectResponseFixture::shortContainerId(), $started->getId()); self::assertSame('shared_adm', $started->getEnvironmentVariables()->getValueBy(key: 'MYSQL_DATABASE')); } + + public function testRunIfNotExistsWhenMySQLContainerExistsThenReturnsItAsMySQLContainerStarted(): void + { + /** @Given a MySQL container */ + $container = MySQLDockerContainer::from(image: 'mysql:8.1', client: $this->client) + ->withName(name: 'existing-db') + ->withDatabase(database: 'my_db') + ->withRootPassword(rootPassword: 'root'); + + $this->client->withDockerLookupResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'existing-db', + environment: ['MYSQL_DATABASE=my_db', 'MYSQL_ROOT_PASSWORD=root'], + exposedPorts: ['3306/tcp' => (object)[]] + ) + ); + + /** @When runIfNotExists is called */ + $started = $container->runIfNotExists(); + + /** @Then it should return a MySQLContainerStarted wrapping the existing container */ + self::assertSame('existing-db', $started->getName()); + } + + public function testRunWhenNeitherDatabaseNorGrantedHostsAreConfiguredThenNoSetupCommandIsIssued(): void + { + /** @Given a MySQL container without a database and without granted hosts */ + $container = MySQLDockerContainer::from(image: 'mysql:8.4', client: $this->client) + ->withName(name: 'no-setup') + ->withRootPassword(rootPassword: 'root'); + + /** @And the Docker daemon creates the container */ + $this->client->withDockerCreateResponse(output: InspectResponseFixture::containerId()); + + /** @And the inspect response carries only the root password */ + $this->client->withDockerInspectResponse( + inspectResult: InspectResponseFixture::build( + hostname: 'no-setup', + environment: ['MYSQL_ROOT_PASSWORD=root'] + ) + ); + + /** @And the MySQL readiness check succeeds */ + $this->client->withDockerExecuteResponse(output: 'mysqld is alive'); + + /** @When the container is started */ + $container->run(); + + /** @Then the readiness check should be the only command executed inside the container */ + self::assertCount( + 1, + array_filter( + $this->client->getExecutedCommandLines(), + static fn(string $commandLine): bool => str_starts_with($commandLine, 'docker exec') + ) + ); + } } diff --git a/tests/Unit/SharedMySQLContainer.php b/tests/Unit/SharedMySQLContainer.php index 5416d41..8e7dd17 100644 --- a/tests/Unit/SharedMySQLContainer.php +++ b/tests/Unit/SharedMySQLContainer.php @@ -27,8 +27,7 @@ public static function reusedWith( $databaseTemplate = 'MYSQL_DATABASE=%s'; - $client->withDockerListResponse(output: InspectResponseFixture::containerId()); - $client->withDockerInspectResponse( + $client->withDockerLookupResponse( inspectResult: InspectResponseFixture::build( hostname: $hostname, environment: [ diff --git a/tests/Unit/Waits/ContainerWaitForDependencyTest.php b/tests/Unit/Waits/ContainerWaitForDependencyTest.php index d3081ac..75b3943 100644 --- a/tests/Unit/Waits/ContainerWaitForDependencyTest.php +++ b/tests/Unit/Waits/ContainerWaitForDependencyTest.php @@ -5,6 +5,7 @@ namespace Test\Unit\Waits; use PHPUnit\Framework\TestCase; +use Test\Unit\ClockMock; use TinyBlocks\DockerContainer\Exceptions\ContainerWaitTimeout; use TinyBlocks\DockerContainer\Waits\Conditions\ContainerReady; use TinyBlocks\DockerContainer\Waits\ContainerWaitForDependency; @@ -12,71 +13,115 @@ final class ContainerWaitForDependencyTest extends TestCase { + protected function setUp(): void + { + ClockMock::freeze(); + } + + protected function tearDown(): void + { + ClockMock::release(); + } + public function testWaitBeforeWhenTimeoutIsZeroThenChecksTheConditionOnce(): void { /** @Given a condition that is immediately ready */ $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should still be checked once */ $condition->expects(self::once())->method('isReady')->willReturn(true); /** @When waiting with a zero timeout */ ContainerWaitForDependency::untilReady(condition: $condition) ->withTimeout(timeout: Duration::zero()) ->waitBefore(); - - /** @Then the condition should still have been checked once */ - self::assertTrue(true); } public function testWaitBeforeWhenConditionHoldsLaterThenChecksUntilItHolds(): void { /** @Given a condition that becomes ready on the third check */ $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should be checked three times */ $condition->expects(self::exactly(3)) ->method('isReady') ->willReturnOnConsecutiveCalls(false, false, true); /** @When waiting for the dependency within the default timeout */ ContainerWaitForDependency::untilReady(condition: $condition)->waitBefore(); - - /** @Then the condition should have been checked three times */ - self::assertTrue(true); } public function testWaitBeforeWhenConditionIsImmediatelyReadyThenChecksOnce(): void { /** @Given a condition that is immediately ready */ $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should be checked exactly once */ $condition->expects(self::once())->method('isReady')->willReturn(true); /** @When waiting for the dependency */ ContainerWaitForDependency::untilReady(condition: $condition)->waitBefore(); + } + + public function testWaitBeforeWhenDeadlineIsReachedExactlyThenStopsChecking(): void + { + /** @Given a condition whose first check ends exactly at the deadline, once the sleep is added */ + $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should not be checked again */ + $condition->expects(self::once())->method('isReady')->willReturnCallback( + static function (): bool { + ClockMock::advanceBy(nanoseconds: 750_000_000); + + return false; + } + ); + + /** @And a timeout exception should be thrown */ + $this->expectException(ContainerWaitTimeout::class); - /** @Then the condition should have been checked exactly once */ - self::assertTrue(true); + /** @When waiting for the dependency for one second */ + ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) + ->waitBefore(); } public function testWaitBeforeWhenConditionHoldsLaterThenSleepsBetweenChecks(): void { - /** @Given the moment the wait starts */ - $start = microtime(true); + /** @Given a condition that becomes ready on the third check */ + $condition = $this->createStub(ContainerReady::class); - /** @And a condition that holds only after the first poll interval has elapsed */ + /** @And the condition fails twice before it holds */ + $condition->method('isReady')->willReturnOnConsecutiveCalls(false, false, true); + + /** @When waiting for the dependency */ + ContainerWaitForDependency::untilReady(condition: $condition)->waitBefore(); + + /** @Then a quarter of a second should have been slept after each failed check */ + self::assertSame(0.5, ClockMock::elapsedInSeconds()); + } + + public function testWaitBeforeWhenConditionIsImmediatelyReadyThenDoesNotSleep(): void + { + /** @Given a condition that is immediately ready */ $condition = $this->createStub(ContainerReady::class); - $condition->method('isReady')->willReturnCallback( - static fn(): bool => (microtime(true) - $start) >= 0.2 - ); + + /** @And the condition reports readiness on its first check */ + $condition->method('isReady')->willReturn(true); /** @When waiting for the dependency */ ContainerWaitForDependency::untilReady(condition: $condition)->waitBefore(); - /** @Then the wait should have slept a full poll interval before observing readiness */ - self::assertGreaterThanOrEqual(0.25, (microtime(true) - $start)); + /** @Then no time should have been spent waiting */ + self::assertSame(0.0, ClockMock::elapsedInSeconds()); } public function testWaitBeforeWhenConditionNeverHoldsThenContainerWaitTimeout(): void { /** @Given a condition that never becomes ready */ $condition = $this->createStub(ContainerReady::class); + + /** @And the condition fails on every check */ $condition->method('isReady')->willReturn(false); /** @And a wait bounded by one second */ @@ -91,27 +136,96 @@ public function testWaitBeforeWhenConditionNeverHoldsThenContainerWaitTimeout(): $wait->waitBefore(); } + public function testWaitBeforeWhenConditionNeverHoldsThenWaitsExactlyTheTimeout(): void + { + /** @Given a condition that never becomes ready */ + $condition = $this->createStub(ContainerReady::class); + + /** @And the condition fails on every check */ + $condition->method('isReady')->willReturn(false); + + /** @And a wait bounded by two seconds */ + $wait = ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 2)); + + try { + /** @When waiting for the dependency */ + $wait->waitBefore(); + } catch (ContainerWaitTimeout) { + /** @Then exactly two seconds should have been spent waiting */ + self::assertSame(2.0, ClockMock::elapsedInSeconds()); + } + } + public function testWaitBeforeWhenConditionNeverHoldsThenChecksEveryQuarterSecond(): void { /** @Given a condition that never becomes ready and counts its checks */ $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should be checked four times, once per quarter of the second */ $condition->expects(self::exactly(4))->method('isReady')->willReturn(false); - /** @And a wait bounded by one second */ - $wait = ContainerWaitForDependency::untilReady(condition: $condition) - ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)); + /** @And a timeout exception should be thrown */ + $this->expectException(ContainerWaitTimeout::class); + + /** @When waiting for the dependency for one second */ + ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) + ->waitBefore(); + } + + public function testWaitBeforeWhenOneNanosecondRemainsThenChecksTheConditionAgain(): void + { + /** @Given a condition whose first check ends one nanosecond before the deadline, once the sleep is added */ + $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should be checked a second time */ + $condition->expects(self::exactly(2))->method('isReady')->willReturnCallback( + static function (): bool { + ClockMock::advanceBy(nanoseconds: 749_999_999); - /** @Then a timeout exception should be thrown once the four checks of the second are spent */ + return false; + } + ); + + /** @And a timeout exception should be thrown */ $this->expectException(ContainerWaitTimeout::class); - /** @When waiting for the dependency */ - $wait->waitBefore(); + /** @When waiting for the dependency for one second */ + ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) + ->waitBefore(); + } + + public function testWaitBeforeWhenChecksAreSlowThenTheirDurationCountsTowardTheTimeout(): void + { + /** @Given a condition that takes half a second to answer and never becomes ready */ + $condition = $this->createMock(ContainerReady::class); + + /** @Then the condition should be checked only twice within the second */ + $condition->expects(self::exactly(2))->method('isReady')->willReturnCallback( + static function (): bool { + ClockMock::advanceBy(nanoseconds: 500_000_000); + + return false; + } + ); + + /** @And a timeout exception should be thrown */ + $this->expectException(ContainerWaitTimeout::class); + + /** @When waiting for the dependency for one second */ + ContainerWaitForDependency::untilReady(condition: $condition) + ->withTimeout(timeout: Duration::fromSeconds(seconds: 1)) + ->waitBefore(); } public function testWaitBeforeWhenTimeoutIsZeroAndConditionFailsThenContainerWaitTimeout(): void { /** @Given a condition that becomes ready only on the second check */ $condition = $this->createStub(ContainerReady::class); + + /** @And the condition fails its first check */ $condition->method('isReady')->willReturnOnConsecutiveCalls(false, true); /** @And a wait with a zero timeout, which allows a single check */ diff --git a/tests/Unit/Waits/ContainerWaitForTimeTest.php b/tests/Unit/Waits/ContainerWaitForTimeTest.php index 2ece2f0..c721969 100644 --- a/tests/Unit/Waits/ContainerWaitForTimeTest.php +++ b/tests/Unit/Waits/ContainerWaitForTimeTest.php @@ -5,54 +5,56 @@ namespace Test\Unit\Waits; use PHPUnit\Framework\TestCase; +use Test\Unit\ClockMock; use TinyBlocks\DockerContainer\ContainerStarted; use TinyBlocks\DockerContainer\Waits\ContainerWaitForTime; use TinyBlocks\Time\Duration; final class ContainerWaitForTimeTest extends TestCase { - public function testWaitAfterPausesForSpecifiedDuration(): void + protected function setUp(): void { - /** @Given a wait-for-time of 1 second */ - $wait = ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 1)); - - /** @And the moment the wait starts */ - $start = microtime(true); - - /** @When waiting after a container started */ - $wait->waitAfter(containerStarted: $this->createStub(ContainerStarted::class)); - - /** @Then at least 0.9 seconds should have elapsed */ - self::assertGreaterThanOrEqual(0.9, (microtime(true) - $start)); + ClockMock::freeze(); } - public function testWaitBeforePausesForSpecifiedDuration(): void + protected function tearDown(): void { - /** @Given a wait-for-time of 1 second */ - $wait = ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 1)); + ClockMock::release(); + } - /** @And the moment the wait starts */ - $start = microtime(true); + public function testWaitBeforeWhenDurationIsZeroThenReturnsAtOnce(): void + { + /** @Given a wait-for-time of zero */ + $wait = ContainerWaitForTime::forDuration(duration: Duration::zero()); /** @When waiting before a container runs */ $wait->waitBefore(); - /** @Then at least 0.9 seconds should have elapsed */ - self::assertGreaterThanOrEqual(0.9, (microtime(true) - $start)); + /** @Then no time should have been spent waiting */ + self::assertSame(0.0, ClockMock::elapsedInSeconds()); } - public function testWaitForZeroSecondsReturnsImmediately(): void + public function testWaitAfterWhenDurationIsGivenThenPausesForThatDuration(): void { - /** @Given a wait-for-time of zero */ - $wait = ContainerWaitForTime::forDuration(duration: Duration::zero()); + /** @Given a wait-for-time of three seconds */ + $wait = ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 3)); + + /** @When waiting after a container started */ + $wait->waitAfter(containerStarted: $this->createStub(ContainerStarted::class)); + + /** @Then exactly three seconds should have been spent waiting */ + self::assertSame(3.0, ClockMock::elapsedInSeconds()); + } - /** @And the moment the wait starts */ - $start = microtime(true); + public function testWaitBeforeWhenDurationIsGivenThenPausesForThatDuration(): void + { + /** @Given a wait-for-time of three seconds */ + $wait = ContainerWaitForTime::forDuration(duration: Duration::fromSeconds(seconds: 3)); /** @When waiting before a container runs */ $wait->waitBefore(); - /** @Then the wait should return at once */ - self::assertLessThan(0.1, (microtime(true) - $start)); + /** @Then exactly three seconds should have been spent waiting */ + self::assertSame(3.0, ClockMock::elapsedInSeconds()); } } diff --git a/tests/Unit/Waits/Overrides/clock.php b/tests/Unit/Waits/Overrides/clock.php new file mode 100644 index 0000000..69d9adc --- /dev/null +++ b/tests/Unit/Waits/Overrides/clock.php @@ -0,0 +1,30 @@ +