Phred/tests/Feature/M12FeaturesTest.php

91 lines
3.2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Phred\Tests\Feature;
use PHPUnit\Framework\TestCase;
use Phred\Http\Kernel;
use Nyholm\Psr7\ServerRequest;
use Phred\Http\Support\Paginator;
use Symfony\Component\Serializer\SerializerInterface;
class M12FeaturesTest extends TestCase
{
public function test_serialization_service_is_bound(): void
{
$kernel = new Kernel();
$serializer = $kernel->container()->get(SerializerInterface::class);
$this->assertInstanceOf(SerializerInterface::class, $serializer);
$data = ['name' => 'John'];
$json = $serializer->serialize($data, 'json');
$this->assertEquals('{"name":"John"}', $json);
}
public function test_paginator_rest(): void
{
$items = [['id' => 1], ['id' => 2]];
$paginator = new Paginator($items, 10, 2, 1, 'http://localhost/api/posts');
$data = $paginator->toArray();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('meta', $data);
$this->assertArrayHasKey('links', $data);
$this->assertEquals(10, $data['meta']['total']);
$this->assertEquals('/api/posts?page=1&per_page=2', $data['links']['self']);
}
public function test_xml_support(): void
{
$kernel = new Kernel();
$request = (new ServerRequest('GET', '/_phred/health'))
->withHeader('Accept', 'application/xml');
$response = $kernel->handle($request);
$this->assertEquals('application/xml', $response->getHeaderLine('Content-Type'));
$body = (string) $response->getBody();
$this->assertStringContainsString('<?xml', $body);
$this->assertStringContainsString('<ok>1</ok>', $body);
$this->assertStringContainsString('<framework>Phred</framework>', $body);
}
public function test_url_extension_xml(): void
{
$kernel = new Kernel();
$request = new ServerRequest('GET', '/_phred/health.xml');
$response = $kernel->handle($request);
$this->assertEquals('application/xml', $response->getHeaderLine('Content-Type'));
}
public function test_validation_middleware(): void
{
$middleware = new class extends \Phred\Http\Middleware\ValidationMiddleware {
protected function validate(\Psr\Http\Message\ServerRequestInterface $request): array
{
$body = $request->getParsedBody();
$errors = [];
if (empty($body['name'])) {
$errors['name'] = 'Name is required';
}
return $errors;
}
};
$request = new ServerRequest('POST', '/test');
$handler = new class implements \Psr\Http\Server\RequestHandlerInterface {
public function handle(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface
{
return new \Nyholm\Psr7\Response(200);
}
};
$response = $middleware->process($request, $handler);
$this->assertEquals(422, $response->getStatusCode());
$data = json_decode((string) $response->getBody(), true);
$this->assertEquals('Name is required', $data['errors']['name']);
}
}