Files
project-manager/tests/ApiTestCase.php
T

183 lines
5.5 KiB
PHP
Raw Normal View History

2026-09-03 18:30:52 +01:00
<?php
declare(strict_types=1);
namespace Tests;
use PDO;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Slim\App;
use Slim\Psr7\Factory\ServerRequestFactory;
/**
* Boots the real Slim app against a throwaway SQLite database with all
* migrations applied. Email goes to a per-test log file (MAIL_TRANSPORT=log).
2026-09-03 18:30:52 +01:00
*/
abstract class ApiTestCase extends TestCase
{
protected App $app;
private string $databasePath;
private string $mailLogPath;
private ?PDO $db = null;
/** @var array<string, string> */
private array $env = [];
2026-09-03 18:30:52 +01:00
protected function setUp(): void
{
$unique = uniqid('todo-test-', true);
$this->databasePath = sys_get_temp_dir() . "/{$unique}.sqlite";
$this->mailLogPath = sys_get_temp_dir() . "/{$unique}.mail.log";
2026-09-03 18:30:52 +01:00
$this->setEnv([
'DATABASE_PATH' => $this->databasePath,
'APP_URL' => 'https://app.test',
'MAIL_TRANSPORT' => 'log',
'MAIL_LOG_PATH' => $this->mailLogPath,
]);
$pdo = $this->db();
2026-09-03 18:30:52 +01:00
$pdo->exec('PRAGMA foreign_keys = ON');
foreach (glob(dirname(__DIR__) . '/migrations/*.sql') ?: [] as $migration) {
$pdo->exec((string) file_get_contents($migration));
}
$this->app = require dirname(__DIR__) . '/src/bootstrap.php';
}
protected function tearDown(): void
{
$this->db = null;
2026-09-03 18:30:52 +01:00
@unlink($this->databasePath);
@unlink($this->mailLogPath);
foreach (array_keys($this->env) as $key) {
putenv($key);
unset($_ENV[$key], $_SERVER[$key]);
}
$this->env = [];
}
/** @param array<string, string> $vars */
private function setEnv(array $vars): void
{
foreach ($vars as $key => $value) {
putenv("{$key}={$value}");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
$this->env[$key] = $value;
}
}
/**
* Change config env vars and rebuild the app against them (same database).
* For settings Config::load() only reads once at boot, e.g. APP_ALLOW_REGISTRATION.
*
* @param array<string, string> $vars
*/
protected function reconfigure(array $vars): void
{
$this->setEnv($vars);
$this->app = require dirname(__DIR__) . '/src/bootstrap.php';
}
/** A connection to the test database, for seeding rows directly. */
protected function db(): PDO
{
if ($this->db === null) {
$this->db = new PDO('sqlite:' . $this->databasePath, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
}
return $this->db;
2026-09-03 18:30:52 +01:00
}
/**
* @param array<string, mixed>|null $body
* @param array<string, string> $headers
*/
protected function request(
string $method,
string $path,
?array $body = null,
array $headers = [],
): ResponseInterface {
$request = (new ServerRequestFactory())->createServerRequest($method, $path);
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
if ($body !== null) {
$request = $request->withParsedBody($body)->withHeader('Content-Type', 'application/json');
}
return $this->app->handle($request);
}
/**
* Sign in (creating the account if needed) via the real magic-link flow and
* return an `Authorization` header for the resulting session.
2026-09-03 18:30:52 +01:00
*
* @return array<string, string>
*/
protected function authHeader(string $email = 'user@example.com'): array
{
// Clear any resend throttle so this works even if the address was just
// emailed a link earlier in the same test.
$this->db()->prepare('UPDATE users SET verification_email_sent_at = NULL WHERE email = :email')
->execute(['email' => $email]);
$this->request('POST', '/api/auth/magic-link', ['email' => $email]);
2026-09-03 18:30:52 +01:00
$token = $this->decode(
$this->request('POST', '/api/auth/verify-email', ['token' => $this->tokenFromEmail()]),
2026-09-03 18:30:52 +01:00
)['token'];
return ['Authorization' => 'Bearer ' . $token];
}
/** All emails sent so far, oldest first. @return list<array{to: string, subject: string, body: string}> */
protected function sentEmails(): array
{
if (!is_file($this->mailLogPath)) {
return [];
}
$lines = array_filter(explode("\n", (string) file_get_contents($this->mailLogPath)));
return array_map(
static fn (string $line): array => json_decode($line, true, 512, JSON_THROW_ON_ERROR),
array_values($lines),
);
}
/** @return array{to: string, subject: string, body: string} */
protected function lastEmail(): array
{
$emails = $this->sentEmails();
self::assertNotEmpty($emails, 'Expected an email to have been sent.');
return $emails[array_key_last($emails)];
}
/** Pull the magic-link token out of an email body. */
protected function tokenFromEmail(?array $email = null): string
{
$email ??= $this->lastEmail();
self::assertSame(1, preg_match('/verify-email\?token=([a-f0-9]+)/', $email['body'], $m));
return $m[1];
}
2026-09-03 18:30:52 +01:00
/**
* @return array<string, mixed>
*/
protected function decode(ResponseInterface $response): array
{
return (array) json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
}