From 14c4d4e258a253ccbd1918ae3da058695b17ffdb Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Fri, 23 Oct 2026 11:22:37 +0200 Subject: [PATCH 1/4] chore: consistent health checks (P1) Adds the standard health check set agreed for all Laravel Cloud apps: CacheCheck, OptimizedAppCheck, PendingMigrationsCheck, ProductionConfigCheck (production only), SchedulePolicyCheck and StorageRoundTripCheck. SecurityAdvisoriesCheck loses ->lastDayOfMonth(): spatie only runs a check when its cron is due in the minute of the request, and Oh Dear asks once an hour, so the check was skipped on practically every run. Co-Authored-By: Claude Opus 5.5 --- app/Checks/PendingMigrationsCheck.php | 67 +++++++++++++++++++ app/Checks/ProductionConfigCheck.php | 47 +++++++++++++ app/Checks/SchedulePolicyCheck.php | 51 ++++++++++++++ app/Checks/StorageRoundTripCheck.php | 48 +++++++++++++ app/Providers/AppServiceProvider.php | 17 +++-- .../Checks/PendingMigrationsCheckTest.php | 21 ++++++ .../Unit/Checks/ProductionConfigCheckTest.php | 42 ++++++++++++ tests/Unit/Checks/SchedulePolicyCheckTest.php | 34 ++++++++++ .../Unit/Checks/StorageRoundTripCheckTest.php | 31 +++++++++ 9 files changed, 354 insertions(+), 4 deletions(-) create mode 100644 app/Checks/PendingMigrationsCheck.php create mode 100644 app/Checks/ProductionConfigCheck.php create mode 100644 app/Checks/SchedulePolicyCheck.php create mode 100644 app/Checks/StorageRoundTripCheck.php create mode 100644 tests/Unit/Checks/PendingMigrationsCheckTest.php create mode 100644 tests/Unit/Checks/ProductionConfigCheckTest.php create mode 100644 tests/Unit/Checks/SchedulePolicyCheckTest.php create mode 100644 tests/Unit/Checks/StorageRoundTripCheckTest.php diff --git a/app/Checks/PendingMigrationsCheck.php b/app/Checks/PendingMigrationsCheck.php new file mode 100644 index 0000000..352101d --- /dev/null +++ b/app/Checks/PendingMigrationsCheck.php @@ -0,0 +1,67 @@ +pending(); + } catch (Throwable $exception) { + return $result->shortSummary('unreadable')->failed("Cannot tell which migrations have run: {$exception->getMessage()}"); + } + + if ($pending === null) { + return $result->shortSummary('no migrations table')->failed('The migrations table does not exist, so this database has never been migrated.'); + } + + $result->shortSummary($pending === [] ? 'up to date' : count($pending).' pending'); + + if ($pending === []) { + return $result->ok(); + } + + $reported = array_slice($pending, 0, self::REPORTED_MIGRATIONS); + $hidden = count($pending) - count($reported); + + return $result->failed( + count($pending).' migration(s) have not run: '.implode(', ', $reported) + .($hidden > 0 ? ", and {$hidden} more" : '') + .'. Run `php artisan migrate --force`.', + ); + } + + /** + * @return list|null + */ + private function pending(): ?array + { + /** @var Migrator $migrator */ + $migrator = app('migrator'); + + if (! $migrator->repositoryExists()) { + return null; + } + + $files = $migrator->getMigrationFiles(array_merge([database_path('migrations')], $migrator->paths())); + + return array_values(array_diff(array_keys($files), $migrator->getRepository()->getRan())); + } +} diff --git a/app/Checks/ProductionConfigCheck.php b/app/Checks/ProductionConfigCheck.php new file mode 100644 index 0000000..3f86e2e --- /dev/null +++ b/app/Checks/ProductionConfigCheck.php @@ -0,0 +1,47 @@ +shortSummary($problems === [] ? 'ok' : count($problems).' problem(s)'); + + return $problems === [] ? $result->ok() : $result->failed(implode('; ', $problems).'.'); + } +} diff --git a/app/Checks/SchedulePolicyCheck.php b/app/Checks/SchedulePolicyCheck.php new file mode 100644 index 0000000..bf2a14c --- /dev/null +++ b/app/Checks/SchedulePolicyCheck.php @@ -0,0 +1,51 @@ +between()` or `->environments()` do not help: Cloud only sees the cron. + */ +final class SchedulePolicyCheck extends Check +{ + public const int MIN_INTERVAL_MINUTES = 5; + + public function run(): Result + { + $offenders = collect(app(Schedule::class)->events()) + ->filter(fn (Event $event): bool => $this->runsMoreOftenThanAllowed($event->expression)) + ->map(fn (Event $event): string => trim(($event->description ?: (string) $event->command)." ({$event->expression})")) + ->values() + ->all(); + + $result = Result::make()->shortSummary($offenders === [] ? 'ok' : count($offenders).' task(s) too frequent'); + + return $offenders === [] + ? $result->ok() + : $result->failed('Tasks run more often than every '.self::MIN_INTERVAL_MINUTES.' minutes: '.implode(', ', $offenders).'.'); + } + + private function runsMoreOftenThanAllowed(string $expression): bool + { + $minute = explode(' ', trim($expression))[0]; + + if ($minute === '*') { + return true; + } + + if (preg_match('/^\*\/(\d+)$/', $minute, $matches) === 1) { + return (int) $matches[1] < self::MIN_INTERVAL_MINUTES; + } + + return count(explode(',', $minute)) > intdiv(60, self::MIN_INTERVAL_MINUTES); + } +} diff --git a/app/Checks/StorageRoundTripCheck.php b/app/Checks/StorageRoundTripCheck.php new file mode 100644 index 0000000..dc3ea7f --- /dev/null +++ b/app/Checks/StorageRoundTripCheck.php @@ -0,0 +1,48 @@ +shortSummary("{$disk} ({$driver})"); + + if ($driver === 'local') { + return $result->failed("The default disk `{$disk}` is local; files are lost on the next deploy. Set FILESYSTEM_DISK to the bucket disk."); + } + + $path = 'health/'.Str::uuid()->toString().'.txt'; + $content = 'ok '.now()->toIso8601String(); + + try { + Storage::disk($disk)->put($path, $content); + $read = Storage::disk($disk)->get($path); + Storage::disk($disk)->delete($path); + } catch (Throwable $exception) { + return $result->failed("Storage round trip on `{$disk}` failed: {$exception->getMessage()}"); + } + + return $read === $content + ? $result->ok() + : $result->failed("Storage round trip on `{$disk}` read back different content."); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 3d2b2c3..c5b1020 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -7,6 +7,10 @@ use App\Checks\FailedJobsCheck; use App\Checks\JobsCheck; use App\Checks\NightwatchIssuesCheck; +use App\Checks\PendingMigrationsCheck; +use App\Checks\ProductionConfigCheck; +use App\Checks\SchedulePolicyCheck; +use App\Checks\StorageRoundTripCheck; use App\Models\AiModel; use App\Models\Network; use App\Models\NetworkUser; @@ -24,9 +28,11 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; +use Spatie\Health\Checks\Checks\CacheCheck; use Spatie\Health\Checks\Checks\DatabaseCheck; use Spatie\Health\Checks\Checks\DebugModeCheck; use Spatie\Health\Checks\Checks\EnvironmentCheck; +use Spatie\Health\Checks\Checks\OptimizedAppCheck; use Spatie\Health\Checks\Checks\ScheduleCheck; use Spatie\Health\Facades\Health; use Spatie\SecurityAdvisoriesHealthCheck\SecurityAdvisoriesCheck; @@ -73,9 +79,6 @@ public function boot(): void $scheduleCheck = ScheduleCheck::new(); $scheduleCheck->heartbeatMaxAgeInMinutes(120); - $advisoriesCheck = SecurityAdvisoriesCheck::new(); - $advisoriesCheck->lastDayOfMonth(); - Health::checks([ DatabaseCheck::new(), DebugModeCheck::new(), @@ -84,7 +87,13 @@ public function boot(): void $scheduleCheck, FailedJobsCheck::new(), NightwatchIssuesCheck::new()->if(filled(config('default.nightwatch.api_token')) && filled(config('default.nightwatch.application_id'))), - $advisoriesCheck, + SecurityAdvisoriesCheck::new(), + CacheCheck::new(), + OptimizedAppCheck::new(), + PendingMigrationsCheck::new(), + ProductionConfigCheck::new()->if(app()->isProduction()), + SchedulePolicyCheck::new(), + StorageRoundTripCheck::new(), ]); } diff --git a/tests/Unit/Checks/PendingMigrationsCheckTest.php b/tests/Unit/Checks/PendingMigrationsCheckTest.php new file mode 100644 index 0000000..aa4ca1a --- /dev/null +++ b/tests/Unit/Checks/PendingMigrationsCheckTest.php @@ -0,0 +1,21 @@ +run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails when a migration has not run', function () { + $latest = DB::table('migrations')->orderByDesc('id')->value('migration'); + DB::table('migrations')->where('migration', $latest)->delete(); + + $result = (new PendingMigrationsCheck)->run(); + + expect($result->status->equals(Status::failed()))->toBeTrue() + ->and($result->getNotificationMessage())->toContain($latest); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/ProductionConfigCheckTest.php b/tests/Unit/Checks/ProductionConfigCheckTest.php new file mode 100644 index 0000000..7a81e01 --- /dev/null +++ b/tests/Unit/Checks/ProductionConfigCheckTest.php @@ -0,0 +1,42 @@ + 'https://example.ch', + 'cache.default' => 'database', + 'session.driver' => 'database', + ]); +}); + +it('passes for a production-ready configuration', function () { + expect((new ProductionConfigCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails when APP_URL is not https', function () { + config(['app.url' => 'http://example.ch']); + + expect((new ProductionConfigCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails when APP_URL points at localhost', function () { + config(['app.url' => 'https://localhost']); + + expect((new ProductionConfigCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails for array cache or session stores', function (string $key) { + config([$key => 'array']); + + expect((new ProductionConfigCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->with(['cache.default', 'session.driver'])->group('unit', 'checks'); + +it('does not check the mailer', function () { + config(['mail.default' => 'log']); + + expect((new ProductionConfigCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/SchedulePolicyCheckTest.php b/tests/Unit/Checks/SchedulePolicyCheckTest.php new file mode 100644 index 0000000..6dbd0a4 --- /dev/null +++ b/tests/Unit/Checks/SchedulePolicyCheckTest.php @@ -0,0 +1,34 @@ +command('inspire')->cron($expression); + app()->instance(Schedule::class, $schedule); + + return $schedule; +} + +it('passes for hourly and five-minute tasks', function (string $expression) { + schedulePolicyWith($expression); + + expect((new SchedulePolicyCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->with(['0 * * * *', '*/5 * * * 1-5', '0 22 28-31 * *', '0,30 * * * *'])->group('unit', 'checks'); + +it('fails for tasks that run more often than every five minutes', function (string $expression) { + schedulePolicyWith($expression); + + expect((new SchedulePolicyCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->with(['* * * * *', '*/2 * * * *', '0,1,2,3,4,5,6,7,8,9,10,11,12 * * * *'])->group('unit', 'checks'); + +it('passes the schedule this app defines', function () { + runArtisan('schedule:list')->assertSuccessful(); + + expect((new SchedulePolicyCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/StorageRoundTripCheckTest.php b/tests/Unit/Checks/StorageRoundTripCheckTest.php new file mode 100644 index 0000000..52a8460 --- /dev/null +++ b/tests/Unit/Checks/StorageRoundTripCheckTest.php @@ -0,0 +1,31 @@ + 's3', 'filesystems.disks.s3.driver' => 's3']); + Storage::fake('s3'); + + expect((new StorageRoundTripCheck)->run()->status->equals(Status::ok()))->toBeTrue() + ->and(Storage::disk('s3')->allFiles('health'))->toBe([]); +})->group('unit', 'checks'); + +it('fails when the default disk is local', function () { + config(['filesystems.default' => 'local', 'filesystems.disks.local.driver' => 'local']); + + expect((new StorageRoundTripCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails when the disk throws', function () { + config(['filesystems.default' => 's3', 'filesystems.disks.s3.driver' => 's3']); + Storage::shouldReceive('disk')->with('s3')->andThrow(new RuntimeException('bucket gone')); + + $result = (new StorageRoundTripCheck)->run(); + + expect($result->status->equals(Status::failed()))->toBeTrue() + ->and($result->getNotificationMessage())->toContain('bucket gone'); +})->group('unit', 'checks'); From 592a87083e89821a8cc23d59cca0ca94af2c5775 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Fri, 23 Oct 2026 11:23:12 +0200 Subject: [PATCH 2/4] chore: Postmark token health check (P2) Adds PostmarkTokenCheck, registered only when the mailer is postmark: it asks Postmark for the server behind the configured token and fails when the token is missing or rejected, before mails pile up in failed jobs. Co-Authored-By: Claude Opus 5.5 --- app/Checks/PostmarkTokenCheck.php | 47 ++++++++++++++++++++ app/Providers/AppServiceProvider.php | 2 + tests/Unit/Checks/PostmarkTokenCheckTest.php | 31 +++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 app/Checks/PostmarkTokenCheck.php create mode 100644 tests/Unit/Checks/PostmarkTokenCheckTest.php diff --git a/app/Checks/PostmarkTokenCheck.php b/app/Checks/PostmarkTokenCheck.php new file mode 100644 index 0000000..2932415 --- /dev/null +++ b/app/Checks/PostmarkTokenCheck.php @@ -0,0 +1,47 @@ +shortSummary('no token')->failed('MAIL_MAILER is postmark, but no Postmark server token is configured.'); + } + + try { + $response = Http::withHeaders(['X-Postmark-Server-Token' => $token]) + ->acceptJson() + ->timeout(3) + ->get('https://api.postmarkapp.com/server'); + } catch (Throwable $exception) { + return $result->shortSummary('postmark unreachable')->failed("Postmark request failed: {$exception->getMessage()}"); + } + + if ($response->successful()) { + return $result->shortSummary('token valid')->ok(); + } + + $message = $response->json('Message'); + + return $result->shortSummary("http {$response->status()}") + ->failed('Postmark rejected the server token: '.(is_string($message) && $message !== '' ? $message : $response->status()).'.'); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index c5b1020..711b41b 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -8,6 +8,7 @@ use App\Checks\JobsCheck; use App\Checks\NightwatchIssuesCheck; use App\Checks\PendingMigrationsCheck; +use App\Checks\PostmarkTokenCheck; use App\Checks\ProductionConfigCheck; use App\Checks\SchedulePolicyCheck; use App\Checks\StorageRoundTripCheck; @@ -94,6 +95,7 @@ public function boot(): void ProductionConfigCheck::new()->if(app()->isProduction()), SchedulePolicyCheck::new(), StorageRoundTripCheck::new(), + PostmarkTokenCheck::new()->if(config('mail.default') === 'postmark'), ]); } diff --git a/tests/Unit/Checks/PostmarkTokenCheckTest.php b/tests/Unit/Checks/PostmarkTokenCheckTest.php new file mode 100644 index 0000000..2813ec7 --- /dev/null +++ b/tests/Unit/Checks/PostmarkTokenCheckTest.php @@ -0,0 +1,31 @@ + 'token']); + Http::fake(['api.postmarkapp.com/server' => Http::response(['Name' => 'app'])]); + + expect((new PostmarkTokenCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + Http::assertSent(fn (Request $request): bool => $request->hasHeader('X-Postmark-Server-Token', 'token')); +})->group('unit', 'checks'); + +it('fails when Postmark rejects the server token', function () { + config(['services.postmark.token' => 'token']); + Http::fake(['api.postmarkapp.com/server' => Http::response(['Message' => 'Invalid token'], 401)]); + + expect((new PostmarkTokenCheck)->run()->status->equals(Status::failed()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails without a token', function () { + config(['services.postmark.token' => null, 'services.postmark.key' => null]); + Http::fake(); + + expect((new PostmarkTokenCheck)->run()->status->equals(Status::failed()))->toBeTrue(); + Http::assertNothingSent(); +})->group('unit', 'checks'); From 824f6b9a29d9a9026bcb57d813fd39d3124279a5 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Fri, 23 Oct 2026 12:36:52 +0200 Subject: [PATCH 3/4] chore: same health check set in every app Every codebar Laravel app now registers the same checks in the same order. Checks that do not apply report ok instead of being left out: - DatabaseCheck, DatabaseConnectionCountCheck (warn > 50, fail > 80), JobsCheck, FailedJobsCheck and PendingMigrationsCheck report "no database" when config('health.uses_database') is false. - PostmarkTokenCheck reports ok when the mailer is not postmark. - EntraClientSecretCheck finds its credentials in microsoft-entra-sso or services.microsoft and reports ok when no SSO is configured. - StorageRoundTripCheck warns instead of failing while the default disk is local (a bucket will be added to every app). Co-Authored-By: Claude Opus 5.5 --- app/Checks/DatabaseAvailability.php | 19 ++++ app/Checks/DatabaseCheck.php | 23 +++++ app/Checks/DatabaseConnectionCountCheck.php | 35 +++++++ app/Checks/EntraClientSecretCheck.php | 91 +++++++++++++++++++ app/Checks/FailedJobsCheck.php | 4 + app/Checks/JobsCheck.php | 4 + app/Checks/PendingMigrationsCheck.php | 4 + app/Checks/PostmarkTokenCheck.php | 8 +- app/Checks/StorageRoundTripCheck.php | 4 +- app/Providers/AppServiceProvider.php | 28 +++--- tests/Unit/Checks/DatabaseChecksTest.php | 32 +++++++ .../Checks/EntraClientSecretCheckTest.php | 55 +++++++++++ tests/Unit/Checks/PostmarkTokenCheckTest.php | 12 +++ .../Unit/Checks/StorageRoundTripCheckTest.php | 4 +- 14 files changed, 303 insertions(+), 20 deletions(-) create mode 100644 app/Checks/DatabaseAvailability.php create mode 100644 app/Checks/DatabaseCheck.php create mode 100644 app/Checks/DatabaseConnectionCountCheck.php create mode 100644 app/Checks/EntraClientSecretCheck.php create mode 100644 tests/Unit/Checks/DatabaseChecksTest.php create mode 100644 tests/Unit/Checks/EntraClientSecretCheckTest.php diff --git a/app/Checks/DatabaseAvailability.php b/app/Checks/DatabaseAvailability.php new file mode 100644 index 0000000..d8b28ee --- /dev/null +++ b/app/Checks/DatabaseAvailability.php @@ -0,0 +1,19 @@ +shortSummary('no database')->ok(); + } + + return parent::run(); + } +} diff --git a/app/Checks/DatabaseConnectionCountCheck.php b/app/Checks/DatabaseConnectionCountCheck.php new file mode 100644 index 0000000..6bd51d5 --- /dev/null +++ b/app/Checks/DatabaseConnectionCountCheck.php @@ -0,0 +1,35 @@ +shortSummary('no database')->ok(); + } + + $connection = $this->connectionName ?? $this->getDefaultConnectionName(); + + if (config("database.connections.{$connection}.driver") === 'sqlite') { + return Result::make()->shortSummary('sqlite')->ok(); + } + + return parent::run(); + } +} diff --git a/app/Checks/EntraClientSecretCheck.php b/app/Checks/EntraClientSecretCheck.php new file mode 100644 index 0000000..a387c59 --- /dev/null +++ b/app/Checks/EntraClientSecretCheck.php @@ -0,0 +1,91 @@ + config key and tenant key, in lookup order */ + private array $sources = [['microsoft-entra-sso', 'tenant_id'], ['services.microsoft', 'tenant']]; + + /** Placeholder secrets some configs fall back to when SSO is not set up. */ + private const array PLACEHOLDER_SECRETS = ['', 'not-configured']; + + public function configKey(string $configKey, string $tenantKey = 'tenant_id'): self + { + $this->sources = [[$configKey, $tenantKey]]; + + return $this; + } + + public function run(): Result + { + $result = Result::make(); + $credentials = $this->credentials(); + + if ($credentials === null) { + return $result->shortSummary('no sso configured')->ok(); + } + + [$tenant, $clientId, $clientSecret] = $credentials; + + try { + $response = Http::asForm()->timeout(3)->post("https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token", [ + 'grant_type' => 'client_credentials', + 'client_id' => $clientId, + 'client_secret' => $clientSecret, + 'scope' => 'https://graph.microsoft.com/.default', + ]); + } catch (Throwable $exception) { + return $result->shortSummary('entra unreachable')->failed("Entra request failed: {$exception->getMessage()}"); + } + + if ($response->successful()) { + return $result->shortSummary('secret valid')->ok(); + } + + $error = $response->json('error'); + $error = is_string($error) ? $error : ''; + + return $result->shortSummary($error !== '' ? $error : "http {$response->status()}") + ->failed('Entra rejected the client credentials ('.($error ?: $response->status()).'). Create a new client secret and update the environment.'); + } + + /** + * @return array{0: string, 1: string, 2: string}|null + */ + private function credentials(): ?array + { + foreach ($this->sources as [$configKey, $tenantKey]) { + $tenant = $this->configString("{$configKey}.{$tenantKey}"); + $clientId = $this->configString("{$configKey}.client_id"); + $clientSecret = $this->configString("{$configKey}.client_secret"); + + if ($tenant !== '' && $clientId !== '' && ! in_array($clientSecret, self::PLACEHOLDER_SECRETS, true)) { + return [$tenant, $clientId, $clientSecret]; + } + } + + return null; + } + + private function configString(string $key): string + { + $value = config($key); + + return is_string($value) ? $value : ''; + } +} diff --git a/app/Checks/FailedJobsCheck.php b/app/Checks/FailedJobsCheck.php index 130b06a..49074d2 100644 --- a/app/Checks/FailedJobsCheck.php +++ b/app/Checks/FailedJobsCheck.php @@ -12,6 +12,10 @@ class FailedJobsCheck extends Check { public function run(): Result { + if (! DatabaseAvailability::isAvailable()) { + return Result::make()->shortSummary('no database')->ok(); + } + $count = DB::table('failed_jobs')->count(); $result = Result::make(); diff --git a/app/Checks/JobsCheck.php b/app/Checks/JobsCheck.php index 019c650..b7dfaa2 100644 --- a/app/Checks/JobsCheck.php +++ b/app/Checks/JobsCheck.php @@ -20,6 +20,10 @@ class JobsCheck extends Check public function run(): Result { + if (! DatabaseAvailability::isAvailable()) { + return Result::make()->shortSummary('no database')->ok(); + } + $count = $this->currentJobsTableCount(); $result = Result::make(); diff --git a/app/Checks/PendingMigrationsCheck.php b/app/Checks/PendingMigrationsCheck.php index 352101d..470c3d1 100644 --- a/app/Checks/PendingMigrationsCheck.php +++ b/app/Checks/PendingMigrationsCheck.php @@ -20,6 +20,10 @@ final class PendingMigrationsCheck extends Check public function run(): Result { + if (! DatabaseAvailability::isAvailable()) { + return Result::make()->shortSummary('no database')->ok(); + } + $result = Result::make(); try { diff --git a/app/Checks/PostmarkTokenCheck.php b/app/Checks/PostmarkTokenCheck.php index 2932415..259b3ec 100644 --- a/app/Checks/PostmarkTokenCheck.php +++ b/app/Checks/PostmarkTokenCheck.php @@ -12,12 +12,18 @@ /** * Asks Postmark for the server that belongs to the configured server * token. Fails when the token is missing or rejected, before mails pile up - * in failed jobs. + * in failed jobs. Reports ok when the mailer is not postmark. */ final class PostmarkTokenCheck extends Check { public function run(): Result { + $mailer = config('mail.default'); + + if ($mailer !== 'postmark') { + return Result::make()->shortSummary('mailer: '.(is_string($mailer) ? $mailer : 'none'))->ok(); + } + $token = config('services.postmark.token') ?? config('services.postmark.key'); $token = is_string($token) ? $token : ''; $result = Result::make(); diff --git a/app/Checks/StorageRoundTripCheck.php b/app/Checks/StorageRoundTripCheck.php index dc3ea7f..0c2a78e 100644 --- a/app/Checks/StorageRoundTripCheck.php +++ b/app/Checks/StorageRoundTripCheck.php @@ -12,7 +12,7 @@ /** * Writes, reads and deletes a small file on the default disk. Fails when - * the bucket's credentials or endpoint are wrong, and when the default + * the bucket's credentials or endpoint are wrong. Warns while the default * disk is a local one: the container's disk is ephemeral on Laravel Cloud, * so files written there are lost on the next deploy or wake-up. */ @@ -27,7 +27,7 @@ public function run(): Result $result = Result::make()->shortSummary("{$disk} ({$driver})"); if ($driver === 'local') { - return $result->failed("The default disk `{$disk}` is local; files are lost on the next deploy. Set FILESYSTEM_DISK to the bucket disk."); + return $result->warning("The default disk `{$disk}` is local; files are lost on the next deploy. Attach a bucket and set FILESYSTEM_DISK."); } $path = 'health/'.Str::uuid()->toString().'.txt'; diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 711b41b..da8f8b8 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,6 +4,9 @@ namespace App\Providers; +use App\Checks\DatabaseCheck; +use App\Checks\DatabaseConnectionCountCheck; +use App\Checks\EntraClientSecretCheck; use App\Checks\FailedJobsCheck; use App\Checks\JobsCheck; use App\Checks\NightwatchIssuesCheck; @@ -30,7 +33,6 @@ use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; use Spatie\Health\Checks\Checks\CacheCheck; -use Spatie\Health\Checks\Checks\DatabaseCheck; use Spatie\Health\Checks\Checks\DebugModeCheck; use Spatie\Health\Checks\Checks\EnvironmentCheck; use Spatie\Health\Checks\Checks\OptimizedAppCheck; @@ -72,30 +74,26 @@ public function boot(): void // shows up, and the cached listings in ViewDataAction rely on this to catch one. Model::shouldBeStrict(! $this->app->isProduction()); - $environmentCheck = EnvironmentCheck::new(); - $environmentCheck->if(app()->isProduction()); - // The app hibernates and the scheduler only runs on an hourly wake-up, // so heartbeats can legitimately be up to an hour old. - $scheduleCheck = ScheduleCheck::new(); - $scheduleCheck->heartbeatMaxAgeInMinutes(120); - Health::checks([ - DatabaseCheck::new(), DebugModeCheck::new(), - $environmentCheck, - JobsCheck::new(), - $scheduleCheck, - FailedJobsCheck::new(), - NightwatchIssuesCheck::new()->if(filled(config('default.nightwatch.api_token')) && filled(config('default.nightwatch.application_id'))), - SecurityAdvisoriesCheck::new(), + EnvironmentCheck::new()->if(app()->isProduction()), + DatabaseCheck::new(), + DatabaseConnectionCountCheck::new(), CacheCheck::new(), OptimizedAppCheck::new(), + ScheduleCheck::new()->heartbeatMaxAgeInMinutes(120), + SecurityAdvisoriesCheck::new(), + NightwatchIssuesCheck::new()->if(filled(config('default.nightwatch.api_token')) && filled(config('default.nightwatch.application_id'))), + JobsCheck::new(), + FailedJobsCheck::new(), PendingMigrationsCheck::new(), ProductionConfigCheck::new()->if(app()->isProduction()), SchedulePolicyCheck::new(), StorageRoundTripCheck::new(), - PostmarkTokenCheck::new()->if(config('mail.default') === 'postmark'), + EntraClientSecretCheck::new(), + PostmarkTokenCheck::new(), ]); } diff --git a/tests/Unit/Checks/DatabaseChecksTest.php b/tests/Unit/Checks/DatabaseChecksTest.php new file mode 100644 index 0000000..49e389c --- /dev/null +++ b/tests/Unit/Checks/DatabaseChecksTest.php @@ -0,0 +1,32 @@ + false]); + + /** @var Check $instance */ + $instance = new $check; + $result = $instance->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no database'); +})->with([DatabaseCheck::class, DatabaseConnectionCountCheck::class, JobsCheck::class, FailedJobsCheck::class, PendingMigrationsCheck::class])->group('unit', 'checks'); + +it('checks the database when the app has one', function () { + expect((new DatabaseCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); + +it('uses the agreed connection thresholds', function () { + $check = new DatabaseConnectionCountCheck; + + expect((fn () => [$this->warningThreshold, $this->errorThreshold])->call($check))->toBe([50, 80]); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/EntraClientSecretCheckTest.php b/tests/Unit/Checks/EntraClientSecretCheckTest.php new file mode 100644 index 0000000..94ac2d1 --- /dev/null +++ b/tests/Unit/Checks/EntraClientSecretCheckTest.php @@ -0,0 +1,55 @@ + 'tenant', + 'microsoft-entra-sso.client_id' => 'client', + 'microsoft-entra-sso.client_secret' => 'secret', + 'services.microsoft' => [], + ]); +}); + +it('passes when Entra issues a token', function () { + Http::fake(['login.microsoftonline.com/*' => Http::response(['access_token' => 'x'])]); + + expect((new EntraClientSecretCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://login.microsoftonline.com/tenant/oauth2/v2.0/token'); +})->group('unit', 'checks'); + +it('fails when Entra rejects the secret', function () { + Http::fake(['login.microsoftonline.com/*' => Http::response(['error' => 'invalid_client'], 401)]); + + $result = (new EntraClientSecretCheck)->run(); + + expect($result->status->equals(Status::failed()))->toBeTrue() + ->and($result->shortSummary)->toBe('invalid_client'); +})->group('unit', 'checks'); + +it('reads socialite credentials from services.microsoft', function () { + config([ + 'microsoft-entra-sso' => [], + 'services.microsoft' => ['tenant' => 'social-tenant', 'client_id' => 'client', 'client_secret' => 'secret'], + ]); + Http::fake(['login.microsoftonline.com/*' => Http::response(['access_token' => 'x'])]); + + expect((new EntraClientSecretCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/social-tenant/')); +})->group('unit', 'checks'); + +it('passes without a request when no SSO is configured', function (?string $secret) { + config(['microsoft-entra-sso.client_secret' => $secret]); + Http::fake(); + + $result = (new EntraClientSecretCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no sso configured'); + Http::assertNothingSent(); +})->with([null, '', 'not-configured'])->group('unit', 'checks'); diff --git a/tests/Unit/Checks/PostmarkTokenCheckTest.php b/tests/Unit/Checks/PostmarkTokenCheckTest.php index 2813ec7..0441bab 100644 --- a/tests/Unit/Checks/PostmarkTokenCheckTest.php +++ b/tests/Unit/Checks/PostmarkTokenCheckTest.php @@ -7,6 +7,10 @@ use Illuminate\Support\Facades\Http; use Spatie\Health\Enums\Status; +beforeEach(function () { + config(['mail.default' => 'postmark']); +}); + it('passes when Postmark accepts the server token', function () { config(['services.postmark.token' => 'token']); Http::fake(['api.postmarkapp.com/server' => Http::response(['Name' => 'app'])]); @@ -29,3 +33,11 @@ expect((new PostmarkTokenCheck)->run()->status->equals(Status::failed()))->toBeTrue(); Http::assertNothingSent(); })->group('unit', 'checks'); + +it('passes without a request when the mailer is not postmark', function () { + config(['mail.default' => 'log', 'services.postmark.token' => null]); + Http::fake(); + + expect((new PostmarkTokenCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + Http::assertNothingSent(); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/StorageRoundTripCheckTest.php b/tests/Unit/Checks/StorageRoundTripCheckTest.php index 52a8460..2dce04d 100644 --- a/tests/Unit/Checks/StorageRoundTripCheckTest.php +++ b/tests/Unit/Checks/StorageRoundTripCheckTest.php @@ -14,10 +14,10 @@ ->and(Storage::disk('s3')->allFiles('health'))->toBe([]); })->group('unit', 'checks'); -it('fails when the default disk is local', function () { +it('warns while the default disk is local', function () { config(['filesystems.default' => 'local', 'filesystems.disks.local.driver' => 'local']); - expect((new StorageRoundTripCheck)->run()->status->equals(Status::failed()))->toBeTrue(); + expect((new StorageRoundTripCheck)->run()->status->equals(Status::warning()))->toBeTrue(); })->group('unit', 'checks'); it('fails when the disk throws', function () { From 40894d3c67fcd74c0befc3bf77c6fdad03cb6f97 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Fri, 23 Oct 2026 13:06:33 +0200 Subject: [PATCH 4/4] test: a dedicated test per health check and full coverage The standard health checks get one test file per class (DatabaseCheck, DatabaseConnectionCountCheck, DatabaseAvailability) and tests for every branch, so the 100 % coverage gate holds. PendingMigrationsCheck is now tested against a mocked migrator; DatabaseConnectionCountCheck is no longer final so its thresholds can be tested without a real connection count. EntraClientSecretCheck drops the unused configKey() override. Co-Authored-By: Claude Opus 5.5 --- app/Checks/DatabaseConnectionCountCheck.php | 2 +- app/Checks/EntraClientSecretCheck.php | 11 +--- .../Unit/Checks/DatabaseAvailabilityTest.php | 17 +++++ tests/Unit/Checks/DatabaseCheckTest.php | 21 ++++++ tests/Unit/Checks/DatabaseChecksTest.php | 32 --------- .../DatabaseConnectionCountCheckTest.php | 50 ++++++++++++++ .../Checks/EntraClientSecretCheckTest.php | 16 +++++ tests/Unit/Checks/FailedJobsCheckTest.php | 9 +++ tests/Unit/Checks/JobsCheckTest.php | 9 +++ .../Checks/PendingMigrationsCheckTest.php | 65 +++++++++++++++++-- tests/Unit/Checks/PostmarkTokenCheckTest.php | 15 +++++ .../Unit/Checks/StorageRoundTripCheckTest.php | 12 ++++ 12 files changed, 211 insertions(+), 48 deletions(-) create mode 100644 tests/Unit/Checks/DatabaseAvailabilityTest.php create mode 100644 tests/Unit/Checks/DatabaseCheckTest.php delete mode 100644 tests/Unit/Checks/DatabaseChecksTest.php create mode 100644 tests/Unit/Checks/DatabaseConnectionCountCheckTest.php diff --git a/app/Checks/DatabaseConnectionCountCheck.php b/app/Checks/DatabaseConnectionCountCheck.php index 6bd51d5..e669a02 100644 --- a/app/Checks/DatabaseConnectionCountCheck.php +++ b/app/Checks/DatabaseConnectionCountCheck.php @@ -12,7 +12,7 @@ * above 50, fail above 80), reporting ok for apps without a database and * for SQLite, which has no connection count. */ -final class DatabaseConnectionCountCheck extends SpatieDatabaseConnectionCountCheck +class DatabaseConnectionCountCheck extends SpatieDatabaseConnectionCountCheck { protected ?int $warningThreshold = 50; diff --git a/app/Checks/EntraClientSecretCheck.php b/app/Checks/EntraClientSecretCheck.php index a387c59..9b797ea 100644 --- a/app/Checks/EntraClientSecretCheck.php +++ b/app/Checks/EntraClientSecretCheck.php @@ -19,18 +19,11 @@ final class EntraClientSecretCheck extends Check { /** @var list config key and tenant key, in lookup order */ - private array $sources = [['microsoft-entra-sso', 'tenant_id'], ['services.microsoft', 'tenant']]; + private const array SOURCES = [['microsoft-entra-sso', 'tenant_id'], ['services.microsoft', 'tenant']]; /** Placeholder secrets some configs fall back to when SSO is not set up. */ private const array PLACEHOLDER_SECRETS = ['', 'not-configured']; - public function configKey(string $configKey, string $tenantKey = 'tenant_id'): self - { - $this->sources = [[$configKey, $tenantKey]]; - - return $this; - } - public function run(): Result { $result = Result::make(); @@ -69,7 +62,7 @@ public function run(): Result */ private function credentials(): ?array { - foreach ($this->sources as [$configKey, $tenantKey]) { + foreach (self::SOURCES as [$configKey, $tenantKey]) { $tenant = $this->configString("{$configKey}.{$tenantKey}"); $clientId = $this->configString("{$configKey}.client_id"); $clientSecret = $this->configString("{$configKey}.client_secret"); diff --git a/tests/Unit/Checks/DatabaseAvailabilityTest.php b/tests/Unit/Checks/DatabaseAvailabilityTest.php new file mode 100644 index 0000000..ada0d20 --- /dev/null +++ b/tests/Unit/Checks/DatabaseAvailabilityTest.php @@ -0,0 +1,17 @@ + null]); + + expect(DatabaseAvailability::isAvailable())->toBeTrue(); +})->group('unit', 'checks'); + +it('treats the database as unavailable when the app opts out', function () { + config(['health.uses_database' => false]); + + expect(DatabaseAvailability::isAvailable())->toBeFalse(); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/DatabaseCheckTest.php b/tests/Unit/Checks/DatabaseCheckTest.php new file mode 100644 index 0000000..84e230c --- /dev/null +++ b/tests/Unit/Checks/DatabaseCheckTest.php @@ -0,0 +1,21 @@ + false]); + + $result = (new DatabaseCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no database'); +})->group('unit', 'checks'); + +it('connects to the database when the app has one', function () { + config(['health.uses_database' => true]); + + expect((new DatabaseCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/DatabaseChecksTest.php b/tests/Unit/Checks/DatabaseChecksTest.php deleted file mode 100644 index 49e389c..0000000 --- a/tests/Unit/Checks/DatabaseChecksTest.php +++ /dev/null @@ -1,32 +0,0 @@ - false]); - - /** @var Check $instance */ - $instance = new $check; - $result = $instance->run(); - - expect($result->status->equals(Status::ok()))->toBeTrue() - ->and($result->shortSummary)->toBe('no database'); -})->with([DatabaseCheck::class, DatabaseConnectionCountCheck::class, JobsCheck::class, FailedJobsCheck::class, PendingMigrationsCheck::class])->group('unit', 'checks'); - -it('checks the database when the app has one', function () { - expect((new DatabaseCheck)->run()->status->equals(Status::ok()))->toBeTrue(); -})->group('unit', 'checks'); - -it('uses the agreed connection thresholds', function () { - $check = new DatabaseConnectionCountCheck; - - expect((fn () => [$this->warningThreshold, $this->errorThreshold])->call($check))->toBe([50, 80]); -})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/DatabaseConnectionCountCheckTest.php b/tests/Unit/Checks/DatabaseConnectionCountCheckTest.php new file mode 100644 index 0000000..83d3c38 --- /dev/null +++ b/tests/Unit/Checks/DatabaseConnectionCountCheckTest.php @@ -0,0 +1,50 @@ + true, 'database.connections.health_pgsql' => ['driver' => 'pgsql']]); + + $check = new class($connections) extends DatabaseConnectionCountCheck + { + public function __construct(private readonly int $connections) {} + + protected function getConnectionCount(): int + { + return $this->connections; + } + }; + $check->connectionName('health_pgsql'); + + return $check; +} + +it('reports ok with "no database" when the app has none', function () { + config(['health.uses_database' => false]); + + $result = (new DatabaseConnectionCountCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no database'); +})->group('unit', 'checks'); + +it('reports ok for sqlite, which has no connection count', function () { + config(['health.uses_database' => true, 'database.connections.health_sqlite' => ['driver' => 'sqlite']]); + + $result = (new DatabaseConnectionCountCheck)->connectionName('health_sqlite')->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('sqlite'); +})->group('unit', 'checks'); + +it('applies the agreed thresholds', function (int $connections, Status $status) { + expect(connectionCountCheckWith($connections)->run()->status->equals($status))->toBeTrue(); +})->with([ + 'ok' => [10, Status::ok()], + 'warning above 50' => [60, Status::warning()], + 'failed above 80' => [90, Status::failed()], +])->group('unit', 'checks'); diff --git a/tests/Unit/Checks/EntraClientSecretCheckTest.php b/tests/Unit/Checks/EntraClientSecretCheckTest.php index 94ac2d1..7ae50d5 100644 --- a/tests/Unit/Checks/EntraClientSecretCheckTest.php +++ b/tests/Unit/Checks/EntraClientSecretCheckTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Checks\EntraClientSecretCheck; +use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Spatie\Health\Enums\Status; @@ -53,3 +54,18 @@ ->and($result->shortSummary)->toBe('no sso configured'); Http::assertNothingSent(); })->with([null, '', 'not-configured'])->group('unit', 'checks'); + +it('reports the HTTP status when Entra gives no error code', function () { + Http::fake(['login.microsoftonline.com/*' => Http::response('', 500)]); + + expect((new EntraClientSecretCheck)->run()->shortSummary)->toBe('http 500'); +})->group('unit', 'checks'); + +it('fails when Entra cannot be reached', function () { + Http::fake(fn () => throw new ConnectionException('timeout')); + + $result = (new EntraClientSecretCheck)->run(); + + expect($result->status->equals(Status::failed()))->toBeTrue() + ->and($result->shortSummary)->toBe('entra unreachable'); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/FailedJobsCheckTest.php b/tests/Unit/Checks/FailedJobsCheckTest.php index 99d76d5..8325b50 100644 --- a/tests/Unit/Checks/FailedJobsCheckTest.php +++ b/tests/Unit/Checks/FailedJobsCheckTest.php @@ -31,3 +31,12 @@ DB::table('failed_jobs')->delete(); })->group('unit', 'checks'); + +it('reports ok with "no database" when the app has none', function () { + config(['health.uses_database' => false]); + + $result = (new FailedJobsCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no database'); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/JobsCheckTest.php b/tests/Unit/Checks/JobsCheckTest.php index 2017230..71926f6 100644 --- a/tests/Unit/Checks/JobsCheckTest.php +++ b/tests/Unit/Checks/JobsCheckTest.php @@ -75,3 +75,12 @@ protected function currentJobsTableCount(): int expect($result->status->equals(Status::ok()))->toBeTrue(); })->group('unit', 'checks'); + +it('reports ok with "no database" when the app has none', function () { + config(['health.uses_database' => false]); + + $result = (new JobsCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('no database'); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/PendingMigrationsCheckTest.php b/tests/Unit/Checks/PendingMigrationsCheckTest.php index aa4ca1a..14bfb25 100644 --- a/tests/Unit/Checks/PendingMigrationsCheckTest.php +++ b/tests/Unit/Checks/PendingMigrationsCheckTest.php @@ -3,19 +3,72 @@ declare(strict_types=1); use App\Checks\PendingMigrationsCheck; -use Illuminate\Support\Facades\DB; +use Illuminate\Database\Migrations\MigrationRepositoryInterface; +use Illuminate\Database\Migrations\Migrator; use Spatie\Health\Enums\Status; +/** + * @param list $files + * @param list $ran + */ +function pendingMigrationsWith(array $files, array $ran, bool $repositoryExists = true): void +{ + $repository = Mockery::mock(MigrationRepositoryInterface::class); + $repository->shouldReceive('getRan')->andReturn($ran); + + $migrator = Mockery::mock(Migrator::class); + $migrator->shouldReceive('repositoryExists')->andReturn($repositoryExists); + $migrator->shouldReceive('paths')->andReturn([]); + $migrator->shouldReceive('getMigrationFiles')->andReturn(array_combine($files, $files)); + $migrator->shouldReceive('getRepository')->andReturn($repository); + + app()->instance('migrator', $migrator); +} + it('passes when every migration has run', function () { - expect((new PendingMigrationsCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + pendingMigrationsWith(['a', 'b'], ['a', 'b']); + + $result = (new PendingMigrationsCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('up to date'); })->group('unit', 'checks'); -it('fails when a migration has not run', function () { - $latest = DB::table('migrations')->orderByDesc('id')->value('migration'); - DB::table('migrations')->where('migration', $latest)->delete(); +it('fails and names the migrations that have not run', function () { + pendingMigrationsWith(['a', 'b', 'c'], ['a']); $result = (new PendingMigrationsCheck)->run(); expect($result->status->equals(Status::failed()))->toBeTrue() - ->and($result->getNotificationMessage())->toContain($latest); + ->and($result->shortSummary)->toBe('2 pending') + ->and($result->getNotificationMessage())->toContain('b, c'); +})->group('unit', 'checks'); + +it('lists at most five pending migrations', function () { + pendingMigrationsWith(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'], []); + + expect((new PendingMigrationsCheck)->run()->getNotificationMessage())->toContain('and 2 more'); +})->group('unit', 'checks'); + +it('fails when the migrations table does not exist', function () { + pendingMigrationsWith([], [], repositoryExists: false); + + expect((new PendingMigrationsCheck)->run()->shortSummary)->toBe('no migrations table'); +})->group('unit', 'checks'); + +it('fails when the migrations cannot be read', function () { + $migrator = Mockery::mock(Migrator::class); + $migrator->shouldReceive('repositoryExists')->andThrow(new RuntimeException('connection lost')); + app()->instance('migrator', $migrator); + + $result = (new PendingMigrationsCheck)->run(); + + expect($result->shortSummary)->toBe('unreadable') + ->and($result->getNotificationMessage())->toContain('connection lost'); +})->group('unit', 'checks'); + +it('reports ok with "no database" when the app has none', function () { + config(['health.uses_database' => false]); + + expect((new PendingMigrationsCheck)->run()->shortSummary)->toBe('no database'); })->group('unit', 'checks'); diff --git a/tests/Unit/Checks/PostmarkTokenCheckTest.php b/tests/Unit/Checks/PostmarkTokenCheckTest.php index 0441bab..6c28eb9 100644 --- a/tests/Unit/Checks/PostmarkTokenCheckTest.php +++ b/tests/Unit/Checks/PostmarkTokenCheckTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Checks\PostmarkTokenCheck; +use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Spatie\Health\Enums\Status; @@ -41,3 +42,17 @@ expect((new PostmarkTokenCheck)->run()->status->equals(Status::ok()))->toBeTrue(); Http::assertNothingSent(); })->group('unit', 'checks'); + +it('fails when Postmark cannot be reached', function () { + config(['services.postmark.token' => 'token']); + Http::fake(fn () => throw new ConnectionException('timeout')); + + expect((new PostmarkTokenCheck)->run()->shortSummary)->toBe('postmark unreachable'); +})->group('unit', 'checks'); + +it('reports the HTTP status when Postmark gives no message', function () { + config(['services.postmark.token' => 'token']); + Http::fake(['api.postmarkapp.com/server' => Http::response('', 500)]); + + expect((new PostmarkTokenCheck)->run()->getNotificationMessage())->toContain('500'); +})->group('unit', 'checks'); diff --git a/tests/Unit/Checks/StorageRoundTripCheckTest.php b/tests/Unit/Checks/StorageRoundTripCheckTest.php index 2dce04d..96d8781 100644 --- a/tests/Unit/Checks/StorageRoundTripCheckTest.php +++ b/tests/Unit/Checks/StorageRoundTripCheckTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Checks\StorageRoundTripCheck; +use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Support\Facades\Storage; use Spatie\Health\Enums\Status; @@ -29,3 +30,14 @@ expect($result->status->equals(Status::failed()))->toBeTrue() ->and($result->getNotificationMessage())->toContain('bucket gone'); })->group('unit', 'checks'); + +it('fails when the file reads back different content', function () { + config(['filesystems.default' => 's3', 'filesystems.disks.s3.driver' => 's3']); + $disk = Mockery::mock(Filesystem::class); + $disk->shouldReceive('put')->andReturnTrue(); + $disk->shouldReceive('get')->andReturn('something else'); + $disk->shouldReceive('delete')->andReturnTrue(); + Storage::shouldReceive('disk')->with('s3')->andReturn($disk); + + expect((new StorageRoundTripCheck)->run()->getNotificationMessage())->toContain('different content'); +})->group('unit', 'checks');