rob-revisited/ide/tests/FixturesTest.php

273 lines
16 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Fixtures\FakerCatalog;
use JumPHP\Ide\Fixtures\FixtureCommands;
use JumPHP\Ide\Fixtures\FixtureGenerator;
use PHPUnit\Framework\TestCase;
/**
* The fixtures form's core (ide/src/Fixtures): Faker fixtures and Foundry factories + stories written from a model (exact texts in
* tests/fixtures/fixtures-expected), the load order computed from the relations, an existing fixture read back and edited with every
* byte outside the form's regions kept, the packages to install, and the guards of a load.
*/
final class FixturesTest extends TestCase
{
private const EXPECTED = __DIR__ . '/fixtures/fixtures-expected';
private string $tmp = '';
protected function tearDown(): void
{
if ($this->tmp !== '') {
exec('rm -rf ' . escapeshellarg($this->tmp));
}
}
private function assertSameAsExpected(string $file, string $actual): void
{
if (is_file(self::EXPECTED . '/.write')) {
@mkdir(dirname(self::EXPECTED . "/$file"), 0777, true);
file_put_contents(self::EXPECTED . "/$file", $actual);
}
self::assertFileExists(self::EXPECTED . "/$file");
self::assertSame((string)file_get_contents(self::EXPECTED . "/$file"), $actual, $file);
}
/** a temporary project with a few files */
private function project(array $files = []): string
{
$this->tmp = sys_get_temp_dir() . '/fixtures-test-' . getmypid() . '-' . uniqid();
mkdir($this->tmp);
file_put_contents("$this->tmp/composer.json", json_encode(['require' => ['symfony/framework-bundle' => '^7.1', 'doctrine/orm' => '^3.0'], 'autoload' => ['psr-4' => ['App\\' => 'src/']]]));
foreach ($files as $path => $content) {
@mkdir(dirname("$this->tmp/$path"), 0777, true);
file_put_contents("$this->tmp/$path", $content);
}
return $this->tmp;
}
/** @return array<string, mixed> */
private function post(string $kind = 'faker'): array
{
return FixtureGenerator::normalize(['entity' => 'App\\Entity\\Post', 'kind' => $kind, 'count' => 12, 'groups' => ['dev', 'demo'], 'seed' => 7, 'fields' => [
['name' => 'title', 'generator' => ['type' => 'faker', 'formatter' => 'sentence', 'args' => [4]]],
['name' => 'slug', 'generator' => ['type' => 'sequence', 'pattern' => 'post-{n}']],
['name' => 'price', 'generator' => ['type' => 'between', 'min' => 1, 'max' => 500, 'float' => true, 'decimals' => 2, 'cast' => 'string']],
['name' => 'views', 'generator' => ['type' => 'between', 'min' => 0, 'max' => 9999]],
['name' => 'online', 'generator' => ['type' => 'boolean', 'chance' => 80]],
['name' => 'status', 'generator' => ['type' => 'enum', 'class' => 'App\\Enum\\Status', 'mode' => 'random']],
['name' => 'kind', 'generator' => ['type' => 'enum', 'class' => 'App\\Enum\\Status', 'mode' => 'case', 'case' => 'Draft']],
['name' => 'createdAt', 'generator' => ['type' => 'dateBetween', 'from' => '-1 year', 'to' => 'now', 'immutable' => true]],
['name' => 'note', 'generator' => ['type' => 'null']],
['name' => 'internal', 'generator' => ['type' => 'skip']],
['name' => 'author', 'generator' => ['type' => 'ref', 'target' => 'App\\Entity\\User', 'mode' => 'random']],
['name' => 'editor', 'generator' => ['type' => 'ref', 'target' => 'App\\Entity\\User', 'mode' => 'index', 'index' => 2]],
['name' => 'tags', 'generator' => ['type' => 'refs', 'target' => 'App\\Entity\\Tag', 'min' => 1, 'max' => 3]],
]], ['App\\Entity\\Tag' => 'App\\DataFixtures\\TagFixtures']);
}
public function testAFakerFixtureIsWrittenFromTheModel(): void
{
$files = FixtureGenerator::files($this->post());
self::assertSame(['src/DataFixtures/PostFixtures.php'], array_keys($files));
$this->assertSameAsExpected('faker/PostFixtures.php', $files['src/DataFixtures/PostFixtures.php']);
}
public function testAFoundryFactoryAStoryAndTheFixtureThatLoadsItAreWritten(): void
{
$files = FixtureGenerator::files($this->post('foundry'));
self::assertSame(['src/Factory/PostFactory.php', 'src/Story/PostStory.php', 'src/DataFixtures/PostFixtures.php'], array_keys($files));
foreach ($files as $path => $code) {
$this->assertSameAsExpected('foundry/' . basename($path), $code);
}
}
public function testASelfReferenceOnlyPointsAtTheObjectsAlreadyMade(): void
{
$m = FixtureGenerator::normalize(['entity' => 'App\\Entity\\Category', 'count' => 5, 'fields' => [
['name' => 'name', 'generator' => ['type' => 'faker', 'formatter' => 'word', 'args' => []]],
['name' => 'parent', 'generator' => ['type' => 'ref', 'target' => 'App\\Entity\\Category', 'mode' => 'random']]]]);
$code = FixtureGenerator::files($m)['src/DataFixtures/CategoryFixtures.php'];
self::assertSame([], $m['dependencies']);
self::assertStringContainsString('$category->setParent($i > 0 ? $this->getReference(self::REFERENCE_PREFIX . $faker->numberBetween(0, $i - 1), Category::class) : null);', $code);
self::assertStringContainsString('return [];', $code);
}
public function testTheLoadOrderComesFromTheRelations(): void
{
self::assertSame($this->post()['dependencies'], ['App\\DataFixtures\\UserFixtures', 'App\\DataFixtures\\TagFixtures']);
$order = FixtureGenerator::order(['Post' => ['User', 'Tag'], 'User' => [], 'Tag' => ['User'], 'Comment' => ['Post', 'User']]);
self::assertSame(['User', 'Tag', 'Post', 'Comment'], array_values($order['order']));
self::assertSame([], $order['cycles']);
$cycle = FixtureGenerator::order(['A' => ['B'], 'B' => ['A'], 'C' => []]);
self::assertSame(['C'], $cycle['order']);
self::assertSame(['A', 'B'], $cycle['cycles']);
}
public function testAnExistingFixtureIsReadBackIntoItsModel(): void
{
$m = $this->post();
$code = FixtureGenerator::files($m)['src/DataFixtures/PostFixtures.php'];
self::assertSame($m, FixtureGenerator::read($code));
self::assertNull(FixtureGenerator::read("<?php\nclass X {}\n"));
}
public function testEditingChangesTheRegionsAndNothingElse(): void
{
$m = $this->post();
$code = FixtureGenerator::files($m)['src/DataFixtures/PostFixtures.php'];
// somebody added things by hand
$mine = str_replace(" public function getDependencies(): array", " /** my own helper */\n private function extra(): int\n {\n return 42;\n }\n\n public function getDependencies(): array", $code);
$mine = str_replace("use Doctrine\\Persistence\\ObjectManager;\n", "use Doctrine\\Persistence\\ObjectManager;\nuse Psr\\Log\\LoggerInterface;\n", $mine);
$changed = $m;
$changed['count'] = 40;
$changed['groups'] = ['dev'];
$changed['fields'][0]['generator'] = ['type' => 'fixed', 'value' => "it's fixed"];
$changed = FixtureGenerator::normalize($changed, ['App\\Entity\\Tag' => 'App\\DataFixtures\\TagFixtures']);
$after = FixtureGenerator::files($changed, ['src/DataFixtures/PostFixtures.php' => $mine])['src/DataFixtures/PostFixtures.php'];
self::assertStringContainsString('public const COUNT = 40;', $after);
self::assertStringContainsString("\$post->setTitle('it\\'s fixed');", $after);
self::assertStringContainsString("return ['dev'];", $after);
self::assertStringContainsString('private function extra(): int', $after);
self::assertStringContainsString('use Psr\\Log\\LoggerInterface;', $after);
// outside the regions every byte is the same
$blank = fn (string $c) => preg_replace('/^([ \t]*)\/\/ jumphp:begin (\w+).*?^\1\/\/ jumphp:end \2$/ms', '$1// region $2', $c);
self::assertSame($blank($mine), $blank($after));
// and the model is the new one
self::assertSame(40, FixtureGenerator::read($after)['count']);
// editing with the same model changes nothing at all
self::assertSame($mine, FixtureGenerator::files($m, ['src/DataFixtures/PostFixtures.php' => $mine])['src/DataFixtures/PostFixtures.php']);
}
public function testAFileTheFormDidNotMakeIsNeverRewritten(): void
{
$this->expectException(\InvalidArgumentException::class);
FixtureGenerator::files($this->post(), ['src/DataFixtures/PostFixtures.php' => "<?php\nclass PostFixtures {}\n"]);
}
public function testFoundryRegionsAreEditedInTheFactoryAndTheStory(): void
{
$m = $this->post('foundry');
$files = FixtureGenerator::files($m);
$m['count'] = 3;
$after = FixtureGenerator::files(FixtureGenerator::normalize($m), $files);
self::assertStringContainsString("PostFactory::createMany(3, static fn (int \$i): array => ['slug' => 'post-' . \$i]);", $after['src/Story/PostStory.php']);
self::assertSame($files['src/Factory/PostFactory.php'], $after['src/Factory/PostFactory.php']);
}
public function testTheGeneratorsKnowTheirColumns(): void
{
self::assertSame(['type' => 'faker', 'formatter' => 'email', 'args' => []], FakerCatalog::suggest('contactEmail', 'string'));
self::assertSame('paragraph', FakerCatalog::suggest('description', 'text')['formatter']);
self::assertSame(['type' => 'between', 'min' => 1, 'max' => 100], FakerCatalog::suggest('stock', 'integer'));
self::assertSame('string', FakerCatalog::suggest('price', 'decimal')['cast']);
self::assertSame(['type' => 'boolean', 'chance' => 50], FakerCatalog::suggest('active', 'boolean'));
self::assertTrue(FakerCatalog::suggest('createdAt', 'datetime_immutable')['immutable']);
$names = array_column(FakerCatalog::all(), 'name');
self::assertContains('numberBetween', $names);
foreach (FakerCatalog::all() as $f) {
self::assertNotEmpty($f['samples'], $f['name']);
}
}
public function testTheProjectsEntitiesComeWithASuggestedGeneratorPerField(): void
{
$info = FixtureCommands::info(__DIR__ . '/fixtures/doctrine', true);
$post = current(array_filter($info['entities'], fn ($e) => $e['name'] === 'Post'));
$fields = array_column($post['fields'], null, 'name');
self::assertSame(['type' => 'skip'], $fields['id']['suggest']);
self::assertSame('sentence', $fields['title']['suggest']['formatter']);
self::assertSame(['type' => 'enum', 'class' => 'App\\Enum\\Status', 'mode' => 'random'], $fields['status']['suggest']);
self::assertSame('ref', $fields['author']['suggest']['type']);
self::assertSame('refs', $fields['tags']['suggest']['type']);
self::assertArrayNotHasKey('comments', $fields, 'the inverse side is not set from the fixture');
self::assertSame('App', $info['rootNamespace']);
self::assertSame('faker', $info['kind']);
}
public function testThePackagesToInstallAreOfferedAsDevDependencies(): void
{
$root = $this->project();
$plan = FixtureCommands::installPlan($root);
self::assertFalse($plan['bundle']['installed']);
self::assertSame('composer require doctrine/doctrine-fixtures-bundle --dev', $plan['bundle']['command']);
self::assertSame('composer require fakerphp/faker --dev', $plan['faker']['command']);
self::assertSame('composer require zenstruck/foundry --dev', $plan['foundry']['command']);
file_put_contents("$root/composer.json", json_encode(['require-dev' => ['doctrine/doctrine-fixtures-bundle' => '^4', 'zenstruck/foundry' => '^2']]));
$plan = FixtureCommands::installPlan($root);
self::assertTrue($plan['bundle']['installed']);
self::assertTrue($plan['foundry']['installed']);
self::assertFalse($plan['faker']['installed']);
self::assertSame('foundry', FixtureCommands::info($root, false)['kind']);
}
public function testFixturesAreNeverLoadedInProduction(): void
{
$root = $this->project([".env" => "APP_ENV=dev\nDATABASE_URL=\"mysql://u:[email protected]:3306/shop\"\n"]);
self::assertFalse(FixtureCommands::guard($root)['blocked']);
file_put_contents("$root/.env.local", "APP_ENV=prod\n");
$g = FixtureCommands::guard($root);
self::assertTrue($g['blocked']);
self::assertStringContainsString('APP_ENV=prod', $g['reason']);
unlink("$root/.env.local");
// a connection of the Database window flagged production, the one DATABASE_URL points at
@mkdir("$root/.jumphp");
file_put_contents("$root/.jumphp/databases.json", json_encode(['connections' => [['id' => 'a1', 'name' => 'Shop live', 'driver' => 'mysql', 'host' => 'db.example.org', 'user' => 'u', 'database' => 'shop', 'production' => true]]]));
$g = FixtureCommands::guard($root);
self::assertTrue($g['blocked']);
self::assertSame('Shop live', $g['connection']);
// the load itself is refused too, not only the form
$handlers = [];
FixtureCommands::register(function (string $name, callable $h) use (&$handlers) { $handlers[$name] = $h; }, $root, fn () => ['code' => 0, 'output' => ''], null);
$this->expectException(\RuntimeException::class);
$handlers['fixtures.load'](['mode' => 'append']);
}
public function testTheLoadCommandAppendsOrPurgesByGroup(): void
{
$root = $this->project([".env" => "APP_ENV=dev\n"]);
$plan = FixtureCommands::loadPlan($root, ['mode' => 'append', 'groups' => ['dev', 'bad group!', 'demo']]);
self::assertSame(['doctrine:fixtures:load', '--no-interaction', '--append', '--group=dev', '--group=demo'], $plan['argv']);
$plan = FixtureCommands::loadPlan($root, ['mode' => 'purge', 'group' => 'demo']);
self::assertSame(['doctrine:fixtures:load', '--no-interaction', '--group=demo'], $plan['argv']);
$ran = [];
$handlers = [];
FixtureCommands::register(function (string $name, callable $h) use (&$handlers) { $handlers[$name] = $h; }, $root, function (array $p) use (&$ran) { $ran[] = $p; return ['code' => 0, 'output' => 'ok']; }, null);
try {
$handlers['fixtures.load'](['mode' => 'purge']);
self::fail('a purge needs its confirmation');
} catch (\RuntimeException) {
}
$r = $handlers['fixtures.load'](['mode' => 'purge', 'confirmPurge' => true, 'groups' => ['dev']]);
self::assertInstanceOf(Deferred::class, $r);
self::assertSame([['argv' => ['doctrine:fixtures:load', '--no-interaction', '--group=dev']]], $ran);
}
public function testThePreviewTellsWhichFixturesAreStillToMake(): void
{
$root = $this->project();
$handlers = [];
FixtureCommands::register(function (string $name, callable $h) use (&$handlers) { $handlers[$name] = $h; }, $root, null, null);
$r = $handlers['fixtures.preview'](['model' => $this->post()]);
self::assertSame(['src/DataFixtures/PostFixtures.php'], array_column($r['changes'], 'file'));
self::assertNull($r['changes'][0]['before']);
self::assertSame(['App\\DataFixtures\\UserFixtures', 'App\\DataFixtures\\TagFixtures'], $r['missing']);
}
public function testThePreviewScriptPrintsRowsFromTheProjectsOwnFaker(): void
{
$script = FixtureGenerator::previewScript($this->post(), 3);
self::assertStringContainsString("\$faker = \\Faker\\Factory::create('en_US');\n\$faker->seed(7);", $script);
self::assertStringContainsString('for ($i = 0; $i < 3; $i++)', $script);
self::assertStringContainsString("'author' => '-> User (random)',", $script);
self::assertStringContainsString("'status' => \$faker->randomElement(\\App\\Enum\\Status::cases())->name,", $script);
self::assertStringNotContainsString("'internal'", $script);
$php = PHP_BINARY;
file_put_contents($f = sys_get_temp_dir() . '/jumphp-preview-lint.php', $script);
exec(escapeshellarg($php) . ' -l ' . escapeshellarg($f) . ' 2>&1', $out, $code);
unlink($f);
self::assertSame(0, $code, implode("\n", $out));
}
}