rob-revisited/ide/tests/UnitTestsWindowTest.php

256 lines
18 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\UnitTests\Clover;
use JumPHP\Ide\UnitTests\Diff;
use JumPHP\Ide\UnitTests\JUnit;
use JumPHP\Ide\UnitTests\TeamCity;
use JumPHP\Ide\UnitTests\TestCommand;
use JumPHP\Ide\UnitTests\TestDiscovery;
use JumPHP\Ide\Workspace\MemoryWorkspace;
use PHPUnit\Framework\TestCase;
/** The Tests window's core: tests found by reading the files, the commands per kind of project, the reports read. */
final class UnitTestsWindowTest extends TestCase
{
private const CALC = <<<'PHP'
<?php
namespace App\Tests\Unit;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
final class CalcTest extends TestCase
{
public function testAddition(): void {}
#[Test]
public function arraysAreCompared(): void {}
#[DataProvider('sums')]
public function testSums(int $a): void {}
#[TestWith([1])]
#[TestWith([2])]
public function testWith(int $a): void {}
/** @test */
public function viaDocblock(): void {}
/** @dataProvider rows */
public function testRows(): void {}
public static function sums(): array { return []; }
public function helper(): void {}
private function testPrivate(): void {}
}
abstract class BaseTest extends TestCase
{
public function testInherited(): void {}
}
PHP;
private function sfProject(): MemoryWorkspace
{
return new MemoryWorkspace([
'composer.json' => '{"require-dev": {"phpunit/phpunit": "^11"}}',
'phpunit.dist.xml' => '<phpunit><testsuites><testsuite name="Unit"><directory>tests/Unit</directory></testsuite>'
. '<testsuite name="Other"><directory suffix="Check.php">tests/Other</directory><file>tests/Single.php</file><exclude>tests/Other/Skip</exclude></testsuite>'
. '</testsuites><source><include><directory>src</directory></include></source></phpunit>',
'tests/Unit/CalcTest.php' => self::CALC,
'tests/Unit/NotATest.php' => '<?php class Helper {}',
'tests/Other/FooCheck.php' => "<?php\nnamespace T;\nfinal class FooCheck extends \\PHPUnit\\Framework\\TestCase { public function testFoo(): void {} }",
'tests/Other/Skip/BarCheck.php' => "<?php\nfinal class BarCheck extends \\PHPUnit\\Framework\\TestCase { public function testBar(): void {} }",
'tests/Single.php' => "<?php\nfinal class SingleTest extends \\PHPUnit\\Framework\\TestCase { public function testOne(): void {} }",
'src/Kernel.php' => '<?php class Kernel {}',
], 'testSF');
}
public function testPhpunitSuitesFilesClassesAndMethodsAreFoundWithoutRunningAnything(): void
{
$scopes = (new TestDiscovery($this->sfProject()))->scopes();
self::assertCount(1, $scopes);
$scope = $scopes[0];
self::assertSame(['phpunit:', 'phpunit', 'testSF', 'phpunit.dist.xml', true], [$scope['id'], $scope['type'], $scope['label'], $scope['config'], $scope['source']]);
self::assertSame(['Unit', 'Other'], array_column($scope['suites'], 'name'));
self::assertSame(['tests/Unit/CalcTest.php'], array_column($scope['suites'][0]['files'], 'path'));
self::assertSame(['tests/Other/FooCheck.php', 'tests/Single.php'], array_column($scope['suites'][1]['files'], 'path'), 'suffix, <file>, <exclude>');
$class = $scope['suites'][0]['files'][0]['classes'][0];
self::assertSame(['App\Tests\Unit\CalcTest', 'CalcTest', 9], [$class['name'], $class['short'], $class['line']]);
$methods = array_column($class['methods'], null, 'name');
self::assertSame(['testAddition', 'arraysAreCompared', 'testSums', 'testWith', 'viaDocblock', 'testRows'], array_keys($methods), 'test*, #[Test], @test; not helpers, private or abstract classes');
self::assertSame('App\Tests\Unit\CalcTest::testSums', $methods['testSums']['id']);
self::assertSame('sums', $methods['testSums']['provider']);
self::assertSame('rows', $methods['testRows']['provider']);
self::assertSame(2, $methods['testWith']['sets']);
self::assertSame(17, $methods['testSums']['line']);
}
public function testJumphpGameTestsAndPestAndJavascriptAreFound(): void
{
$ws = new MemoryWorkspace([
'bin/jumphp' => '#!/bin/sh',
'games/pong/config/project.yaml' => "project:\n id: pong\n",
'games/pong/tests/PaddleTest.php' => "<?php\nnamespace Tests;\nuse JumPHP\\Testing\\GameTestCase;\nfinal class PaddleTest extends GameTestCase { public function testMoves(): void {} }",
'games/pong/tests/PlayBase.php' => "<?php\nnamespace Tests;\nabstract class PlayBase extends \\JumPHP\\Testing\\GameTestCase {}",
'games/pong/tests/BallTest.php' => "<?php\nnamespace Tests;\nfinal class BallTest extends PlayBase { public function testBounces(): void {} }",
'games/pong/tests/MathTest.php' => "<?php\nnamespace Tests;\nfinal class MathTest extends \\PHPUnit\\Framework\\TestCase { public function testSum(): void {} }",
'ide/phpunit.xml' => '<phpunit><testsuites><testsuite name="ide"><directory>tests</directory></testsuite></testsuites></phpunit>',
'ide/tests/CoreTest.php' => "<?php\nfinal class CoreTest extends \\PHPUnit\\Framework\\TestCase { public function testCore(): void {} }",
'ide/ui/js/zoom.test.mjs' => "import test, { describe } from 'node:test';\ntest('top', () => {});\ndescribe('group', () => {\n test('inner', () => {});\n describe('deeper', () => {\n it.skip('leaf \\'q\\'', () => {});\n });\n});\n",
'site/composer.json' => '{"require-dev": {"pestphp/pest": "^3"}}',
'site/phpunit.xml' => '<phpunit><testsuites><testsuite name="Feature"><directory>tests</directory></testsuite></testsuites></phpunit>',
'site/tests/HomeTest.php' => "<?php\ntest('the home page answers', function () {})->with([1]);\ndescribe('cart', function () {\n it('adds an item', function () {});\n});\n",
]);
$modules = [['id' => 'pong', 'dir' => 'games/pong', 'kind' => 'game']];
$scopes = array_column((new TestDiscovery($ws))->scopes($modules, true), null, 'id');
self::assertSame(['phpunit:games/pong', 'phpunit:ide', 'pest:site', 'node:'], array_keys($scopes));
$pong = $scopes['phpunit:games/pong'];
self::assertSame(['pong', 'game', true, null], [$pong['module'], $pong['kind'], $pong['game'], $pong['config']]);
$games = [];
foreach ($pong['suites'][0]['files'] as $f) {
foreach ($f['classes'] as $c) {
$games[$c['short']] = $c['game'];
}
}
self::assertSame(['BallTest' => true, 'MathTest' => false, 'PaddleTest' => true], $games, 'a game test through an abstract base too');
self::assertSame(['the home page answers', '`cart` → it adds an item'], array_column($scopes['pest:site']['suites'][0]['files'][0]['tests'], 'name'));
$js = $scopes['node:']['suites'][0]['files'][0]['tests'];
self::assertSame(["ide/ui/js/zoom.test.mjs::top", "ide/ui/js/zoom.test.mjs::group > inner", "ide/ui/js/zoom.test.mjs::group > deeper > leaf 'q'"], array_column($js, 'id'));
self::assertSame([2, 4, 6], array_column($js, 'line'));
}
public function testCommandsAreBuiltTheProjectsWay(): void
{
$game = ['id' => 'phpunit:games/pong', 'type' => 'phpunit', 'dir' => 'games/pong', 'module' => 'pong', 'config' => null, 'source' => false, 'game' => true, 'suites' => []];
$b = TestCommand::build($game, ['test' => 'Tests\PaddleTest::testMoves', 'file' => 'games/pong/tests/PaddleTest.php'], true, ['jumphp' => true, 'root' => '/p']);
self::assertSame(['bin/jumphp', 'test', 'pong', '--phpunit', '--teamcity', '--log-junit', 'var/ide-tests/junit.xml', '--coverage-clover', 'var/ide-tests/clover.xml',
'--coverage-filter', 'src', '--filter', '/^Tests\\\\PaddleTest\:\:testMoves(?: with data set .*)?$/', 'tests/PaddleTest.php'], $b['command']);
self::assertSame(['JUMPHP_FILM' => 'var/ide-tests/film', 'JUMPHP_PROFILE' => 'games/pong/var/ide-tests/xdebug', 'JUMPHP_PROFILE_MODE' => 'coverage'], $b['env']);
self::assertSame(['games/pong/var/ide-tests/junit.xml', 'games/pong/var/ide-tests/clover.xml', 'games/pong/var/ide-tests/film', ['/workspace/' => '']],
[$b['junit'], $b['clover'], $b['film'], $b['paths']]);
// the PHPUnit filter really selects these names
$filter = $b['command'][12];
self::assertMatchesRegularExpression($filter, 'Tests\PaddleTest::testMoves');
self::assertMatchesRegularExpression($filter, 'Tests\PaddleTest::testMoves with data set #0');
self::assertDoesNotMatchRegularExpression($filter, 'Tests\PaddleTest::testMovesFast');
// a game in its own repository: through the IDE's copy of JumPHP, linked as games/<id>
$b = TestCommand::build($game, [], false, ['linked' => true, 'root' => '/home/u/pong']);
self::assertSame(['@jumphp', 'test', 'pong', '--phpunit', '--teamcity', '--log-junit', 'var/ide-tests/junit.xml', 'tests'], $b['command']);
self::assertSame(['pong', ['/workspace/games/pong/' => '']], [$b['game'], $b['paths']]);
// a Symfony site: in its PHP container (web:composer exec), a data set, the suite, the failed ones
$site = ['id' => 'phpunit:', 'type' => 'phpunit', 'dir' => '', 'module' => null, 'config' => 'phpunit.dist.xml', 'source' => true, 'game' => false, 'suites' => []];
$b = TestCommand::build($site, ['test' => 'App\T::testSums', 'set' => '"wrong"', 'file' => 'tests/T.php'], true, ['root' => '/home/u/sf', 'runner' => 'docker']);
self::assertSame(['@jumphp', 'web:composer', '/home/u/sf', 'exec', '--', 'env', 'XDEBUG_MODE=coverage', 'php', 'vendor/bin/phpunit', '--teamcity', '--log-junit',
'var/ide-tests/junit.xml', '--coverage-clover', 'var/ide-tests/clover.xml', '--filter', '/^App\\\\T\:\:testSums with data set "wrong"$/', 'tests/T.php'], $b['command']);
self::assertTrue($b['toolkit']);
self::assertSame(['--testsuite', 'Unit'], TestCommand::phpSelection($site, ['suite' => 'Unit']));
$failed = TestCommand::phpSelection($site, ['tests' => ['App\A::testX', 'App\B::testY with data set #2']]);
self::assertMatchesRegularExpression($failed[1], 'App\B::testY with data set #2');
self::assertMatchesRegularExpression($failed[1], 'App\A::testX');
self::assertDoesNotMatchRegularExpression($failed[1], 'App\B::testY with data set #3');
// the computer's PHP when chosen
$b = TestCommand::build($site, [], false, ['root' => '/home/u/sf', 'runner' => 'local', 'php' => '/usr/bin/php8.3']);
self::assertSame(['/usr/bin/php8.3', 'vendor/bin/phpunit', '--teamcity', '--log-junit', 'var/ide-tests/junit.xml'], $b['command']);
// JavaScript: node --test with the IDE's reporter; in Docker when the computer has no node
$js = ['id' => 'node:', 'type' => 'node', 'dir' => '', 'suites' => [['name' => 'js', 'files' => [['path' => 'a.test.mjs'], ['path' => 'b.test.mjs']]]]];
$b = TestCommand::build($js, ['test' => 'b.test.mjs::group > inner'], false, ['root' => '/p', 'node' => true]);
self::assertSame(['node', '--test', '--test-reporter=./var/ide-tests/node-teamcity.mjs', '--test-reporter-destination=stdout', '--test-name-pattern=^(?:inner)$', 'b.test.mjs'], $b['command']);
$b = TestCommand::build($js, [], false, ['root' => '/p', 'node' => false, 'uid' => '1000:1000']);
self::assertSame(['docker', 'run', '--rm', '-v', '/p:/w', '-w', '/w', '--user', '1000:1000', 'node:22-alpine', 'node', '--test'], array_slice($b['command'], 0, 12));
}
public function testTeamCityIsReadAsItComes(): void
{
$tc = new TeamCity(['/app/' => '']);
$first = $tc->feed("PHPUnit 11.5\n##teamcity[testCount count='3' flowId='7']\n##teamcity[testSuiteStarted name='App\\T' locationHint='php_qn:///app/tests/T.php::\\App\\T' flowId='7']\n##teamcity[testStarted name='testA' locationHint='php_qn:///app/tests/T.php::\\App\\T::testA' flowId='7']\n##teamcity[testFin");
self::assertSame([3, ['App\T::testA'], []], [$first['count'], $first['started'], $first['results']]);
self::assertStringContainsString('PHPUnit 11.5', $first['text']);
$rest = $tc->feed("ished name='testA' duration='12' flowId='7']\n"
. "##teamcity[testStarted name='testSums with data set \"wrong\"' locationHint='php_qn:///app/tests/T.php::\\App\\T::testSums with data set \"wrong\"' flowId='7']\n"
. "##teamcity[testFailed name='testSums with data set \"wrong\"' message='Failed asserting that two arrays are equal.' details='/app/tests/T.php:26|n' type='comparisonFailure' actual='Array (|n |'age|' => 37|n)' expected='Array (|n |'age|' => 36|n)' flowId='7']\n"
. "##teamcity[testFinished name='testSums with data set \"wrong\"' duration='0' flowId='7']\n"
. "##teamcity[testStarted name='testSkip' locationHint='php_qn:///app/tests/T.php::\\App\\T::testSkip' flowId='7']\n"
. "##teamcity[testIgnored name='testSkip' message='not ready |[yet|]' duration='0' flowId='7']\n"
. "##teamcity[testFinished name='testSkip' duration='0' flowId='7']\n"
. "##teamcity[testStarted name='testBoom' locationHint='php_qn:///app/tests/T.php::\\App\\T::testBoom' flowId='7']\n"
. "##teamcity[testFailed name='testBoom' message='RuntimeException: boom' details='/app/tests/T.php:40|n' duration='0' flowId='7']\n"
. "##teamcity[testFinished name='testBoom' duration='0' flowId='7']\n", true);
$r = array_column([...$first['results'], ...$rest['results']], null, 'id');
self::assertSame(['passed', 12, 'tests/T.php'], [$r['App\T::testA']['status'], $r['App\T::testA']['duration'], $r['App\T::testA']['file']]);
$sum = $r['App\T::testSums with data set "wrong"'];
self::assertSame(['failed', 'App\T::testSums', '"wrong"', "Array (\n 'age' => 36\n)", "Array (\n 'age' => 37\n)", "tests/T.php:26\n"],
[$sum['status'], $sum['test'], $sum['set'], $sum['expected'], $sum['actual'], $sum['details']]);
self::assertSame(['skipped', 'not ready [yet]'], [$r['App\T::testSkip']['status'], $r['App\T::testSkip']['message']]);
self::assertSame('error', $r['App\T::testBoom']['status']);
// the node reporter: file://<file>:<line>, describe path as the name
$js = (new TeamCity(['/w/' => '']))->feed("##teamcity[testStarted name='group > inner' locationHint='file:///w/a.test.mjs:5']\n##teamcity[testFinished name='group > inner' duration='2']\n");
self::assertSame(['a.test.mjs::group > inner', 'a.test.mjs', 5], [$js['results'][0]['id'], $js['results'][0]['file'], $js['results'][0]['line']]);
}
public function testJUnitGivesThePrintedOutputAndTheDiff(): void
{
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<testsuites><testsuite name="x">
<testcase name="arraysAreCompared" file="/app/tests/CalcTest.php" line="17" class="App\Tests\CalcTest" classname="App.Tests.CalcTest" time="0.004211">
<failure type="PHPUnit\Framework\ExpectationFailedException">App\Tests\CalcTest::arraysAreCompared
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 'age' =&gt; 36
+ 'age' =&gt; 37
)
/app/tests/CalcTest.php:20</failure>
<system-out>some output
</system-out>
</testcase>
<testcase name="testSkipped" file="/app/tests/CalcTest.php" line="34" class="App\Tests\CalcTest" classname="App.Tests.CalcTest" time="0.001"><skipped/></testcase>
</testsuite></testsuites>
XML;
$r = JUnit::parse($xml, ['/app/' => '']);
self::assertSame(['App\Tests\CalcTest::arraysAreCompared', 'failed', 4, 17, 'tests/CalcTest.php', "some output\n"], [$r[0]['id'], $r[0]['status'], $r[0]['duration'], $r[0]['line'], $r[0]['file'], $r[0]['output']]);
self::assertSame('Failed asserting that two arrays are equal.', $r[0]['message']);
self::assertSame(["Array (\n 'age' => 36\n)", "Array (\n 'age' => 37\n)"], [$r[0]['expected'], $r[0]['actual']]);
self::assertStringContainsString('tests/CalcTest.php:20', $r[0]['details']);
self::assertSame('skipped', $r[1]['status']);
$merged = JUnit::merge([['id' => 'App\Tests\CalcTest::arraysAreCompared', 'status' => 'failed', 'output' => '', 'file' => 'tests/CalcTest.php', 'line' => null]], $r);
self::assertSame(["some output\n", 17, 2], [$merged[0]['output'], $merged[0]['line'], count($merged)]);
self::assertNull(Diff::fromUnified('Failed asserting that false is true.'));
}
public function testCloverGivesTheLinesRunAndThePercentagePerFile(): void
{
$xml = '<coverage><project><file name="/workspace/games/pong/src/Ball.php"><line num="3" type="method" count="1"/><line num="5" type="stmt" count="2"/>'
. '<line num="6" type="stmt" count="0"/><line num="7" type="stmt" count="1"/><line num="8" type="stmt" count="0"/></file>'
. '<file name="/workspace/games/pong/src/Empty.php"/></project></coverage>';
$c = Clover::parse($xml, ['/workspace/' => '']);
self::assertSame(['covered' => [5, 7], 'uncovered' => [6, 8], 'percent' => 50.0], $c['files']['games/pong/src/Ball.php']);
self::assertSame(100.0, $c['files']['games/pong/src/Empty.php']['percent']);
self::assertSame([50.0, 4, 2], [$c['percent'], $c['statements'], $c['covered']]);
}
public function testJestJsonIsRead(): void
{
$json = json_encode(['testResults' => [['name' => '/p/src/a.test.js', 'assertionResults' => [
['ancestorTitles' => ['cart'], 'title' => 'adds', 'status' => 'failed', 'duration' => 3, 'failureMessages' => ["Error: expected 2\n at /p/src/a.test.js:4:5"]],
['ancestorTitles' => [], 'title' => 'later', 'status' => 'pending'],
]]]]);
$r = TestCommand::parseJest((string)$json, ['/p/' => '']);
self::assertSame(['src/a.test.js::cart > adds', 'failed', 'Error: expected 2'], [$r[0]['id'], $r[0]['status'], $r[0]['message']]);
self::assertStringContainsString('src/a.test.js:4:5', $r[0]['details']);
self::assertSame('skipped', $r[1]['status']);
}
}