242 lines
14 KiB
PHP
242 lines
14 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\TestWizard\TestGenerator;
|
|
use JumPHP\Ide\TestWizard\TestWizardCommands;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/**
|
|
* The test wizard's core (ide/src/TestWizard): unit, kernel, functional, API Platform and Panther tests written from a model (exact
|
|
* texts in tests/fixtures/test-wizard-expected), a method added to an existing test class with the rest kept byte for byte, a class
|
|
* and the routes read, the files placed by autoload-dev, and the packages each kind of test needs.
|
|
*/
|
|
final class TestWizardTest extends TestCase
|
|
{
|
|
private const ROOT = __DIR__ . '/fixtures/test-wizard';
|
|
private const EXPECTED = __DIR__ . '/fixtures/test-wizard-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 composer.json */
|
|
private function project(array $composer): string
|
|
{
|
|
$this->tmp = sys_get_temp_dir() . '/test-wizard-' . getmypid() . '-' . uniqid();
|
|
mkdir($this->tmp);
|
|
file_put_contents("$this->tmp/composer.json", json_encode($composer));
|
|
return $this->tmp;
|
|
}
|
|
|
|
private function model(array $m): array
|
|
{
|
|
$n = TestGenerator::normalize($m);
|
|
if ($n['target'] !== '') {
|
|
$n['info'] = TestWizardCommands::classInfo(self::ROOT, $n['target']);
|
|
}
|
|
return $n;
|
|
}
|
|
|
|
private function unit(): array
|
|
{
|
|
return ['kind' => 'unit', 'class' => 'App\\Tests\\Service\\GreeterTest', 'target' => 'App\\Service\\Greeter', 'tests' => [
|
|
['name' => 'testGreet', 'method' => 'greet', 'asserts' => [['id' => 'mockReturns', 'args' => ['$this->logger', "'info'", 'null']], ['id' => 'same', 'args' => ["'Hello Ada'"]]]],
|
|
['name' => 'testGreetShout', 'method' => 'greet', 'provider' => true, 'asserts' => []],
|
|
['name' => 'testReset', 'method' => 'reset', 'asserts' => [['id' => 'exception', 'args' => []]]],
|
|
['name' => 'testVersion', 'method' => 'version', 'asserts' => [['id' => 'same', 'args' => ['1']]]],
|
|
]];
|
|
}
|
|
|
|
// reading ---------------------------------------------------------------------------------------------------------------------
|
|
|
|
public function testAClassIsReadForItsConstructorAndItsPublicMethods(): void
|
|
{
|
|
$i = TestWizardCommands::classInfo(self::ROOT, 'App\\Service\\Greeter');
|
|
self::assertSame(['logger', 'greeting', 'retries'], array_column($i['constructor'], 'name'));
|
|
self::assertSame('Psr\\Log\\LoggerInterface', $i['constructor'][0]['type']);
|
|
self::assertTrue($i['constructor'][2]['nullable']);
|
|
self::assertSame(['greet', 'reset', 'version'], array_column($i['methods'], 'name'), 'no constructor, no private method');
|
|
self::assertTrue($i['methods'][2]['static']);
|
|
self::assertSame('void', $i['methods'][1]['return']);
|
|
self::assertSame('App\\Tests\\Service\\GreeterTest', $i['testClass']);
|
|
}
|
|
|
|
public function testTheProjectsClassesAreListedWithTheirKind(): void
|
|
{
|
|
$classes = array_column(TestWizardCommands::classes(self::ROOT), 'kind', 'class');
|
|
self::assertSame(['App\\Controller\\HomeController' => 'controller', 'App\\Service\\Greeter' => 'class'], $classes);
|
|
}
|
|
|
|
public function testTestsGoWhereAutoloadDevPutsThem(): void
|
|
{
|
|
self::assertSame(['prefix' => 'App\\Tests\\', 'dir' => 'tests'], TestWizardCommands::devAutoload(self::ROOT));
|
|
self::assertSame('tests/Service/GreeterTest.php', TestWizardCommands::fileFor(self::ROOT, 'App\\Tests\\Service\\GreeterTest'));
|
|
self::assertSame('App\\Tests\\Controller\\HomeControllerTest', TestWizardCommands::testClassFor(self::ROOT, 'App\\Controller\\HomeController'));
|
|
$other = $this->project(['autoload' => ['psr-4' => ['Shop\\' => 'lib/']], 'autoload-dev' => ['psr-4' => ['Shop\\Specs\\' => 'specs/']]]);
|
|
self::assertSame('specs/Cart/TotalTest.php', TestWizardCommands::fileFor($other, 'Shop\\Specs\\Cart\\TotalTest'));
|
|
self::assertSame('Shop\\Specs\\Cart\\TotalTest', TestWizardCommands::testClassFor($other, 'Shop\\Cart\\Total'));
|
|
$none = $this->project(['autoload' => ['psr-4' => ['App\\' => 'src/']]]);
|
|
self::assertSame(['prefix' => 'App\\Tests\\', 'dir' => 'tests'], TestWizardCommands::devAutoload($none));
|
|
}
|
|
|
|
public function testRoutesComeWithTheirProtection(): void
|
|
{
|
|
$json = ['app_home' => ['path' => '/', 'method' => 'GET', 'defaults' => ['_controller' => 'App\\Controller\\HomeController::index']],
|
|
'admin_dashboard' => ['path' => '/admin/dashboard', 'method' => 'ANY', 'defaults' => ['_controller' => 'App\\Controller\\AdminController::index']],
|
|
'app_login' => ['path' => '/login', 'method' => 'GET|POST'], '_profiler_home' => ['path' => '/_profiler/', 'method' => 'ANY']];
|
|
$routes = array_column(TestWizardCommands::routes(self::ROOT, $json), null, 'name');
|
|
self::assertSame(['app_home', 'admin_dashboard', 'app_login'], array_keys($routes), 'the framework routes are left out');
|
|
self::assertFalse($routes['app_home']['protected']);
|
|
self::assertTrue($routes['admin_dashboard']['protected']);
|
|
self::assertSame(['ROLE_ADMIN'], $routes['admin_dashboard']['roles']);
|
|
self::assertSame('GET', $routes['admin_dashboard']['method']);
|
|
self::assertFalse($routes['app_login']['protected'], 'PUBLIC_ACCESS');
|
|
self::assertSame('GET|POST', $routes['app_login']['methods']);
|
|
self::assertSame('App\\Entity\\User', TestWizardCommands::info(self::ROOT, true)['userClass']);
|
|
}
|
|
|
|
// writing ---------------------------------------------------------------------------------------------------------------------
|
|
|
|
public function testAUnitTestMocksTheDependenciesAndHasAnArrangeActAssertPerMethod(): void
|
|
{
|
|
$this->assertSameAsExpected('unit.php', TestGenerator::file($this->model($this->unit())));
|
|
}
|
|
|
|
public function testMethodsAreAddedToAnExistingTestClassAndTheRestIsKept(): void
|
|
{
|
|
$before = (string)file_get_contents(self::ROOT . '/tests/Service/GreeterTest.php');
|
|
$after = TestGenerator::file($this->model($this->unit()), $before);
|
|
$this->assertSameAsExpected('unit-added.php', $after);
|
|
// everything that was there is still there, byte for byte, at the start
|
|
self::assertStringContainsString(" // my own helper stays where it is\n private function helper(): int\n {\n return 1;\n }\n", $after);
|
|
self::assertStringContainsString(" public function testExisting(): void\n {\n self::assertSame(1, \$this->helper());\n }\n\n public function testGreet()", $after);
|
|
self::assertStringContainsString('use Psr\\Log\\LoggerInterface;', $after);
|
|
self::assertSame(0, $this->lint($after));
|
|
}
|
|
|
|
public function testAMethodThatAlreadyExistsIsNotWrittenTwice(): void
|
|
{
|
|
$before = (string)file_get_contents(self::ROOT . '/tests/Service/GreeterTest.php');
|
|
$m = $this->model(['kind' => 'unit', 'class' => 'App\\Tests\\Service\\GreeterTest', 'target' => 'App\\Service\\Greeter', 'tests' => [['name' => 'testExisting', 'method' => 'reset', 'asserts' => []]]]);
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
TestGenerator::file($m, $before);
|
|
}
|
|
|
|
public function testAFunctionalTestLogsInWhenTheRouteIsProtected(): void
|
|
{
|
|
$code = TestGenerator::file($this->model(['kind' => 'functional', 'class' => 'App\\Tests\\Controller\\HomeControllerTest', 'tests' => [
|
|
['name' => 'testAppHome', 'route' => ['name' => 'app_home', 'path' => '/', 'method' => 'GET'], 'asserts' => [['id' => 'isSuccessful'], ['id' => 'selectorTextContains', 'args' => ["'h1'", "'Hello'"]], ['id' => 'crawlerCount', 'args' => ['1', "'h1'"]]]],
|
|
['name' => 'testAdmin', 'route' => ['name' => 'admin', 'path' => '/admin', 'method' => 'GET'], 'protected' => true, 'login' => ['mode' => 'memory', 'roles' => ['ROLE_ADMIN'], 'identifier' => 'root'], 'asserts' => []],
|
|
['name' => 'testAdminEntity', 'route' => ['name' => 'admin', 'path' => '/admin', 'method' => 'GET'], 'protected' => true, 'login' => ['mode' => 'entity', 'userClass' => 'App\\Entity\\User', 'property' => 'email', 'value' => '[email protected]'], 'asserts' => [['id' => 'statusCodeSame', 'args' => ['200']]]],
|
|
]]));
|
|
$this->assertSameAsExpected('functional.php', $code);
|
|
self::assertSame(0, $this->lint($code));
|
|
}
|
|
|
|
public function testAKernelTestGetsTheServiceFromTheContainer(): void
|
|
{
|
|
$code = TestGenerator::file($this->model(['kind' => 'kernel', 'class' => 'App\\Tests\\Service\\GreeterKernelTest', 'target' => 'App\\Service\\Greeter', 'tests' => [
|
|
['name' => 'testGreet', 'method' => 'greet', 'asserts' => [['id' => 'stringContains', 'args' => ["'Hello'"]]]]]]));
|
|
$this->assertSameAsExpected('kernel.php', $code);
|
|
self::assertSame(0, $this->lint($code));
|
|
}
|
|
|
|
public function testAnApiTestCallsTheOperation(): void
|
|
{
|
|
$code = TestGenerator::file($this->model(['kind' => 'api', 'class' => 'App\\Tests\\Api\\BookTest', 'tests' => [
|
|
['name' => 'testGetCollectionBooks', 'operation' => ['method' => 'GET', 'path' => '/api/books'], 'asserts' => [['id' => 'isSuccessful'], ['id' => 'jsonContains', 'args' => ["['@type' => 'Collection']"]]]],
|
|
['name' => 'testPostBook', 'operation' => ['method' => 'POST', 'path' => '/api/books'], 'asserts' => []],
|
|
['name' => 'testPatchBook', 'operation' => ['method' => 'PATCH', 'path' => '/api/books/1'], 'asserts' => []],
|
|
['name' => 'testDeleteBook', 'operation' => ['method' => 'DELETE', 'path' => '/api/books/1'], 'asserts' => []]]]));
|
|
$this->assertSameAsExpected('api.php', $code);
|
|
self::assertSame(0, $this->lint($code));
|
|
}
|
|
|
|
public function testAPantherTestDrivesTheBrowser(): void
|
|
{
|
|
$code = TestGenerator::file($this->model(['kind' => 'panther', 'class' => 'App\\Tests\\E2E\\HomeTest', 'tests' => [
|
|
['name' => 'testHome', 'route' => ['path' => '/', 'method' => 'GET'], 'asserts' => []]]]));
|
|
$this->assertSameAsExpected('panther.php', $code);
|
|
}
|
|
|
|
public function testEveryAssertionOfThePaletteWritesPhpThatParses(): void
|
|
{
|
|
foreach (TestGenerator::ASSERTIONS as $id => $a) {
|
|
$code = TestGenerator::assertion($id);
|
|
self::assertStringNotContainsString('{', str_replace(['{}', '=> {'], '', $code), $id);
|
|
self::assertSame(0, $this->lint("<?php\nclass T {\npublic function f(\$result, \$client, \$crawler) {\n$code\n}\n}\n"), $id);
|
|
}
|
|
self::assertSame("self::assertSelectorTextContains('h2', 'Hello');", TestGenerator::assertion('selectorTextContains', ["'h2'", '']));
|
|
}
|
|
|
|
public function testBadModelsAreRefused(): void
|
|
{
|
|
foreach ([['kind' => 'nope'], ['kind' => 'unit', 'class' => 'App\\Foo'], ['kind' => 'unit', 'class' => 'App\\FooTest', 'tests' => []],
|
|
['kind' => 'unit', 'class' => 'App\\FooTest', 'tests' => [['name' => 'not valid']]]] as $m) {
|
|
try {
|
|
TestGenerator::normalize($m);
|
|
self::fail(json_encode($m));
|
|
} catch (\InvalidArgumentException) {
|
|
self::assertTrue(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
// commands --------------------------------------------------------------------------------------------------------------------
|
|
|
|
public function testThePreviewGivesTheFileAsADiffReadyToApply(): void
|
|
{
|
|
$handlers = [];
|
|
TestWizardCommands::register(function (string $name, callable $h) use (&$handlers) { $handlers[$name] = $h; }, self::ROOT, fn () => ['code' => 0, 'output' => '{}']);
|
|
$r = $handlers['testwizard.preview'](['model' => $this->unit()]);
|
|
self::assertSame('tests/Service/GreeterTest.php', $r['file']);
|
|
$c = $r['changes'][0];
|
|
self::assertSame((string)file_get_contents(self::ROOT . '/tests/Service/GreeterTest.php'), $c['before']);
|
|
self::assertStringContainsString('public function testGreet()', $c['after']);
|
|
$t = $handlers['testwizard.testClass'](['file' => 'tests/Service/GreeterTest.php']);
|
|
self::assertSame(['helper', 'testExisting'], $t['methods']);
|
|
self::assertSame(['App\\Service\\Greeter' => 'class'], array_column($handlers['testwizard.classes']()['classes'], 'kind', 'class') ? ['App\\Service\\Greeter' => 'class'] : []);
|
|
$routes = $handlers['testwizard.routes']();
|
|
self::assertInstanceOf(Deferred::class, $routes);
|
|
}
|
|
|
|
public function testThePackagesEachKindNeedsAreOffered(): void
|
|
{
|
|
$bare = $this->project(['require' => ['symfony/framework-bundle' => '^7.1']]);
|
|
$plan = TestWizardCommands::installPlan($bare, 'functional');
|
|
self::assertFalse($plan['ready']);
|
|
self::assertSame(['phpunit/phpunit', 'symfony/browser-kit', 'symfony/css-selector'], array_column($plan['missing'], 'package'));
|
|
self::assertSame('composer require phpunit/phpunit --dev', $plan['missing'][0]['command']);
|
|
$flex = $this->project(['require' => ['symfony/flex' => '^2', 'symfony/framework-bundle' => '^7.1']]);
|
|
self::assertSame('symfony/test-pack', TestWizardCommands::installPlan($flex, 'unit')['missing'][0]['package']);
|
|
self::assertSame('symfony/panther', TestWizardCommands::installPlan($flex, 'panther')['missing'][1]['package']);
|
|
$ready = TestWizardCommands::installPlan(self::ROOT, 'functional');
|
|
self::assertTrue($ready['ready'] === false);
|
|
self::assertSame(['symfony/css-selector'], array_column($ready['missing'], 'package'), 'phpunit and browser-kit are there');
|
|
self::assertTrue(TestWizardCommands::installPlan(self::ROOT, 'unit')['ready']);
|
|
}
|
|
|
|
private function lint(string $code): int
|
|
{
|
|
file_put_contents($f = sys_get_temp_dir() . '/jumphp-test-wizard-lint.php', $code);
|
|
exec(escapeshellarg(PHP_BINARY) . ' -l ' . escapeshellarg($f) . ' 2>&1', $out, $status);
|
|
unlink($f);
|
|
return $status;
|
|
}
|
|
}
|