rob-revisited/ide/tests/AbTestTest.php

75 lines
2.7 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Ab\AbTest;
use PHPUnit\Framework\TestCase;
/** A/B tests: the copy A, the functions changed since, the A files of a run. */
final class AbTestTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jumphp-ab-' . bin2hex(random_bytes(4));
mkdir("$this->dir/games/pong/src/Scene", 0777, true);
file_put_contents("$this->dir/games/pong/src/Scene/Play.php", <<<'PHP'
<?php
namespace App\Scene;
final class Play
{
private int $speed = 2;
public function update(float $dt): void
{
$x = 1;
$this->move($x);
}
private function move(int $x): int
{
return $x * $this->speed;
}
}
PHP);
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->dir));
}
public function testTheChangedMethodsAreFoundAndTheirAVersionIsKept(): void
{
$ab = new AbTest($this->dir);
self::assertSame(1, $ab->start('pong', 'games/pong')['files']);
self::assertSame([], $ab->changes('pong'), 'nothing changed yet');
$file = "$this->dir/games/pong/src/Scene/Play.php";
file_put_contents($file, str_replace('return $x * $this->speed;', "\$y = \$x + 0;\n return \$y * \$this->speed;", (string)file_get_contents($file)));
$changes = $ab->changes('pong');
self::assertCount(1, $changes);
self::assertSame('games/pong/src/Scene/Play.php', $changes[0]['file']);
self::assertSame(['App\Scene\Play::move'], array_column($changes[0]['sections'], 'name'));
$overlay = $ab->overlay('pong');
self::assertStringContainsString('return $x * $this->speed;', (string)file_get_contents("$this->dir/$overlay/src/Scene/Play.php"), 'A, as it was');
$ab->stop('pong');
self::assertFalse($ab->state('pong')['active']);
}
public function testAChangeOutsideFunctionsIsSaid(): void
{
$old = "<?php\nclass A {\n private int \$n = 1;\n public function f(): int { return 1; }\n}\n";
$new = "<?php\nclass A {\n private int \$n = 2;\n public function f(): int { return 1; }\n}\n";
$sections = AbTest::sectionsOf($new, AbTest::changedLines($old, $new));
self::assertCount(1, $sections);
self::assertStringStartsWith('(outside functions', $sections[0]['name']);
}
public function testFunctionsAreFoundWithTheirLines(): void
{
$f = AbTest::functions((string)file_get_contents("$this->dir/games/pong/src/Scene/Play.php"));
self::assertSame([['name' => 'App\Scene\Play::update', 'from' => 8, 'to' => 12], ['name' => 'App\Scene\Play::move', 'from' => 14, 'to' => 17]], $f);
}
}