This commit is contained in:
126
tests/Support/ApiTestCase.php
Normal file
126
tests/Support/ApiTestCase.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
|
||||
namespace Tests\Support;
|
||||
|
||||
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
use QdbHttpResponse;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* In-process API tests via qdb_dispatch_api_request().
|
||||
|
||||
*
|
||||
|
||||
* Error envelopes:
|
||||
|
||||
* - Handlers: { ok: false, error: { code, message } } — use assertError()
|
||||
|
||||
* - Auth middleware (require_valid_token, require_role): { error: "message" } — use assertLegacyAuthError()
|
||||
|
||||
*/
|
||||
|
||||
abstract class ApiTestCase extends TestCase
|
||||
|
||||
{
|
||||
|
||||
protected ?string $bearerToken = null;
|
||||
|
||||
|
||||
|
||||
protected function setUp(): void
|
||||
|
||||
{
|
||||
|
||||
parent::setUp();
|
||||
|
||||
DatabaseFixture::forTests()->reset();
|
||||
|
||||
$this->bearerToken = null;
|
||||
|
||||
unset($GLOBALS['__TEST_JSON_BODY']);
|
||||
|
||||
$_GET = [];
|
||||
|
||||
$_POST = [];
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* @return array{status: int, body: array<string, mixed>, raw: string}
|
||||
|
||||
*/
|
||||
|
||||
protected function api(
|
||||
|
||||
string $method,
|
||||
|
||||
string $route,
|
||||
|
||||
?array $jsonBody = null,
|
||||
|
||||
?string $token = null,
|
||||
|
||||
array $query = [],
|
||||
|
||||
): array {
|
||||
|
||||
$_GET = $query;
|
||||
|
||||
$_POST = [];
|
||||
|
||||
$_SERVER['REQUEST_METHOD'] = strtoupper($method);
|
||||
|
||||
$_SERVER['REQUEST_URI'] = '/api/' . ltrim($route, '/');
|
||||
|
||||
$_SERVER['SCRIPT_NAME'] = '/api/index.php';
|
||||
|
||||
$_SERVER['HTTP_AUTHORIZATION'] = ($token ?? $this->bearerToken)
|
||||
|
||||
? 'Bearer ' . ($token ?? $this->bearerToken)
|
||||
|
||||
: '';
|
||||
|
||||
|
||||
|
||||
if ($jsonBody !== null) {
|
||||
|
||||
$GLOBALS['__TEST_JSON_BODY'] = json_encode($jsonBody, JSON_THROW_ON_ERROR);
|
||||
|
||||
} else {
|
||||
|
||||
unset($GLOBALS['__TEST_JSON_BODY']);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
ob_start();
|
||||
|
||||
$status = 200;
|
||||
|
||||
$body = [];
|
||||
|
||||
|
||||
|
||||
try {
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/api/dispatch.php';
|
||||
|
||||
qdb_dispatch_api_request();
|
||||
|
||||
} catch (QdbHttpResponse $e) {
|
||||
|
||||
Reference in New Issue
Block a user