clusev/tests/Feature/HealthServiceTest.php

63 lines
1.7 KiB
PHP

<?php
namespace Tests\Feature;
use App\Models\HealthCheck;
use App\Services\HealthService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class HealthServiceTest extends TestCase
{
use RefreshDatabase;
private function httpCheck(string $url = 'https://svc.example.com/health'): HealthCheck
{
return HealthCheck::create(['type' => 'http', 'target' => $url]);
}
public function test_http_2xx_is_up(): void
{
Http::fake(['*' => Http::response('ok', 200)]);
$r = (new HealthService)->probe($this->httpCheck());
$this->assertTrue($r['ok']);
$this->assertSame('HTTP 200', $r['detail']);
$this->assertNotNull($r['latency']);
}
public function test_http_5xx_is_down_but_answered(): void
{
Http::fake(['*' => Http::response('boom', 500)]);
$r = (new HealthService)->probe($this->httpCheck());
$this->assertFalse($r['ok']);
$this->assertSame('HTTP 500', $r['detail']);
}
public function test_http_connection_error_is_down(): void
{
Http::fake(fn () => throw new ConnectionException('Could not resolve host'));
$r = (new HealthService)->probe($this->httpCheck());
$this->assertFalse($r['ok']);
$this->assertNull($r['latency']);
$this->assertStringContainsString('resolve host', $r['detail']);
}
public function test_tcp_to_a_refused_port_is_down(): void
{
$check = HealthCheck::create(['type' => 'tcp', 'target' => '127.0.0.1', 'port' => 1]);
$r = (new HealthService)->probe($check, 1);
$this->assertFalse($r['ok']);
$this->assertArrayHasKey('detail', $r);
}
}