diff --git a/app/Listeners/VerifyDatabaseIsReachable.php b/app/Listeners/VerifyDatabaseIsReachable.php new file mode 100644 index 00000000..2522072d --- /dev/null +++ b/app/Listeners/VerifyDatabaseIsReachable.php @@ -0,0 +1,23 @@ +select('select 1'); + } catch (Throwable $e) { + throw new RuntimeException('The database is not reachable: '.$e->getMessage(), previous: $e); + } + } +} diff --git a/tests/Feature/EventListenerRegistrationTest.php b/tests/Feature/EventListenerRegistrationTest.php index a6fda0dc..f5fbac1e 100644 --- a/tests/Feature/EventListenerRegistrationTest.php +++ b/tests/Feature/EventListenerRegistrationTest.php @@ -9,6 +9,7 @@ use App\Events\RouteActivated; use App\Events\RouteArticleApproved; use Illuminate\Contracts\Debug\ExceptionHandler; +use Illuminate\Foundation\Events\DiagnosingHealth; use Illuminate\Support\Facades\Event; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -28,6 +29,7 @@ public static function eventProvider(): array 'NewArticleFetched' => [NewArticleFetched::class], 'RouteActivated' => [RouteActivated::class], 'RouteArticleApproved' => [RouteArticleApproved::class], + 'DiagnosingHealth' => [DiagnosingHealth::class], ]; } diff --git a/tests/Feature/HealthEndpointTest.php b/tests/Feature/HealthEndpointTest.php new file mode 100644 index 00000000..a13f13e5 --- /dev/null +++ b/tests/Feature/HealthEndpointTest.php @@ -0,0 +1,41 @@ +get('/up')->assertOk(); + } + + public function test_up_fails_when_the_database_is_unreachable(): void + { + DB::shouldReceive('connection')->andThrow(new RuntimeException('getaddrinfo for db failed')); + + $this->get('/up')->assertServerError(); + } + + public function test_the_listener_throws_when_the_connection_fails(): void + { + DB::shouldReceive('connection')->andThrow(new RuntimeException('getaddrinfo for db failed')); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The database is not reachable'); + + app(VerifyDatabaseIsReachable::class)->handle(new DiagnosingHealth); + } + + public function test_the_listener_passes_when_the_connection_works(): void + { + app(VerifyDatabaseIsReachable::class)->handle(new DiagnosingHealth); + + $this->addToAssertionCount(1); + } +}