From 66262689a572a602d0bc71760bd8c44a9de08731 Mon Sep 17 00:00:00 2001 From: roble Date: Wed, 21 Oct 2026 15:51:20 +0100 Subject: [PATCH 1/3] feat: enhance Docker environment tests and add environment helpers tests --- .../Environments/DockerEnvironmentTest.php | 28 ++- .../Environments/EnvironmentHelpersTest.php | 185 ++++++++++++++++++ tests/Feature/PublishDockerCommandTest.php | 21 ++ tests/Feature/StackCommandTest.php | 9 + tests/Unit/ModuleRegistryTest.php | 37 ++++ 5 files changed, 277 insertions(+), 3 deletions(-) create mode 100644 tests/Feature/Environments/EnvironmentHelpersTest.php diff --git a/tests/Feature/Environments/DockerEnvironmentTest.php b/tests/Feature/Environments/DockerEnvironmentTest.php index 068eec8..562ac62 100644 --- a/tests/Feature/Environments/DockerEnvironmentTest.php +++ b/tests/Feature/Environments/DockerEnvironmentTest.php @@ -1104,9 +1104,25 @@ public function test_certificate_covers_the_custom_domain_and_localhost(): void { $hosts = $this->exposed()->exposedCertificateHosts('myapp.test'); - $this->assertContains('myapp.test', $hosts); - $this->assertContains('*.myapp.test', $hosts); - $this->assertContains('localhost', $hosts); + // The loopback addresses too, so https://127.0.0.1 is trusted as well. + $this->assertSame(['myapp.test', '*.myapp.test', 'localhost', '*.localhost', '127.0.0.1', '::1'], $hosts); + } + + public function test_ports_come_from_env_and_fall_back_to_defaults_when_not_numeric(): void + { + $dir = sys_get_temp_dir().'/sb-ports-'.uniqid(); + mkdir($dir); + file_put_contents($dir.'/.env', "APP_PORT=8080\nAPP_HTTPS_PORT=nope\n"); + + try { + $ports = $this->exposed()->exposedResolvePorts(new FakeInstallCommand(null, [], ['path' => $dir])); + } finally { + exec('rm -rf '.escapeshellarg($dir)); + } + + $this->assertSame(8080, $ports['APP_PORT']); + $this->assertSame(443, $ports['APP_HTTPS_PORT']); + $this->assertSame(3306, $ports['FORWARD_DB_PORT']); } public function test_certificate_hosts_do_not_repeat_localhost(): void @@ -1339,6 +1355,12 @@ public function exposedApplyNginxSettings(string $conf, string $host, int $http, return $this->applyNginxSettings($conf, $host, $http, $https); } + /** @return array */ + public function exposedResolvePorts(InstallCommand $command): array + { + return $this->resolvePorts($command); + } + /** @return string[] */ public function exposedCertificateHosts(string $host): array { diff --git a/tests/Feature/Environments/EnvironmentHelpersTest.php b/tests/Feature/Environments/EnvironmentHelpersTest.php new file mode 100644 index 0000000..33a1b56 --- /dev/null +++ b/tests/Feature/Environments/EnvironmentHelpersTest.php @@ -0,0 +1,185 @@ +tmp = sys_get_temp_dir().'/sb-env-helpers-'.uniqid(); + mkdir($this->tmp, 0755, true); + } + + protected function tearDown(): void + { + exec('rm -rf '.escapeshellarg($this->tmp).' '.escapeshellarg($this->tmp.'-sibling')); + parent::tearDown(); + } + + public function test_an_env_value_is_read_without_its_quotes(): void + { + file_put_contents($this->tmp.'/.env', "APP_URL=\"https://shop.test\"\nDEMO_PASSWORD='s3cret'\n"); + + $this->assertSame('https://shop.test', $this->readEnv('APP_URL')); + $this->assertSame('s3cret', $this->readEnv('DEMO_PASSWORD')); + } + + /** APP_URL must not match APP_URL_PREFIX or a commented-out line. */ + public function test_an_env_value_is_matched_by_its_whole_key(): void + { + file_put_contents($this->tmp.'/.env', "APP_URL_PREFIX=/admin\n# APP_URL=http://old.test\nAPP_URL=https://shop.test\n"); + + $this->assertSame('https://shop.test', $this->readEnv('APP_URL')); + } + + public function test_a_key_with_regex_characters_is_matched_literally(): void + { + file_put_contents($this->tmp.'/.env', "AXB=wrong\nA.B=right\n"); + + $this->assertSame('right', $this->readEnv('A.B')); + } + + public function test_a_missing_env_or_key_reads_as_null(): void + { + $this->assertNull($this->readEnv('APP_URL')); + + file_put_contents($this->tmp.'/.env', "APP_NAME=Shop\n"); + + $this->assertNull($this->readEnv('APP_URL')); + } + + public function test_module_names_are_lowercased_and_empty_entries_dropped(): void + { + $this->assertSame( + ['saucebase/auth', 'saucebase/billing', 'acme/reports'], + $this->modules('Auth,, BILLING ,acme/reports,'), + ); + } + + public function test_none_selects_no_modules(): void + { + $this->assertSame([], $this->modules('none')); + } + + /** /tmp/app-sibling starts with /tmp/app but is not inside it. */ + public function test_a_sibling_sharing_the_folder_name_prefix_is_given_as_an_absolute_path(): void + { + mkdir($this->tmp.'-sibling'); + $cwd = getcwd(); + chdir($this->tmp); + + try { + $steps = $this->cdStep($this->tmp.'-sibling'); + } finally { + chdir($cwd); + } + + $this->assertSame(['cd '.realpath($this->tmp.'-sibling')], $steps); + } + + public function test_a_demo_install_tells_the_user_the_demo_password(): void + { + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + + $steps = $this->environment()->exposedDemoStep($this->command(demo: true)); + + $this->assertCount(1, $steps); + $this->assertStringContainsString('`s3cret`', $steps[0]); + } + + public function test_without_demo_content_no_password_is_shown(): void + { + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + + $this->assertSame([], $this->environment()->exposedDemoStep($this->command())); + } + + private function command(?string $modules = null, ?string $target = null, bool $demo = false): InstallCommand + { + return new class($target ?? $this->tmp, $modules, $demo) extends InstallCommand + { + public function __construct(private string $target, private ?string $modules, private bool $demo) + { + parent::__construct(); + } + + public function targetPath(): string + { + return $this->target; + } + + public function option($key = null): string|array|bool|null + { + return match ($key) { + 'modules' => $this->modules, + 'demo' => $this->demo ?: null, + default => null, + }; + } + + public function getSelectedStack(): ?string + { + return null; + } + + public function getSelectedModules(): array + { + return []; + } + }; + } + + private function environment(): NativeEnvironment + { + return new class extends NativeEnvironment + { + public function exposedReadEnvValue(InstallCommand $command, string $key): ?string + { + return $this->readEnvValue($command, $key); + } + + public function exposedResolveModules(InstallCommand $command): array + { + return $this->resolveModules($command); + } + + public function exposedDemoStep(InstallCommand $command): array + { + return $this->demoStep($command); + } + + public function exposedCdStep(InstallCommand $command): array + { + return $this->cdStep($command); + } + }; + } + + private function readEnv(string $key): ?string + { + return $this->environment()->exposedReadEnvValue($this->command(), $key); + } + + /** @return string[] */ + private function modules(string $raw): array + { + return $this->environment()->exposedResolveModules($this->command($raw)); + } + + /** @return string[] */ + private function cdStep(string $target): array + { + return $this->environment()->exposedCdStep($this->command(target: $target)); + } +} diff --git a/tests/Feature/PublishDockerCommandTest.php b/tests/Feature/PublishDockerCommandTest.php index 490fdc4..db138d7 100644 --- a/tests/Feature/PublishDockerCommandTest.php +++ b/tests/Feature/PublishDockerCommandTest.php @@ -75,6 +75,27 @@ public function test_it_keeps_existing_files_when_not_forced(): void $this->assertSame('mine', file_get_contents($this->tmp.'/docker-compose.yml')); } + public function test_a_skipped_file_does_not_stop_the_rest_from_publishing(): void + { + file_put_contents($this->tmp.'/docker-compose.yml', 'mine'); + + $this->artisan("docker:publish --path={$this->tmp}")->assertSuccessful(); + + foreach (['docker/Dockerfile', 'docker/nginx.conf', 'docker/php.ini', 'docker/xdebug.ini'] as $file) { + $this->assertFileExists($this->tmp.'/'.$file); + } + } + + public function test_without_the_ssl_option_the_ssl_nginx_config_is_kept(): void + { + $this->artisan("docker:publish --path={$this->tmp}")->assertSuccessful(); + + $this->assertSame( + file_get_contents(dirname(__DIR__, 2).'/stubs/docker/docker/nginx.conf'), + file_get_contents($this->tmp.'/docker/nginx.conf'), + ); + } + public function test_force_overwrites_existing_files(): void { file_put_contents($this->tmp.'/docker-compose.yml', 'mine'); diff --git a/tests/Feature/StackCommandTest.php b/tests/Feature/StackCommandTest.php index bbce525..3e318c3 100644 --- a/tests/Feature/StackCommandTest.php +++ b/tests/Feature/StackCommandTest.php @@ -80,6 +80,15 @@ public function test_dev_mode_writes_saucebase_json(): void $this->assertSame(['framework', 'contributor'], array_keys($data)); } + public function test_the_stack_name_is_case_insensitive(): void + { + $this->seedFakeStubs('vue'); + + $this->artisan('stack Vue --dev')->assertSuccessful(); + + $this->assertSame('vue', json_decode(file_get_contents($this->tmpDir.'/saucebase.json'), true)['framework']); + } + public function test_selecting_a_stack_keeps_the_other_settings(): void { $this->seedFakeStubs('vue'); diff --git a/tests/Unit/ModuleRegistryTest.php b/tests/Unit/ModuleRegistryTest.php index ee09e6a..0b52950 100644 --- a/tests/Unit/ModuleRegistryTest.php +++ b/tests/Unit/ModuleRegistryTest.php @@ -2,6 +2,7 @@ namespace Saucebase\Installer\Tests\Unit; +use Illuminate\Support\Facades\Http; use PHPUnit\Framework\Attributes\DataProvider; use Saucebase\Installer\ModuleRegistry; use Saucebase\Installer\Tests\TestCase; @@ -22,4 +23,40 @@ public static function labels(): array ['saucebase/auth-pro', 'Auth Pro'], ]; } + + public function test_a_local_module_names_its_frameworks_without_asking_the_network(): void + { + Http::fake(['*' => Http::response(['extra' => ['saucebase' => ['frameworks' => ['vue']]]])]); + $modules = $this->localModule('auth', ['react']); + + $this->assertSame(['react'], (new ModuleRegistry($modules))->frameworks('saucebase/auth')); + Http::assertNothingSent(); + } + + /** An empty list says nothing, so the published manifest decides. */ + public function test_a_local_module_with_an_empty_framework_list_falls_back_to_the_published_one(): void + { + Http::fake(['*' => Http::response(['extra' => ['saucebase' => ['frameworks' => ['react']]]])]); + $modules = $this->localModule('auth', []); + + $this->assertSame(['react'], (new ModuleRegistry($modules))->frameworks('saucebase/auth')); + } + + public function test_a_published_empty_framework_list_means_vue(): void + { + Http::fake(['*' => Http::response(['extra' => ['saucebase' => ['frameworks' => []]]])]); + + $this->assertSame(['vue'], (new ModuleRegistry)->frameworks('saucebase/auth')); + } + + /** @param string[] $frameworks */ + private function localModule(string $name, array $frameworks): string + { + $dir = sys_get_temp_dir().'/sb-registry-'.uniqid(); + mkdir("{$dir}/{$name}", 0755, true); + file_put_contents("{$dir}/{$name}/composer.json", json_encode(['extra' => ['saucebase' => ['frameworks' => $frameworks]]])); + register_shutdown_function(fn () => exec('rm -rf '.escapeshellarg($dir))); + + return $dir; + } } From f5ce96381a7d6eca5ec0fce7b50b4eb490c48980 Mon Sep 17 00:00:00 2001 From: roble Date: Wed, 21 Oct 2026 17:18:30 +0100 Subject: [PATCH 2/3] refactor: update process handling to use Illuminate's Process facade and improve dependency versions --- composer.json | 25 ++-- src/Console/Application.php | 2 + src/Console/Commands/InstallCommand.php | 28 ++--- src/Console/Commands/StackCommand.php | 21 ++-- src/Environments/DockerEnvironment.php | 108 ++++++++---------- src/Environments/Environment.php | 3 +- .../Environments/DockerEnvironmentTest.php | 18 +++ .../Environments/DockerQuietExecTest.php | 27 +++-- tests/Feature/InstallCommandPatchesTest.php | 3 + tests/Feature/InstallCommandTest.php | 8 ++ tests/Feature/StackCommandTest.php | 3 + tests/TestCase.php | 33 ++++++ tests/Unit/ProcessGuardTest.php | 39 +++++++ 13 files changed, 203 insertions(+), 115 deletions(-) create mode 100644 tests/Unit/ProcessGuardTest.php diff --git a/composer.json b/composer.json index b3bc036..945213b 100644 --- a/composer.json +++ b/composer.json @@ -7,20 +7,21 @@ "require": { "php": "^8.4", "composer-runtime-api": "^2.2", - "guzzlehttp/guzzle": "^7.8", - "illuminate/console": "^13.0", - "illuminate/container": "^13.0", - "illuminate/events": "^13.0", - "illuminate/filesystem": "^13.0", - "illuminate/http": "^13.0", - "illuminate/support": "^13.0", - "laravel/installer": "^5.14", - "laravel/prompts": "^0.3", - "symfony/process": "^8.0" + "guzzlehttp/guzzle": "^7.16", + "illuminate/console": "^13.38", + "illuminate/container": "^13.38", + "illuminate/events": "^13.38", + "illuminate/filesystem": "^13.38", + "illuminate/http": "^13.38", + "illuminate/support": "^13.38", + "laravel/installer": "^5.32", + "laravel/prompts": "^0.3.26", + "symfony/process": "^8.1.9", + "illuminate/process": "^13.38" }, "require-dev": { - "phpunit/phpunit": "^11.0", - "mockery/mockery": "^1.6" + "phpunit/phpunit": "^11.5.57", + "mockery/mockery": "^1.6.15" }, "autoload": { "psr-4": { diff --git a/src/Console/Application.php b/src/Console/Application.php index a6c4cf4..452821b 100644 --- a/src/Console/Application.php +++ b/src/Console/Application.php @@ -6,6 +6,7 @@ use Illuminate\Console\Application as ConsoleApplication; use Illuminate\Events\Dispatcher; use Illuminate\Http\Client\Factory as HttpFactory; +use Illuminate\Process\Factory as ProcessFactory; use Illuminate\Support\Facades\Facade; use Saucebase\Installer\Console\Commands\InstallCommand; use Saucebase\Installer\Console\Commands\NewCommand; @@ -19,6 +20,7 @@ public static function make(): ConsoleApplication $container = new Container; Container::setInstance($container); $container->singleton(HttpFactory::class); + $container->singleton(ProcessFactory::class); Facade::setFacadeApplication($container); $console = new ConsoleApplication($container, new Dispatcher($container), static::version()); diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 002c0a6..d8222b1 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -10,7 +10,7 @@ use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; use Saucebase\Installer\ModuleRegistry; -use Symfony\Component\Process\Process; +use Illuminate\Support\Facades\Process; use function Laravel\Prompts\callout; use function Laravel\Prompts\select; @@ -107,11 +107,10 @@ public function path(string $relative = ''): string */ public function runArtisan(array $args, int $timeout = 120): bool { - $process = new Process([PHP_BINARY, $this->path('artisan'), ...$args], $this->targetPath()); - $process->setTimeout($timeout); - $process->run(); - - return $process->isSuccessful(); + return Process::path($this->targetPath()) + ->timeout($timeout) + ->run([PHP_BINARY, $this->path('artisan'), ...$args]) + ->successful(); } public function getSelectedStack(): ?string @@ -274,11 +273,10 @@ public function installCore(): bool /** @param string[] $command */ public function runProcess(array $command, int $timeout = 300): bool { - $process = new Process($command, $this->targetPath()); - $process->setTimeout($timeout); - $process->run(); - - return $process->isSuccessful(); + return Process::path($this->targetPath()) + ->timeout($timeout) + ->run($command) + ->successful(); } /** A contributor checkout runs the UI from saucebase/core instead of owning a copy. */ @@ -836,11 +834,9 @@ public function applyModulePatches(array $modules): bool private function gitApply(string $patch, string ...$flags): bool { - $process = new Process(['git', 'apply', '--whitespace=nowarn', ...$flags, $patch]); - $process->setWorkingDirectory($this->targetPath()); - $process->run(); - - return $process->isSuccessful(); + return Process::path($this->targetPath()) + ->run(['git', 'apply', '--whitespace=nowarn', ...$flags, $patch]) + ->successful(); } /** diff --git a/src/Console/Commands/StackCommand.php b/src/Console/Commands/StackCommand.php index 39b5ac5..8cbcc2e 100644 --- a/src/Console/Commands/StackCommand.php +++ b/src/Console/Commands/StackCommand.php @@ -4,7 +4,7 @@ use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; -use Symfony\Component\Process\Process; +use Illuminate\Support\Facades\Process; use function Laravel\Prompts\select; @@ -155,9 +155,7 @@ private function runReset(): int $this->restoreTrackedFiles($framework); foreach ($this->generatedFiles($framework) as $file) { - $process = new Process(['git', '-C', $this->basePath, 'checkout', '--', $file]); - $process->run(); - $exitCode = $process->getExitCode(); + $exitCode = Process::run(['git', '-C', $this->basePath, 'checkout', '--', $file])->exitCode(); if ($exitCode !== 0) { // Module files are tracked in their own repos — skip-worktree was already @@ -343,10 +341,9 @@ private function skipGeneratedFiles(string $framework): void } foreach ($this->generatedFiles($framework) as $file) { - $process = new Process(['git', '-C', $this->basePath, 'update-index', '--skip-worktree', $file]); - $process->run(); + $result = Process::run(['git', '-C', $this->basePath, 'update-index', '--skip-worktree', $file]); - if ($process->getExitCode() !== 0) { + if ($result->exitCode() !== 0) { $this->warn("Could not skip-worktree {$file} (not in git index)."); } } @@ -355,7 +352,7 @@ private function skipGeneratedFiles(string $framework): void private function restoreTrackedFiles(string $framework): void { foreach ($this->generatedFiles($framework) as $file) { - (new Process(['git', '-C', $this->basePath, 'update-index', '--no-skip-worktree', $file]))->run(); + Process::run(['git', '-C', $this->basePath, 'update-index', '--no-skip-worktree', $file]); } } @@ -366,11 +363,11 @@ private function restoreTrackedFiles(string $framework): void protected function runNpmInstall(): void { $this->info('Running npm install...'); - $process = new Process(['npm', 'install'], $this->basePath); - $process->setTimeout(300); - $process->run(fn ($_type, $buffer) => $this->output->write($buffer)); + $result = Process::path($this->basePath) + ->timeout(300) + ->run(['npm', 'install'], fn ($_type, $buffer) => $this->output->write($buffer)); - if (! $process->isSuccessful()) { + if (! $result->successful()) { $this->warn('npm install failed. Run manually: npm install'); } } diff --git a/src/Environments/DockerEnvironment.php b/src/Environments/DockerEnvironment.php index f01451b..c1edf8c 100644 --- a/src/Environments/DockerEnvironment.php +++ b/src/Environments/DockerEnvironment.php @@ -3,7 +3,7 @@ namespace Saucebase\Installer\Environments; use Saucebase\Installer\Console\Commands\InstallCommand; -use Symfony\Component\Process\Process; +use Illuminate\Support\Facades\Process; use function Laravel\Prompts\confirm; use function Laravel\Prompts\select; @@ -182,17 +182,16 @@ protected function generateSsl(InstallCommand $command): void $command->info('Generating SSL certificates...'); @mkdir(dirname($certFile), 0755, true); - (new Process(['mkcert', '-install']))->run(); + Process::run(['mkcert', '-install']); - $cert = new Process([ + $cert = Process::run([ 'mkcert', '-key-file', $keyFile, '-cert-file', $certFile, ...$this->certificateHosts($host), ]); - $cert->run(); - if (! $cert->isSuccessful()) { + if (! $cert->successful()) { $command->warn('SSL generation failed. Run mkcert manually if HTTPS is needed.'); } } @@ -213,16 +212,14 @@ protected function certificateHosts(string $host): array */ protected function certCoversHost(string $certFile, string $host): bool { - $process = new Process(['openssl', 'x509', '-in', $certFile, '-noout', '-text']); - $process->setTimeout(15); - $process->run(); + $result = Process::timeout(15)->run(['openssl', 'x509', '-in', $certFile, '-noout', '-text']); - if (! $process->isSuccessful()) { + if (! $result->successful()) { return false; } // Anchor the end so "DNS:myapp.test" does not satisfy a request for "app.test". - return preg_match('/DNS:'.preg_quote($host, '/').'(?=[,\s]|$)/', $process->getOutput()) === 1; + return preg_match('/DNS:'.preg_quote($host, '/').'(?=[,\s]|$)/', $result->output()) === 1; } /** @@ -380,27 +377,25 @@ protected function portInUse(int $port): bool /** @return string[] Names of the containers belonging to this app's own Compose project. */ protected function ownContainers(InstallCommand $command): array { - $process = new Process(['docker', 'compose', 'ps', '--format', '{{.Name}}'], $command->targetPath()); - $process->setTimeout(15); - $process->run(); + $result = Process::path($command->targetPath()) + ->timeout(15) + ->run(['docker', 'compose', 'ps', '--format', '{{.Name}}']); - if (! $process->isSuccessful()) { + if (! $result->successful()) { return []; } - return array_values(array_filter(array_map('trim', preg_split('/\R/', $process->getOutput()) ?: []))); + return array_values(array_filter(array_map('trim', preg_split('/\R/', $result->output()) ?: []))); } /** @return array Host port => owner. */ protected function dockerPortOwners(): array { - $process = new Process([ + $result = Process::timeout(15)->run([ 'docker', 'ps', '--format', '{{.Ports}}|{{.Names}}|{{.Label "com.docker.compose.project"}}', ]); - $process->setTimeout(15); - $process->run(); - return $process->isSuccessful() ? $this->parseDockerPortOwners($process->getOutput()) : []; + return $result->successful() ? $this->parseDockerPortOwners($result->output()) : []; } /** @return array */ @@ -498,14 +493,12 @@ protected function stopConflicting(InstallCommand $command, array $targets, arra foreach ($targets as $target) { $command->info('Stopping '.($target['project'] ?? $target['container']).'...'); - $process = $target['project'] !== null - ? new Process(['docker', 'compose', '-p', $target['project'], 'stop']) - : new Process(['docker', 'stop', $target['container']]); - $process->setTimeout(120); - $process->run(); + $result = Process::timeout(120)->run($target['project'] !== null + ? ['docker', 'compose', '-p', $target['project'], 'stop'] + : ['docker', 'stop', $target['container']]); - if (! $process->isSuccessful()) { - $command->error('Failed to stop '.($target['project'] ?? $target['container']).': '.$process->getErrorOutput()); + if (! $result->successful()) { + $command->error('Failed to stop '.($target['project'] ?? $target['container']).': '.$result->errorOutput()); } } @@ -577,13 +570,13 @@ protected function startDocker(InstallCommand $command): bool // a container that comes back up can lose its host port bindings. `up` then sees // an unchanged config hash, considers it up to date, and never repairs it. // `up -d` alone already creates what is missing and recreates what changed. - $up = new Process(['docker', 'compose', 'up', '-d', '--wait', '--build'], $command->targetPath()); - $up->setTimeout(30 * 60); // 30 minutes — first run pulls images + builds layers - $up->run(fn ($_type, $buffer) => $command->line(trim($buffer))); + $up = Process::path($command->targetPath()) + ->timeout(30 * 60) // 30 minutes — first run pulls images + builds layers + ->run(['docker', 'compose', 'up', '-d', '--wait', '--build'], fn ($_type, $buffer) => $command->line(trim($buffer))); $command->newLine(); - if (! $up->isSuccessful()) { - $command->error('Docker failed to start: '.$up->getErrorOutput()); + if (! $up->successful()) { + $command->error('Docker failed to start: '.$up->errorOutput()); return false; } @@ -639,46 +632,40 @@ protected function recreateWebContainer(InstallCommand $command): void { // --force-recreate is the only thing that fixes an already-running container // with dropped bindings; a plain `up` leaves it alone. - $process = new Process( - ['docker', 'compose', 'up', '-d', '--force-recreate', 'nginx'], - $command->targetPath(), - ); - $process->setTimeout(120); - $process->run(); + Process::path($command->targetPath()) + ->timeout(120) + ->run(['docker', 'compose', 'up', '-d', '--force-recreate', 'nginx']); } protected function runComposerInContainer(InstallCommand $command): bool { $command->info('Installing PHP dependencies...'); - $process = new Process(['docker', 'compose', 'exec', '-T', 'app', 'composer', 'install'], $command->targetPath()); - $process->setTimeout(300); - $process->run(fn ($_type, $buffer) => $command->line(trim($buffer))); + $result = Process::path($command->targetPath()) + ->timeout(300) + ->run(['docker', 'compose', 'exec', '-T', 'app', 'composer', 'install'], fn ($_type, $buffer) => $command->line(trim($buffer))); - if (! $process->isSuccessful()) { + if (! $result->successful()) { $command->error('composer install failed inside container.'); } - return $process->isSuccessful(); + return $result->successful(); } /** `$quiet` holds the output back unless the command fails, so a task line stays clean. */ protected function execInContainer(InstallCommand $command, array $args, int $timeout = 120, bool $quiet = false): bool { - $process = $this->containerProcess($command, $args); - $process->setTimeout($timeout); - $process->run($quiet ? null : fn ($_type, $buffer) => $command->line(trim($buffer))); + $result = Process::path($command->targetPath()) + ->timeout($timeout) + ->run( + array_merge(['docker', 'compose', 'exec', '-T', 'app'], $args), + $quiet ? null : fn ($_type, $buffer) => $command->line(trim($buffer)), + ); - if ($quiet && ! $process->isSuccessful()) { - $command->line(trim($process->getOutput().$process->getErrorOutput())); + if ($quiet && ! $result->successful()) { + $command->line(trim($result->output().$result->errorOutput())); } - return $process->isSuccessful(); - } - - /** @param string[] $args */ - protected function containerProcess(InstallCommand $command, array $args): Process - { - return new Process(array_merge(['docker', 'compose', 'exec', '-T', 'app'], $args), $command->targetPath()); + return $result->successful(); } protected function generateAppKey(InstallCommand $command): bool @@ -713,14 +700,11 @@ protected function ensureDatabaseUser(InstallCommand $command): bool return true; } - $process = new Process( - ['docker', 'compose', 'exec', '-T', 'mysql', 'mysql', '-uroot', '-p'.$password, '-e', $sql], - $command->targetPath(), - ); - $process->setTimeout(60); - $process->run(); + $result = Process::path($command->targetPath()) + ->timeout(60) + ->run(['docker', 'compose', 'exec', '-T', 'mysql', 'mysql', '-uroot', '-p'.$password, '-e', $sql]); - if ($process->isSuccessful()) { + if ($result->successful()) { return true; } @@ -905,6 +889,6 @@ protected function resumeOptions(): array protected function dockerComposeAvailable(): bool { - return (bool) shell_exec('docker compose version 2>/dev/null'); + return trim(Process::run(['docker', 'compose', 'version'])->output()) !== ''; } } diff --git a/src/Environments/Environment.php b/src/Environments/Environment.php index 913e7b5..9fc3b2d 100644 --- a/src/Environments/Environment.php +++ b/src/Environments/Environment.php @@ -2,6 +2,7 @@ namespace Saucebase\Installer\Environments; +use Illuminate\Support\Facades\Process; use Saucebase\Installer\Console\Commands\InstallCommand; abstract class Environment @@ -170,6 +171,6 @@ public function hasCommand(string $name): bool protected function commandExists(string $name): bool { - return (bool) shell_exec("which {$name} 2>/dev/null"); + return trim(Process::run(['which', $name])->output()) !== ''; } } diff --git a/tests/Feature/Environments/DockerEnvironmentTest.php b/tests/Feature/Environments/DockerEnvironmentTest.php index 562ac62..fa6defb 100644 --- a/tests/Feature/Environments/DockerEnvironmentTest.php +++ b/tests/Feature/Environments/DockerEnvironmentTest.php @@ -231,6 +231,8 @@ protected function startDocker(InstallCommand $command): bool public function test_run_returns_failure_and_skips_composer_when_docker_fails_to_start(): void { + $this->fakeToolsInstalled(); + $spy = (object) ['composerCalled' => false]; $env = new class($spy) extends DockerEnvironment @@ -266,6 +268,8 @@ protected function runComposerInContainer(InstallCommand $command): bool public function test_run_returns_failure_when_composer_install_fails_in_container(): void { + $this->fakeToolsInstalled(); + $spy = (object) ['installCalled' => false]; $env = new class($spy) extends DockerEnvironment @@ -396,6 +400,20 @@ protected function generateSsl(InstallCommand $command): void {} protected function setDockerEnvDefaults(InstallCommand $command): void {} + // Stubbed so the test never queries the real Docker for ports or runs + // `composer require` in a container: only the module step should fail. + protected function checkPorts(InstallCommand $command): bool + { + return true; + } + + protected function configureNginx(InstallCommand $command): void {} + + protected function execInContainer(InstallCommand $command, array $args, int $timeout = 120, bool $quiet = false): bool + { + return true; + } + protected function startDocker(InstallCommand $command): bool { return true; diff --git a/tests/Feature/Environments/DockerQuietExecTest.php b/tests/Feature/Environments/DockerQuietExecTest.php index 06d0054..2eb663d 100644 --- a/tests/Feature/Environments/DockerQuietExecTest.php +++ b/tests/Feature/Environments/DockerQuietExecTest.php @@ -2,18 +2,20 @@ namespace Saucebase\Installer\Tests\Feature\Environments; +use Illuminate\Support\Facades\Process; use Saucebase\Installer\Console\Commands\InstallCommand; use Saucebase\Installer\Environments\DockerEnvironment; use Saucebase\Installer\Tests\Feature\TestableInstallCommand; use Saucebase\Installer\Tests\TestCase; -use Symfony\Component\Process\Process; /** A quiet container command keeps a task line clean, and still shows why it failed. */ class DockerQuietExecTest extends TestCase { /** @return array{0: bool, 1: string[]} */ - private function execQuietly(string $script): array + private function execQuietly(string $output, string $errorOutput = '', int $exitCode = 0): array { + Process::fake(["'docker' 'compose' 'exec' *" => Process::result($output, $errorOutput, $exitCode)]); + $command = new class extends TestableInstallCommand { /** @var string[] */ @@ -26,15 +28,8 @@ public function line($string, $style = null, $verbosity = null): void }; $command->fakeOptions = ['path' => sys_get_temp_dir()]; - $docker = new class($script) extends DockerEnvironment + $docker = new class extends DockerEnvironment { - public function __construct(private string $script) {} - - protected function containerProcess(InstallCommand $command, array $args): Process - { - return new Process(['sh', '-c', $this->script]); - } - public function quietly(InstallCommand $command): bool { return $this->execInContainer($command, ['php', 'artisan', 'migrate'], quiet: true); @@ -46,7 +41,7 @@ public function quietly(InstallCommand $command): bool public function test_a_quiet_command_prints_nothing_when_it_succeeds(): void { - [$ok, $printed] = $this->execQuietly('echo "Seeding database."'); + [$ok, $printed] = $this->execQuietly('Seeding database.'); $this->assertTrue($ok); $this->assertSame([], $printed); @@ -54,9 +49,17 @@ public function test_a_quiet_command_prints_nothing_when_it_succeeds(): void public function test_a_quiet_command_prints_its_output_when_it_fails(): void { - [$ok, $printed] = $this->execQuietly('echo "Seeding database."; echo "SQLSTATE: table missing" >&2; exit 1'); + [$ok, $printed] = $this->execQuietly('Seeding database.', 'SQLSTATE: table missing', 1); $this->assertFalse($ok); $this->assertStringContainsString('SQLSTATE: table missing', implode("\n", $printed)); } + + public function test_the_command_runs_in_the_app_container_from_the_app_folder(): void + { + $this->execQuietly('ok'); + + Process::assertRan(fn ($process) => $process->command === ['docker', 'compose', 'exec', '-T', 'app', 'php', 'artisan', 'migrate'] + && $process->path === sys_get_temp_dir()); + } } diff --git a/tests/Feature/InstallCommandPatchesTest.php b/tests/Feature/InstallCommandPatchesTest.php index e8dd9f5..0bf9654 100644 --- a/tests/Feature/InstallCommandPatchesTest.php +++ b/tests/Feature/InstallCommandPatchesTest.php @@ -19,6 +19,9 @@ protected function setUp(): void { parent::setUp(); + // These tests are about git really applying a patch, in a temporary folder. + $this->allowRealProcess("'git' *"); + $this->files = new Filesystem; $this->dir = sys_get_temp_dir().'/sb-patches-'.uniqid(); $this->files->ensureDirectoryExists($this->dir.'/app'); diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index 463a967..ea964a7 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -184,6 +184,8 @@ public function call($command, array $arguments = [], $outputBuffer = null): int public function test_only_a_contributor_install_calls_the_stack_command(): void { + $this->fakeToolsInstalled(); + $this->fakePackagistList(); $spy = (object) ['stackCallCount' => 0]; @@ -258,6 +260,8 @@ public function call($command, array $arguments = [], $outputBuffer = null): int public function test_driver_native_skips_the_select_prompt(): void { + $this->fakeToolsInstalled(); + $spy = (object) ['selectCalled' => false]; $this->bindCommand((function () use ($spy) { @@ -322,6 +326,8 @@ public function displaySuccess(array $steps = []): void {} public function test_driver_native_runs_install_without_prompting(): void { + $this->fakeToolsInstalled(); + $this->bindCommand((function () { return new class extends InstallCommand @@ -463,6 +469,8 @@ public function ensureEnvFile(): bool public function test_install_returns_failure_and_skips_modules_when_database_setup_fails(): void { + $this->fakeToolsInstalled(); + $spy = (object) ['modulesSetupCalled' => false]; $this->bindCommand((function () use ($spy) { diff --git a/tests/Feature/StackCommandTest.php b/tests/Feature/StackCommandTest.php index 3e318c3..b87e49c 100644 --- a/tests/Feature/StackCommandTest.php +++ b/tests/Feature/StackCommandTest.php @@ -18,6 +18,9 @@ protected function setUp(): void { parent::setUp(); + // These tests are about git really tracking files, in a temporary repository. + $this->allowRealProcess("'git' *"); + $this->files = new Filesystem; $this->tmpDir = sys_get_temp_dir().'/saucebase-fw-test-'.uniqid(); $this->files->makeDirectory($this->tmpDir.'/resources/js', 0755, true); diff --git a/tests/TestCase.php b/tests/TestCase.php index 665ff3e..db43068 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -5,10 +5,14 @@ use Illuminate\Console\Application as ConsoleApplication; use Illuminate\Console\Command; use Illuminate\Support\Facades\Facade; +use Illuminate\Process\PendingProcess; +use Illuminate\Process\ProcessResult; +use Illuminate\Support\Facades\Process; use PHPUnit\Framework\TestCase as BaseTestCase; use Saucebase\Installer\Console\Application; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\BufferedOutput; +use Symfony\Component\Process\Process as SymfonyProcess; abstract class TestCase extends BaseTestCase { @@ -20,6 +24,12 @@ protected function setUp(): void Facade::clearResolvedInstances(); $this->console = Application::make(); + + // A process a test did not fake fails the test instead of reaching the real + // docker, herd, mkcert, npm, composer or git on the developer's machine. + // Laravel only refuses strays while faking, hence the empty fake. + Process::preventStrayProcesses(); + Process::fake([]); } protected function tearDown(): void @@ -29,6 +39,29 @@ protected function tearDown(): void parent::tearDown(); } + /** Every tool the installer looks up with `which` is installed. */ + protected function fakeToolsInstalled(): void + { + Process::fake(["'which' *" => Process::result('/usr/local/bin/tool')]); + } + + /** + * Let commands matching the pattern really run, for tests about a tool's real + * behaviour in a temporary folder (git applying a patch). Patterns match the + * quoted command line: `'git' *`. + */ + protected function allowRealProcess(string $pattern): void + { + Process::fake([$pattern => function (PendingProcess $pending): ProcessResult { + $process = is_array($pending->command) + ? new SymfonyProcess($pending->command, $pending->path, null, null, $pending->timeout) + : SymfonyProcess::fromShellCommandline($pending->command, $pending->path, null, null, $pending->timeout); + $process->run(); + + return new ProcessResult($process); + }]); + } + /** Replace a registered command with a (usually stubbed) instance for subsequent artisan() calls. */ protected function bindCommand(Command $command): void { diff --git a/tests/Unit/ProcessGuardTest.php b/tests/Unit/ProcessGuardTest.php new file mode 100644 index 0000000..cdb3628 --- /dev/null +++ b/tests/Unit/ProcessGuardTest.php @@ -0,0 +1,39 @@ +expectException(\RuntimeException::class); + $this->expectExceptionMessage('without a matching fake'); + + Process::run(['docker', 'ps']); + } + + public function test_the_installer_starts_processes_through_the_fakeable_facade(): void + { + Process::fake(['*' => Process::result('done')]); + $command = new class extends InstallCommand + { + public function targetPath(): string + { + return '/tmp/app'; + } + }; + + $this->assertTrue($command->runProcess(['composer', 'require', 'saucebase/core'])); + + Process::assertRan(fn ($process) => $process->command === ['composer', 'require', 'saucebase/core'] + && $process->path === '/tmp/app'); + } +} From 8710ef23d7915d7263ec0eb5b6c53fc34f0612b5 Mon Sep 17 00:00:00 2001 From: roble <3231587+roble@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:21:32 +0000 Subject: [PATCH 3/3] PHP Linting (Pint) --- src/Console/Commands/InstallCommand.php | 2 +- src/Environments/DockerEnvironment.php | 2 +- tests/Feature/InstallCommandTest.php | 1 - tests/TestCase.php | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index d8222b1..be3160c 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -3,6 +3,7 @@ namespace Saucebase\Installer\Console\Commands; use Illuminate\Console\Command; +use Illuminate\Support\Facades\Process; use Illuminate\Support\Str; use Laravel\Prompts\Elements\Element; use Laravel\Prompts\Elements\ElementContract; @@ -10,7 +11,6 @@ use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; use Saucebase\Installer\ModuleRegistry; -use Illuminate\Support\Facades\Process; use function Laravel\Prompts\callout; use function Laravel\Prompts\select; diff --git a/src/Environments/DockerEnvironment.php b/src/Environments/DockerEnvironment.php index c1edf8c..d6d15b0 100644 --- a/src/Environments/DockerEnvironment.php +++ b/src/Environments/DockerEnvironment.php @@ -2,8 +2,8 @@ namespace Saucebase\Installer\Environments; -use Saucebase\Installer\Console\Commands\InstallCommand; use Illuminate\Support\Facades\Process; +use Saucebase\Installer\Console\Commands\InstallCommand; use function Laravel\Prompts\confirm; use function Laravel\Prompts\select; diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index ea964a7..d02af65 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -328,7 +328,6 @@ public function test_driver_native_runs_install_without_prompting(): void { $this->fakeToolsInstalled(); - $this->bindCommand((function () { return new class extends InstallCommand { diff --git a/tests/TestCase.php b/tests/TestCase.php index db43068..32e003a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -4,9 +4,9 @@ use Illuminate\Console\Application as ConsoleApplication; use Illuminate\Console\Command; -use Illuminate\Support\Facades\Facade; use Illuminate\Process\PendingProcess; use Illuminate\Process\ProcessResult; +use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Process; use PHPUnit\Framework\TestCase as BaseTestCase; use Saucebase\Installer\Console\Application;