rob-revisited/ide/tests/SchemaCheckTest.php

300 lines
16 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Doctrine\DoctrineCommands;
use JumPHP\Ide\Doctrine\MappingReader;
use JumPHP\Ide\Doctrine\SchemaCheck;
use JumPHP\Ide\Doctrine\SchemaWatcher;
use JumPHP\Ide\Lang\Messages;
use PHPUnit\Framework\TestCase;
/** The database schema health check: the console outputs read, which problems lead to which fixes, the production guard, the triggers. */
final class SchemaCheckTest extends TestCase
{
private const ROOT = __DIR__ . '/fixtures/doctrine';
private const CONSOLE = __DIR__ . '/fixtures/doctrine-console';
/** @var list<string> */
private array $dirs = [];
protected function setUp(): void
{
Messages::setLocale('en');
}
protected function tearDown(): void
{
Messages::reset();
foreach ($this->dirs as $d) {
exec('rm -rf ' . escapeshellarg($d));
}
}
private static function out(string $file): string
{
return (string)file_get_contents(self::CONSOLE . "/$file");
}
/** @param array<string, string> $files */
private function project(array $files): string
{
$dir = sys_get_temp_dir() . '/schema-' . bin2hex(random_bytes(4));
$this->dirs[] = $dir;
mkdir($dir, 0777, true);
foreach ($files as $path => $text) {
@mkdir(dirname("$dir/$path"), 0777, true);
file_put_contents("$dir/$path", $text);
}
return $dir;
}
public function testTheSqlErrorsOfTheThreeDatabasesAreRecognised(): void
{
$mysql = "An exception occurred while executing a query: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'app.xxxxa' doesn't exist";
$e = SchemaCheck::classifyError($mysql);
self::assertSame('no_table', $e['kind']);
self::assertSame('xxxxa', $e['table']);
self::assertSame('xxxxa', SchemaCheck::classifyError('SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "public.xxxxa" does not exist')['table']);
self::assertSame('xxxxa', SchemaCheck::classifyError('SQLSTATE[HY000]: General error: 1 no such table: xxxxa')['table']);
self::assertSame('app', SchemaCheck::classifyError("SQLSTATE[HY000] [1049] Unknown database 'app'")['database']);
self::assertSame('no_database', SchemaCheck::classifyError('SQLSTATE[08006] [7] connection to server failed: FATAL: database "app" does not exist')['kind']);
self::assertSame('unreachable', SchemaCheck::classifyError('SQLSTATE[HY000] [2002] Connection refused')['kind']);
self::assertSame('unreachable', SchemaCheck::classifyError('php_network_getaddresses: getaddrinfo for db failed: Name or service not known')['kind']);
self::assertNull(SchemaCheck::classifyError('Everything is fine'));
// the colours of the console are not part of the message
self::assertSame('xxxxa', SchemaCheck::classifyError("\e[37;41m Table 'app.xxxxa' doesn't exist \e[39;49m")['table']);
}
public function testTheSchemaDumpIsReadWithoutDoctrinesOwnTable(): void
{
$statements = SchemaCheck::schemaStatements(self::out('dump-sql.txt'));
self::assertSame(['post', 'post_tags', 'content', 'category'], array_slice(SchemaCheck::createdTables($statements), 0, 4));
self::assertSame([], SchemaCheck::schemaStatements(" [OK] Nothing to update - your database is already in sync with the current entity metadata.\n"));
self::assertSame([], SchemaCheck::schemaStatements('CREATE TABLE doctrine_migration_versions (version VARCHAR(191) NOT NULL);'));
}
public function testAnEntityWithoutATableIsNamed(): void
{
$entities = (new MappingReader(self::ROOT))->read()['entities'];
$a = SchemaCheck::analyse(['code' => 0, 'output' => self::out('list-migrated.txt')], ['code' => 0, 'output' => self::out('dump-sql.txt')], $entities);
self::assertSame('problems', $a['state']);
$messages = array_column($a['problems'], 'message');
self::assertContains('The entity Post has no table: no migration creates it.', $messages);
self::assertContains('The entity Content has no table: no migration creates it.', $messages);
self::assertSame(['diff', 'openDoctrine', 'all'], $a['problems'][0]['fixes']);
self::assertSame(0, $a['pending']);
}
public function testPendingMigrationsAreCountedAndHideTheirOwnDifference(): void
{
$entities = (new MappingReader(self::ROOT))->read()['entities'];
$a = SchemaCheck::analyse(['code' => 0, 'output' => self::out('list-pending.txt')], ['code' => 0, 'output' => self::out('dump-sql.txt')], $entities);
self::assertSame(['1 migration is not applied.'], array_column($a['problems'], 'message'));
self::assertSame(['migrate', 'openDoctrine', 'all'], $a['problems'][0]['fixes']);
$two = rtrim(self::out('list-pending.txt')) . "\n| DoctrineMigrations\\Version20261116000000 | not migrated | | | |\n+---+\n";
$b = SchemaCheck::analyse(['code' => 0, 'output' => $two], ['code' => 0, 'output' => ''], $entities);
self::assertSame(2, $b['pending']);
self::assertSame(['2 migrations are not applied.'], array_column($b['problems'], 'message'));
}
public function testAMissingDatabaseAndAnUnreachableServerAreTold(): void
{
$e = "In ExceptionConverter.php line 87:\n An exception occurred in the driver: SQLSTATE[HY000] [1049] Unknown database 'app'\n";
$a = SchemaCheck::analyse(['code' => 1, 'output' => $e], null, []);
self::assertSame(['The database app does not exist.'], array_column($a['problems'], 'message'));
self::assertSame(['createDatabase', 'all'], $a['problems'][0]['fixes']);
$b = SchemaCheck::analyse(null, ['code' => 1, 'output' => 'SQLSTATE[HY000] [2002] Connection refused'], []);
self::assertSame('unreachable', $b['problems'][0]['code']);
self::assertSame(['recheck'], $b['problems'][0]['fixes']);
}
public function testAFullyMigratedProjectIsOk(): void
{
$a = SchemaCheck::analyse(['code' => 0, 'output' => self::out('list-migrated.txt')], ['code' => 0, 'output' => " [OK] Nothing to update - your database is already in sync with the current entity metadata.\n"], []);
self::assertSame('ok', $a['state']);
self::assertSame([], $a['problems']);
}
public function testAnErrorTheSiteShowedIsKeptWhenTheCheckFindsNothingElse(): void
{
$observed = SchemaCheck::classifyError("Table 'app.xxxxa' doesn't exist");
$ok = ['code' => 0, 'output' => ''];
$a = SchemaCheck::analyse($ok, $ok, [], $observed);
self::assertSame('The table xxxxa is missing: the site failed on it.', $a['problems'][0]['message']);
}
public function testTheFixesOfTheProblemsAndTheProductionGuard(): void
{
$problems = [['code' => 'no_database', 'fixes' => SchemaCheck::fixesFor('no_database')], ['code' => 'entity_without_table', 'fixes' => SchemaCheck::fixesFor('entity_without_table')]];
$dev = SchemaCheck::fixButtons($problems, false);
self::assertSame(['all', 'createDatabase', 'diff', 'openDoctrine'], array_column($dev, 'id'));
self::assertTrue($dev[0]['primary']);
self::assertSame('Fix everything', $dev[0]['label']);
self::assertSame(['createDatabase', 'diff', 'openDoctrine'], array_column(SchemaCheck::fixButtons($problems, true), 'id'), 'no "Fix everything" on a production database');
self::assertSame(['all', 'schemaUpdate', 'openDoctrine'], array_column(SchemaCheck::fixButtons([['code' => 'out_of_sync', 'fixes' => ['diff', 'openDoctrine', 'all']]], false, false, false), 'id'));
// the order of "Fix everything": the database, what is waiting, then what is missing and its migration
self::assertSame(['createDatabase', 'migrate', 'diff', 'migrate'], SchemaCheck::plan($problems));
self::assertSame(['migrate'], SchemaCheck::plan([['code' => 'pending_migrations']]));
self::assertSame(['schemaUpdate'], SchemaCheck::plan([['code' => 'out_of_sync']], false));
self::assertSame(['doctrine:database:create', '--if-not-exists'], SchemaCheck::argv('createDatabase', true));
}
public function testAProductionDatabaseIsNeverFixedWithoutItsName(): void
{
$root = $this->project(['.env' => 'DATABASE_URL="mysql://app:app@db:3306/shop"', '.jumphp/databases.json' => json_encode(['connections' => [
['id' => 'a1', 'name' => 'Shop live', 'driver' => 'mysql', 'host' => 'db', 'port' => 3306, 'user' => 'app', 'database' => 'shop', 'production' => true]]])]);
self::assertTrue(SchemaCheck::isProduction($root));
$ran = [];
$run = static function (array $argv) use (&$ran): Deferred {
$ran[] = $argv;
return Deferred::resolved(['code' => 0, 'output' => '']);
};
foreach ([['all', null], ['migrate', null], ['migrate', 'wrong']] as [$fix, $confirm]) {
try {
SchemaCheck::fix($root, $fix, $run, $confirm);
self::fail("$fix ran on production");
} catch (\RuntimeException $e) {
self::assertStringContainsString('production database', $e->getMessage());
}
}
self::assertSame([], $ran);
SchemaCheck::fix($root, 'migrate', $run, 'Shop live');
self::assertSame('doctrine:migrations:migrate', $ran[0][0]);
// APP_ENV=prod counts too
self::assertTrue(SchemaCheck::isProduction($this->project(['.env' => 'APP_ENV=dev', '.env.local' => 'APP_ENV=prod'])));
self::assertFalse(SchemaCheck::isProduction($this->project(['.env' => 'APP_ENV=dev'])));
}
/** a console that answers like a project whose entity has no table, then like one that was fixed */
private function fakeConsole(array &$log, bool &$fixed): \Closure
{
return static function (array $argv) use (&$log, &$fixed): Deferred {
$log[] = implode(' ', $argv);
if ($argv[0] === 'doctrine:migrations:migrate') {
$fixed = true;
}
$r = match ($argv[0]) {
'doctrine:migrations:list' => ['code' => 0, 'output' => $fixed ? (string)file_get_contents(self::CONSOLE . '/list-migrated.txt') : ''],
'doctrine:schema:update' => ['code' => 0, 'output' => $fixed ? "Nothing to update\n" : "CREATE TABLE xxxxa (id INT NOT NULL);\n"],
'doctrine:database:create', 'make:migration', 'doctrine:migrations:diff', 'doctrine:migrations:migrate' => ['code' => 0, 'output' => 'ok'],
default => ['code' => 1, 'output' => 'unknown'],
};
return Deferred::resolved($r);
};
}
public function testFixEverythingGeneratesAndMigratesThenChecksAgain(): void
{
$entity = "<?php\nnamespace App\\Entity;\nuse Doctrine\\ORM\\Mapping as ORM;\n#[ORM\\Entity]\nclass Xxxxa\n{\n #[ORM\\Id]\n #[ORM\\Column]\n private ?int \$id = null;\n}\n";
$root = $this->project(['composer.json' => '{}', 'migrations/.gitkeep' => '', 'src/Entity/Xxxxa.php' => $entity]);
$log = [];
$fixed = false;
$check = SchemaCheck::check($root, $this->fakeConsole($log, $fixed))->result();
self::assertSame('problems', $check['state']);
self::assertSame('The entity Xxxxa has no table: no migration creates it.', $check['problems'][0]['message']);
self::assertSame(['all', 'diff', 'openDoctrine'], array_column($check['fixes'], 'id'));
self::assertSame(['diff', 'migrate'], array_column($check['plan'], 'id'));
$log = [];
$r = SchemaCheck::fix($root, 'all', $this->fakeConsole($log, $fixed))->result();
self::assertSame(['diff', 'migrate'], array_column($r['steps'], 'step'));
self::assertSame('ok', $r['check']['state']);
self::assertTrue($r['ok']);
self::assertContains('doctrine:migrations:migrate latest --allow-no-migration', $log);
}
public function testTheCheckRunsWhenTheSiteIsReadyNotBefore(): void
{
$emitted = [];
$checks = 0;
$w = new SchemaWatcher(function (?array $observed) use (&$checks): Deferred {
$checks++;
return Deferred::resolved(['state' => 'problems', 'problems' => [['message' => 'x']]]);
}, function (string $e, array $p) use (&$emitted): void {
$emitted[] = [$e, $p['state'], $p['reason'] ?? null];
}, static fn (): bool => false, static fn (): float => 100.0);
$w->runStarted(7, ['id' => 'web:serve', 'kind' => 'web', 'command' => ['@jumphp', 'web:serve', '/p']]);
$w->runOutput(7, "[web] starting the containers...\n");
self::assertSame(0, $checks, 'the site is not ready yet: its database is still starting');
$w->runOutput(7, "[web] open http://localhost:8080\n");
self::assertSame(1, $checks);
self::assertSame([['doctrine.schema', 'checking', 'site'], ['doctrine.schema', 'problems', 'site']], $emitted);
$w->runOutput(7, "[web] open http://localhost:8080\n");
self::assertSame(1, $checks, 'once per run');
// a run that is not a site is not watched
$w->runStarted(8, ['id' => 'test', 'kind' => 'test', 'command' => ['phpunit']]);
$w->runOutput(8, "[web] open http://x\n");
self::assertSame(1, $checks);
// web:up ending well checks too
$w->runStarted(9, ['id' => 'web:up', 'kind' => 'tool', 'command' => ['@jumphp', 'web:up', '/p']]);
$w->runExited(9, 0);
self::assertSame(2, $checks);
}
public function testTheToggleTheProductionGuardAndTheEntityChangesAreRespected(): void
{
$checks = 0;
$emitted = [];
$production = false;
$now = 100.0;
$w = new SchemaWatcher(function () use (&$checks): Deferred {
$checks++;
return Deferred::resolved(['state' => 'ok', 'problems' => []]);
}, function (string $e, array $p) use (&$emitted): void {
$emitted[] = $p['state'];
}, function () use (&$production): bool {
return $production;
}, function () use (&$now): float {
return $now;
});
$w->filesChanged(['src/Controller/HomeController.php']);
self::assertSame(0, $checks);
$w->filesChanged(['src/Entity/Xxxxa.php']);
self::assertSame(1, $checks);
$w->filesChanged(['migrations/Version1.php']);
self::assertSame(1, $checks, 'two saves in a row make one check');
$now = 110.0;
$w->filesChanged(['migrations/Version1.php']);
self::assertSame(2, $checks);
$w->enabled = false;
$w->filesChanged(['src/Entity/Other.php']);
self::assertSame(2, $checks, 'the Settings toggle');
$w->enabled = true;
$production = true;
$now = 200.0;
$w->filesChanged(['src/Entity/Other.php']);
self::assertSame(2, $checks, 'never by itself on a production database');
self::assertSame('skipped', end($emitted));
}
public function testADoctrineErrorInTheSitesOutputMakesACheckWithTheError(): void
{
$seen = [];
$w = new SchemaWatcher(function (?array $observed) use (&$seen): Deferred {
$seen[] = $observed['table'] ?? $observed['database'] ?? null;
return Deferred::resolved(['state' => 'problems', 'problems' => [['message' => 'm']]]);
}, static function (): void {
}, static fn (): bool => false, static fn (): float => 1.0);
$w->runStarted(1, ['id' => 'web:serve', 'kind' => 'web', 'command' => ['x']]);
$w->runOutput(1, "[error] PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'app.xxxxa' doesn't exist\n");
self::assertSame(['xxxxa'], $seen);
$w->observe('<h1>Everything is fine</h1>');
self::assertCount(1, $seen);
$w->observe("HTTP 500 SQLSTATE[HY000] [1049] Unknown database 'app'");
self::assertSame(['xxxxa', 'app'], $seen);
}
public function testTheCommandsAreRegisteredWhenThereIsAConsole(): void
{
$names = [];
$watcher = DoctrineCommands::register(function (string $name) use (&$names): void {
$names[] = $name;
}, self::ROOT, static fn (array $p): Deferred => Deferred::resolved(['code' => 0, 'output' => '']), null, static function (): void {
});
self::assertInstanceOf(SchemaWatcher::class, $watcher);
foreach (['doctrine.schema.check', 'doctrine.schema.fix', 'doctrine.schema.auto', 'doctrine.schema.observe'] as $n) {
self::assertContains($n, $names);
}
}
}