Phred/tests/ErrorHandlingTest.php

80 lines
3 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace Phred\Tests;
use Nyholm\Psr7\ServerRequest;
use PHPUnit\Framework\TestCase;
final class ErrorHandlingTest extends TestCase
{
public function testRestProblemDetailsOnException(): void
{
$root = dirname(__DIR__);
/** @var object $app */
$app = require $root . '/bootstrap/app.php';
$this->assertInstanceOf(\Phred\Http\Kernel::class, $app);
// Default format is REST (unless ACCEPT requests JSON:API)
$request = new ServerRequest('GET', '/_phred/error');
$response = $app->handle($request);
$this->assertSame(500, $response->getStatusCode());
$this->assertSame('application/problem+json', $response->getHeaderLine('Content-Type'));
$data = json_decode((string) $response->getBody(), true);
$this->assertIsArray($data);
$this->assertArrayHasKey('type', $data);
$this->assertArrayHasKey('title', $data);
$this->assertArrayHasKey('status', $data);
$this->assertArrayHasKey('detail', $data);
$this->assertSame(500, $data['status']);
$this->assertSame('RuntimeException', $data['title']);
$this->assertStringContainsString('Boom', (string) $data['detail']);
}
public function testJsonApiErrorDocumentOnException(): void
{
$root = dirname(__DIR__);
/** @var object $app */
$app = require $root . '/bootstrap/app.php';
$this->assertInstanceOf(\Phred\Http\Kernel::class, $app);
$request = (new ServerRequest('GET', '/_phred/error'))
->withHeader('Accept', 'application/vnd.api+json');
$response = $app->handle($request);
$this->assertSame(500, $response->getStatusCode());
$this->assertSame('application/vnd.api+json', $response->getHeaderLine('Content-Type'));
$data = json_decode((string) $response->getBody(), true);
$this->assertIsArray($data);
$this->assertArrayHasKey('errors', $data);
$this->assertIsArray($data['errors']);
$this->assertNotEmpty($data['errors']);
$err = $data['errors'][0];
$this->assertSame('500', $err['status']);
$this->assertSame('RuntimeException', $err['title']);
$this->assertStringContainsString('Boom', (string) $err['detail']);
}
public function testWhoopsHtmlInDebugMode(): void
{
// Enable debug for this test
putenv('APP_DEBUG=true');
$root = dirname(__DIR__);
/** @var object $app */
$app = require $root . '/bootstrap/app.php';
$this->assertInstanceOf(\Phred\Http\Kernel::class, $app);
$request = (new ServerRequest('GET', '/_phred/error'))
->withHeader('Accept', 'text/html');
$response = $app->handle($request);
$this->assertSame(500, $response->getStatusCode());
$this->assertStringContainsString('text/html', $response->getHeaderLine('Content-Type'));
$html = (string) $response->getBody();
$this->assertNotSame('', $html);
$this->assertStringContainsString('Whoops', $html);
}
}