fix(tia): fingerprint the configuration file the run uses (#1924)

* fix(tia): fingerprint the configuration file the run uses

* fix(tia): tell --no-configuration and identical copies of the configuration apart

* test(tia): cover the gitignore check with composer.lock, as the active configuration is fingerprinted tracked or not
This commit is contained in:
cyppe
2026-11-16 20:50:47 +01:00
committed by GitHub
parent ff1292102c
commit fbaa7fe8e9
11 changed files with 308 additions and 26 deletions
+8 -3
View File
@@ -23,6 +23,7 @@ use Pest\Plugins\Concerns\HandleArguments;
use Pest\Plugins\Tia\BaselineSync;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\CiBranch;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\Contracts\State;
use Pest\Plugins\Tia\CoverageCollector;
use Pest\Plugins\Tia\Fingerprint;
@@ -214,6 +215,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
/** @var array<int, string> */
private array $originalArguments = [];
private ?ConfigurationFile $configuration = null;
private ?string $driftLabel = null;
private ?string $driftDetails = null;
@@ -481,6 +484,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
exit(0);
}
$this->configuration = ConfigurationFile::fromArguments($arguments);
$isWorker = Parallel::isWorker();
$recordingGlobal = $isWorker && (string) Parallel::getGlobal(self::RECORDING_GLOBAL) === '1';
$replayingGlobal = $isWorker && (string) Parallel::getGlobal(self::REPLAYING_GLOBAL) === '1';
@@ -639,7 +644,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -733,7 +738,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -884,7 +889,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
: new TiaRequiresRemote);
}
$fingerprint = Fingerprint::compute($projectRoot);
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration);
$this->startFingerprint = $fingerprint;
$this->startSha = new ChangedFiles($projectRoot)->currentSha();
+121
View File
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use Throwable;
/**
* @internal
*/
final readonly class ConfigurationFile
{
private const string SUPPRESSED = 'none';
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
private function __construct(
private ?string $path,
private bool $suppressed,
) {}
/**
* @param array<int, string> $arguments
*/
public static function fromArguments(array $arguments): self
{
try {
$configuration = new Builder(EventFacade::emitter())->fromParameters(self::configurationParameters($arguments));
} catch (Throwable) {
return self::projectDefault();
}
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
return new self(null, true);
}
$file = new XmlConfigurationFileFinder()->find($configuration);
$path = $file === false ? false : realpath($file);
return new self($path === false ? null : $path, false);
}
public static function at(string $path): self
{
return new self($path, false);
}
public static function projectDefault(): self
{
return new self(null, false);
}
public function fingerprint(string $projectRoot): ?string
{
if ($this->suppressed) {
return self::SUPPRESSED;
}
$path = $this->path ?? $this->defaultIn($projectRoot);
if ($path === null || ! is_file($path)) {
return null;
}
$hash = @hash_file('xxh128', $path);
return $hash === false ? null : $this->relativeTo($projectRoot, $path).':'.$hash;
}
private function defaultIn(string $projectRoot): ?string
{
foreach (self::DEFAULT_NAMES as $name) {
if (is_file($projectRoot.DIRECTORY_SEPARATOR.$name)) {
return $projectRoot.DIRECTORY_SEPARATOR.$name;
}
}
return null;
}
private function relativeTo(string $projectRoot, string $path): string
{
$root = rtrim(str_replace('\\', '/', realpath($projectRoot) ?: $projectRoot), '/').'/';
$file = str_replace('\\', '/', realpath($path) ?: $path);
return str_starts_with($file, $root) ? substr($file, strlen($root)) : $file;
}
/**
* @param array<int, string> $arguments
* @return list<string>
*/
private static function configurationParameters(array $arguments): array
{
$arguments = array_values($arguments);
$parameters = [];
foreach ($arguments as $index => $argument) {
if ($argument === '--no-configuration') {
$parameters[] = $argument;
} elseif ($argument === '--configuration' || $argument === '-c') {
if (isset($arguments[$index + 1])) {
$parameters[] = '--configuration';
$parameters[] = $arguments[$index + 1];
}
} elseif (str_starts_with($argument, '--configuration=')) {
$parameters[] = '--configuration';
$parameters[] = substr($argument, strlen('--configuration='));
} elseif (str_starts_with($argument, '-c') && ! str_starts_with($argument, '--')) {
$parameters[] = '--configuration';
$parameters[] = substr($argument, 2);
}
}
return $parameters;
}
}
+3 -4
View File
@@ -13,7 +13,7 @@ use Symfony\Component\Process\Process;
*/
final readonly class Fingerprint
{
private const int SCHEMA_VERSION = 18;
private const int SCHEMA_VERSION = 19;
/**
* @var array<int, class-string<Lockfile>>
@@ -28,14 +28,13 @@ final readonly class Fingerprint
* environmental: array<string, int|string|null>,
* }
*/
public static function compute(string $projectRoot): array
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array
{
return [
'structural' => [
'schema' => self::SCHEMA_VERSION,
'composer_lock' => self::composerLockHash($projectRoot),
'phpunit_xml' => self::trackedHash($projectRoot, 'phpunit.xml'),
'phpunit_xml_dist' => self::trackedHash($projectRoot, 'phpunit.xml.dist'),
'phpunit_configuration' => ($configuration ?? ConfigurationFile::projectDefault())->fingerprint($projectRoot),
'vite_config' => self::viteConfigHash($projectRoot),
'package_lock' => self::packageLockHash($projectRoot),
'js_config' => self::jsConfigHash($projectRoot),
+7 -3
View File
@@ -7,6 +7,7 @@ namespace Pest\Restarters;
use Composer\XdebugHandler\XdebugHandler;
use Pest\Contracts\Restarter;
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
use Pest\Plugins\Tia\Storage;
@@ -86,10 +87,13 @@ final class XdebugRestarter implements Restarter
return false;
}
return $this->tiaWillReplay($projectRoot);
return $this->tiaWillReplay($projectRoot, $arguments);
}
private function tiaWillReplay(string $projectRoot): bool
/**
* @param array<int, string> $arguments
*/
private function tiaWillReplay(string $projectRoot, array $arguments): bool
{
$path = Storage::tempDir($projectRoot).DIRECTORY_SEPARATOR.Tia::KEY_GRAPH;
@@ -111,7 +115,7 @@ final class XdebugRestarter implements Restarter
return Fingerprint::structuralMatches(
$graph->fingerprint(),
Fingerprint::compute($projectRoot),
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments)),
);
}
}
+7 -1
View File
@@ -1907,6 +1907,12 @@
✓ addOutput → it uses singular form for single test file
✓ addOutput → it returns original exit code when shard is not set
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
✓ it fingerprints the path and the content of the configuration file
✓ it tells an identical copy under another name apart from the original
✓ it resolves a configuration directory the way PHPUnit does
✓ it gives a run with --no-configuration its own fingerprint
PASS Tests\Unit\Plugins\Tia\ContentHash
✓ of() → it returns false when file does not exist
✓ of() → it hashes an existing file
@@ -2442,4 +2448,4 @@
✓ pass with dataset with ('my-datas-set-value')
✓ within describe → pass with dataset with ('my-datas-set-value')
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1756 passed (3817 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1760 passed (3822 assertions)
+4 -2
View File
@@ -2,6 +2,7 @@
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
@@ -13,6 +14,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$projectRoot = dirname(__DIR__, 2);
$home = sys_get_temp_dir().'/pest-tia-'.bin2hex(random_bytes(8));
$fixture = 'tests/Fixtures/Suites/TiaReplayHooks.php';
$configuration = 'tests/Fixtures/Suites/TiaReplayHooks.xml';
mkdir($home, 0755, true);
@@ -24,7 +26,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$id = fn (string $description): string => 'P\Tests\Fixtures\Suites\TiaReplayHooks::'.Str::evaluable($description);
$graph = new Graph($projectRoot);
$graph->setFingerprint(Fingerprint::compute($projectRoot));
$graph->setFingerprint(Fingerprint::compute($projectRoot, ConfigurationFile::at($projectRoot.DIRECTORY_SEPARATOR.$configuration)));
$graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
$graph->markKnownTestFiles([$fixture]);
@@ -48,7 +50,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
expect($storage->write(Tia::KEY_GRAPH, (string) $json))->toBeTrue();
$process = new Process(
['php', 'bin/pest', '--configuration', 'tests/Fixtures/Suites/TiaReplayHooks.xml', '--tia'],
['php', 'bin/pest', '--configuration', $configuration, '--tia'],
$projectRoot,
[
'COLLISION_PRINTER' => 'DefaultPrinter',
+102
View File
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function writeAlternateConfiguration(Project $project, string $failOnRisky = 'false'): void
{
$project->write('phpunit.alternate.xml', str_replace(
'failOnRisky="true"',
sprintf('failOnRisky="%s"', $failOnRisky),
(string) file_get_contents($project->path('phpunit.xml')),
));
}
test('naming the default configuration file or its directory still replays the graph', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$result = $project->pest('--tia', ...$arguments);
expect($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
})->with([
'file' => [['--configuration', 'phpunit.xml']],
'short option' => [['-c', 'phpunit.xml']],
'equals form' => [['--configuration=phpunit.xml']],
'directory' => [['--configuration', '.']],
])->skipOnWindows();
test('a graph recorded under one configuration file is not replayed under another', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing the configuration file in use stops the replay', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master', configuration: 'phpunit.alternate.xml');
$unchanged = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
writeAlternateConfiguration($project, failOnRisky: 'true');
$project->git()->commit('change the alternate configuration');
$edited = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing a configuration file that git ignores stops the replay', function (): void {
$project = Project::make('master');
$project->write('.gitignore', "phpunit.xml\n");
$project->git()->run(['rm', '--cached', '--quiet', 'phpunit.xml']);
$project->git()->commit('stop tracking phpunit.xml');
$project->seed('master');
$unchanged = $project->pest('--tia');
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
$project->write('phpunit.xml', str_replace(
'failOnRisky="true"',
'failOnRisky="false"',
(string) file_get_contents($project->path('phpunit.xml')),
));
$edited = $project->pest('--tia');
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
test('an identical copy of the configuration file under another name does not replay the graph', function (array $arguments): void {
$project = Project::make('master');
$project->write('phpunit.copy.xml', (string) file_get_contents($project->path('phpunit.xml')));
$project->git()->commit('add an identical copy of the configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.copy.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+5 -4
View File
@@ -7,6 +7,7 @@ namespace Tests\Fixtures\Tia;
use FilesystemIterator;
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
@@ -197,15 +198,15 @@ final class Project
/**
* @param array<int, string> $failing
*/
public function seed(string $branch, bool $sentinel = true, array $failing = []): void
public function seed(string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
{
$this->seedFor($this->path, $branch, $sentinel, $failing);
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration);
}
/**
* @param array<int, string> $failing
*/
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = []): void
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
{
$this->graphRoot = $root;
@@ -213,7 +214,7 @@ final class Project
$sha = new GitRepo($root)->sha();
$graph = new Graph($root);
$graph->setFingerprint(Fingerprint::compute($root));
$graph->setFingerprint(Fingerprint::compute($root, $configuration === null ? null : ConfigurationFile::at($root.DIRECTORY_SEPARATOR.$configuration)));
$graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia\ConfigurationFile;
beforeEach(function (): void {
$this->projectRoot = sys_get_temp_dir().'/pest-tia-configuration-'.bin2hex(random_bytes(4));
mkdir($this->projectRoot, 0755, true);
$contents = "<?xml version=\"1.0\"?>\n<phpunit/>\n";
file_put_contents($this->projectRoot.'/phpunit.xml', $contents);
file_put_contents($this->projectRoot.'/phpunit.copy.xml', $contents);
});
afterEach(function (): void {
@unlink($this->projectRoot.'/phpunit.xml');
@unlink($this->projectRoot.'/phpunit.copy.xml');
@rmdir($this->projectRoot);
});
it('fingerprints the path and the content of the configuration file', function (): void {
$fingerprint = ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot);
expect($fingerprint)->toBe('phpunit.xml:'.hash_file('xxh128', $this->projectRoot.'/phpunit.xml'));
});
it('tells an identical copy under another name apart from the original', function (): void {
expect(ConfigurationFile::at($this->projectRoot.'/phpunit.copy.xml')->fingerprint($this->projectRoot))
->not->toBe(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot));
});
it('resolves a configuration directory the way PHPUnit does', function (): void {
expect(ConfigurationFile::fromArguments(['--configuration', $this->projectRoot])->fingerprint($this->projectRoot))
->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot));
});
it('gives a run with --no-configuration its own fingerprint', function (): void {
expect(ConfigurationFile::fromArguments(['--no-configuration'])->fingerprint($this->projectRoot))
->toBe('none')
->not->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot));
});
+8 -8
View File
@@ -56,7 +56,7 @@ describe('compute()', function (): void {
$fingerprint = Fingerprint::compute($clone);
expect($fingerprint['structural']['composer_lock'])->not->toBeNull()
->and($fingerprint['structural']['phpunit_xml'])->not->toBeNull();
->and($fingerprint['structural']['phpunit_configuration'])->not->toBeNull();
} finally {
fingerprintRemoveDirectory($clone);
}
@@ -79,9 +79,9 @@ describe('compute()', function (): void {
$worktreeFingerprint = Fingerprint::compute($worktree);
expect($worktreeFingerprint['structural']['composer_lock'])->not->toBeNull()
->and($worktreeFingerprint['structural']['phpunit_xml'])->not->toBeNull()
->and($worktreeFingerprint['structural']['phpunit_configuration'])->not->toBeNull()
->and($worktreeFingerprint['structural']['composer_lock'])->toBe($cloneFingerprint['structural']['composer_lock'])
->and($worktreeFingerprint['structural']['phpunit_xml'])->toBe($cloneFingerprint['structural']['phpunit_xml']);
->and($worktreeFingerprint['structural']['phpunit_configuration'])->toBe($cloneFingerprint['structural']['phpunit_configuration']);
} finally {
fingerprintRemoveDirectory($clone);
}
@@ -91,17 +91,17 @@ describe('compute()', function (): void {
$clone = fingerprintRepository();
try {
file_put_contents($clone.'/composer.lock', '{"packages": []}');
file_put_contents($clone.'/.gitignore', "phpunit.xml\n");
file_put_contents($clone.'/phpunit.xml', '<phpunit/>');
file_put_contents($clone.'/.gitignore', "composer.lock\n");
fingerprintGit($clone, 'add', '-A');
fingerprintGit($clone, 'commit', '-q', '-m', 'init');
file_put_contents($clone.'/phpunit.xml', '<phpunit/>');
file_put_contents($clone.'/composer.lock', '{"packages": []}');
$fingerprint = Fingerprint::compute($clone);
expect($fingerprint['structural']['phpunit_xml'])->toBeNull()
->and($fingerprint['structural']['composer_lock'])->not->toBeNull();
expect($fingerprint['structural']['composer_lock'])->toBeNull()
->and($fingerprint['structural']['phpunit_configuration'])->not->toBeNull();
} finally {
fingerprintRemoveDirectory($clone);
}
+1 -1
View File
@@ -21,7 +21,7 @@ test('parallel', function () use ($run): void {
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
$profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile');
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1727 passed (3739 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1731 passed (3744 assertions)';
expect($output)
->toContain("Tests: {$expected}")