97 lines
2.8 KiB
PHP
97 lines
2.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Tests;
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Slim\Psr7\Factory\ServerRequestFactory;
|
|
use Slim\Psr7\Response;
|
|
use Slim\Views\Twig;
|
|
|
|
abstract class ControllerTestBase extends TestCase
|
|
{
|
|
/**
|
|
* @param array<string, mixed> $queryParams
|
|
* @param array<string, mixed> $serverParams
|
|
*/
|
|
protected function makeGet(string $path, array $queryParams = [], array $serverParams = []): \Psr\Http\Message\ServerRequestInterface
|
|
{
|
|
$request = (new ServerRequestFactory())->createServerRequest('GET', $path, $serverParams);
|
|
|
|
if ($queryParams !== []) {
|
|
$request = $request->withQueryParams($queryParams);
|
|
}
|
|
|
|
return $request;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $parsedBody
|
|
* @param array<string, mixed> $serverParams
|
|
*/
|
|
protected function makePost(string $path, array $parsedBody = [], array $serverParams = []): \Psr\Http\Message\ServerRequestInterface
|
|
{
|
|
$request = (new ServerRequestFactory())->createServerRequest('POST', $path, $serverParams);
|
|
|
|
if ($parsedBody !== []) {
|
|
$request = $request->withParsedBody($parsedBody);
|
|
}
|
|
|
|
return $request;
|
|
}
|
|
|
|
protected function makeResponse(): ResponseInterface
|
|
{
|
|
return new Response();
|
|
}
|
|
|
|
/**
|
|
* @return Twig&\PHPUnit\Framework\MockObject\MockObject
|
|
*/
|
|
protected function makeTwigMock(): Twig
|
|
{
|
|
/** @var Twig&\PHPUnit\Framework\MockObject\MockObject $mock */
|
|
$mock = $this->getMockBuilder(Twig::class)
|
|
->disableOriginalConstructor()
|
|
->onlyMethods(['render'])
|
|
->getMock();
|
|
|
|
return $mock;
|
|
}
|
|
|
|
protected function assertRedirectTo(ResponseInterface $response, string $path, int $status = 302): void
|
|
{
|
|
self::assertSame($status, $response->getStatusCode());
|
|
self::assertSame($path, $response->getHeaderLine('Location'));
|
|
}
|
|
|
|
protected function assertStatus(ResponseInterface $response, int $status): void
|
|
{
|
|
self::assertSame($status, $response->getStatusCode());
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $expectedSubset
|
|
*/
|
|
protected function assertJsonContains(ResponseInterface $response, array $expectedSubset): void
|
|
{
|
|
$body = (string) $response->getBody();
|
|
/** @var mixed $decoded */
|
|
$decoded = json_decode($body, true);
|
|
|
|
self::assertIsArray($decoded, 'Response body is not valid JSON.');
|
|
|
|
foreach ($expectedSubset as $key => $value) {
|
|
self::assertArrayHasKey($key, $decoded);
|
|
self::assertSame($value, $decoded[$key]);
|
|
}
|
|
}
|
|
|
|
protected function assertJsonContentType(ResponseInterface $response): void
|
|
{
|
|
self::assertStringContainsString('application/json', $response->getHeaderLine('Content-Type'));
|
|
}
|
|
}
|