diff --git a/src/Plugins/Tia.php b/src/Plugins/Tia.php index 6a60f8d3..69de178c 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -442,11 +442,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return null; } - $projectRoot = TestSuite::getInstance()->rootPath; - $real = @realpath($filename); - $rel = $real !== false - ? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR))) - : null; + $rel = $this->projectRelativeTestFile($filename); if ($rel !== null && isset($this->affectedFiles[$rel])) { $this->affectedCount++; @@ -490,6 +486,31 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $result; } + private function projectRelativeTestFile(string $filename): ?string + { + $projectRoot = TestSuite::getInstance()->rootPath; + $real = @realpath($filename); + + return $real !== false + ? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR))) + : null; + } + + private function refreshesEdgesOf(string $testFile): bool + { + $rel = $this->projectRelativeTestFile($testFile); + + if ($rel === null || ! $this->replayGraph instanceof Graph) { + return true; + } + + if (! $this->replayGraph->knowsTest($rel)) { + return ! $this->piggybackCoverage; + } + + return isset($this->affectedFiles[$rel]); + } + public function getAssertionCount(string $testId): int { return $this->cachedAssertionsByTestId[$testId] ?? 0; @@ -638,7 +659,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $projectRoot = TestSuite::getInstance()->rootPath; $perTest = $this->piggybackCoverage - ? $this->mergePerTestFiles($this->coverageCollector->perTestFiles(), $recorder->perTestFiles()) + ? $this->mergePerTestFiles(array_filter($this->coverageCollector->perTestFiles(), $this->refreshesEdgesOf(...), ARRAY_FILTER_USE_KEY), $recorder->perTestFiles()) : $recorder->perTestFiles(); if ($perTest === []) { @@ -1247,6 +1268,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument */ private function activateWorkerRecorderForReplay(array $arguments): array { + $this->recorder->recordOnly($this->refreshesEdgesOf(...)); + if ($this->piggybackCoverage) { $this->recorder->activateLinkTracking(); $this->recordingActive = true; @@ -1257,10 +1280,12 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $recorder = $this->recorder; if (! $recorder->driverAvailable()) { - $this->state->write( - self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json', - '{}', - ); + if ($this->affectedFiles !== []) { + $this->state->write( + self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json', + '{}', + ); + } return $arguments; } @@ -1378,7 +1403,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected, $outsideProject); $affectedSet = array_fill_keys($affected, true); - $canRefreshReplayEdges = $affected !== [] && $coverageAvailable; + $canRefreshReplayEdges = $coverageAvailable; $this->replayRan = true; $this->replayGraph = $graph; @@ -1398,6 +1423,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument if (! Parallel::isEnabled()) { if ($canRefreshReplayEdges) { + $this->recorder->recordOnly($this->refreshesEdgesOf(...)); + if ($this->piggybackCoverage) { $this->recorder->activateLinkTracking(); } else { @@ -2175,7 +2202,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument ); } - $graph->markKnownTestFiles(array_keys($touchedFiles)); + $graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...)))); $graph->pruneStaleResults($this->branch, array_keys($touchedFiles), array_keys($results)); $this->reclaim($graph); @@ -2276,7 +2303,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument } if ($markKnownTestFiles) { - $graph->markKnownTestFiles(array_keys($touchedFiles)); + $graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...)))); } if ($complete) { diff --git a/src/Plugins/Tia/Recorder.php b/src/Plugins/Tia/Recorder.php index 9a9a3ff9..b6c68b3a 100644 --- a/src/Plugins/Tia/Recorder.php +++ b/src/Plugins/Tia/Recorder.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pest\Plugins\Tia; +use Closure; use Pest\Support\Arr; use Pest\Support\Container; use Pest\TestSuite; @@ -46,6 +47,9 @@ final class Recorder private ?SourceScope $sourceScope = null; + /** @var (Closure(string): bool)|null */ + private ?Closure $recordsTestFile = null; + public function activate(): void { $this->active = true; @@ -57,6 +61,14 @@ final class Recorder $this->active = true; } + /** + * @param Closure(string): bool $recordsTestFile + */ + public function recordOnly(Closure $recordsTestFile): void + { + $this->recordsTestFile = $recordsTestFile; + } + public function isActive(): bool { return $this->active; @@ -103,6 +115,10 @@ final class Recorder return; } + if ($this->recordsTestFile instanceof Closure && ! ($this->recordsTestFile)($file)) { + return; + } + $this->currentTestFile = $file; if ($this->watchPatterns()->isReadCaptureEnabled()) { @@ -428,6 +444,7 @@ final class Recorder $this->classFileCache = []; $this->classUsesDatabaseCache = []; $this->sourceScope = null; + $this->recordsTestFile = null; $this->active = false; $this->captureCoverage = false; } diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 9ce98c93..a15819a2 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -2309,6 +2309,8 @@ ✓ activateLinkTracking() → it tracks inertia components without a coverage driver ✓ activateLinkTracking() → it tracks linked sources across consecutive tests ✓ activateLinkTracking() → it records nothing while inactive + ✓ recordOnly() → it records only the test files it accepts + ✓ recordOnly() → it records each test file again after a reset PASS Tests\Unit\Plugins\Tia\ResultKey ✓ it keys a result per dataset row rather than per method @@ -2882,4 +2884,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, 44 skipped, 2136 passed (4703 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2138 passed (4706 assertions) \ No newline at end of file diff --git a/tests/Features/Tia/CoverageScopedUnknownTestFiles.php b/tests/Features/Tia/CoverageScopedUnknownTestFiles.php new file mode 100644 index 00000000..df4557b8 --- /dev/null +++ b/tests/Features/Tia/CoverageScopedUnknownTestFiles.php @@ -0,0 +1,99 @@ +write('support/salutation.php', <<<'PHP' + write('tests/Integration/WelcomeTest.php', <<<'PHP' + greet($name))->toBe('Hello, visitor!'); + }); + PHP); + + $project->git()->commit('add a test file the graph does not know'); + $project->seed('master'); +} + +function forgetWelcomeTest(Project $project): void +{ + $project->mutateGraph(function (array $graph): array { + unset($graph['edges']['tests/Integration/WelcomeTest.php']); + + return $graph; + }); +} + +test('a coverage replay does not narrow the edges of a test file the graph does not know', function (array $arguments): void { + $project = Project::make('master'); + addTestFileThatReadsOutsideTheCoverageSource($project); + + $baseline = $project->pest('--tia', '--coverage', ...$arguments); + + expect($baseline->exitCode)->toBe(0, $baseline->describe()); + + forgetWelcomeTest($project); + + $coverage = $project->pest('--tia', '--coverage', ...$arguments); + + expect($coverage->exitCode)->toBe(0, $coverage->describe()) + ->and($coverage->uncached())->toBe(1, $coverage->describe()) + ->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php'); + + $project->write('support/salutation.php', <<<'PHP' + git()->commit('change the salutation'); + + $result = $project->pest('--tia', ...$arguments); + + expect($result->exitCode)->toBe(1, $result->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('a coverage replay with affected test files does not mark a test file the graph does not know as known', function (array $arguments): void { + $project = Project::make('master'); + addTestFileThatReadsOutsideTheCoverageSource($project); + + $baseline = $project->pest('--tia', '--coverage', ...$arguments); + + expect($baseline->exitCode)->toBe(0, $baseline->describe()); + + forgetWelcomeTest($project); + + $project->write('app/Calculator.php', str_replace( + 'return $a + $b;', + 'return ($a + $b);', + (string) file_get_contents($project->path('app/Calculator.php')), + )); + $project->git()->commit('touch the calculator'); + + $coverage = $project->pest('--tia', '--coverage', ...$arguments); + + expect($coverage->exitCode)->toBe(0, $coverage->describe()) + ->and($coverage->affected())->toBeGreaterThan(0, $coverage->describe()) + ->and($coverage->uncached())->toBe(1, $coverage->describe()) + ->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); diff --git a/tests/Features/Tia/UnknownTestFiles.php b/tests/Features/Tia/UnknownTestFiles.php new file mode 100644 index 00000000..e199a14b --- /dev/null +++ b/tests/Features/Tia/UnknownTestFiles.php @@ -0,0 +1,69 @@ +write('tests/Integration/WelcomeTest.php', <<<'PHP' + greet('visitor'))->toBe('Hello, visitor!'); + }); + PHP); + + $project->git()->commit('add a test file the graph does not know'); +} + +test('a replay records a test file the graph does not know', function (array $arguments): void { + $project = Project::make('master'); + addTestFileTheGraphDoesNotKnow($project); + $project->seed('master'); + + $first = $project->pest('--tia', ...$arguments); + + expect($first->exitCode)->toBe(0, $first->describe()) + ->and($first->replayed())->toBe(Project::TOTAL_TESTS, $first->describe()) + ->and($first->uncached())->toBe(1, $first->describe()) + ->and($project->graph()['edges'] ?? [])->toHaveKey('tests/Integration/WelcomeTest.php'); + + $second = $project->pest('--tia', ...$arguments); + + expect($second->exitCode)->toBe(0, $second->describe()) + ->and($second->replayed())->toBe(Project::TOTAL_TESTS + 1, $second->describe()) + ->and($second->uncached())->toBe(0, $second->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('a replay that records a test file the graph does not know keeps the edges of the known test files', function (array $arguments): void { + $project = Project::make('master'); + addTestFileTheGraphDoesNotKnow($project); + $project->seed('master', failing: ['greets a person']); + $project->mutateGraph(function (array $graph): array { + $graph['edges']['tests/Unit/GreeterTest.php'][] = array_search('app/Calculator.php', $graph['files'], true); + + return $graph; + }); + + $known = $project->graph()['edges'] ?? []; + + $result = $project->pest('--tia', ...$arguments); + $edges = $project->graph()['edges'] ?? []; + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($edges)->toHaveKey('tests/Integration/WelcomeTest.php'); + + unset($edges['tests/Integration/WelcomeTest.php']); + + expect($edges)->toBe($known); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); diff --git a/tests/Unit/Plugins/Tia/Recorder.php b/tests/Unit/Plugins/Tia/Recorder.php index 0242d12d..d4657305 100644 --- a/tests/Unit/Plugins/Tia/Recorder.php +++ b/tests/Unit/Plugins/Tia/Recorder.php @@ -58,3 +58,36 @@ describe('activateLinkTracking()', function (): void { expect($recorder->perTestTables())->toBeEmpty(); }); }); + +describe('recordOnly()', function (): void { + it('records only the test files it accepts', function (): void { + $recorder = new Recorder; + $recorder->activateLinkTracking(); + $recorder->recordOnly(fn (string $testFile): bool => $testFile === '/project/tests/Feature/NewTest.php'); + + $recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php'); + $recorder->linkSource('/project/app/Known.php'); + $recorder->linkTable('known'); + $recorder->endTest(); + + $recorder->beginTest('Some\Missing\TestClass', 'new', '/project/tests/Feature/NewTest.php'); + $recorder->linkSource('/project/app/New.php'); + $recorder->endTest(); + + expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/NewTest.php' => ['/project/app/New.php']]) + ->and($recorder->perTestTables())->toBeEmpty(); + }); + + it('records each test file again after a reset', function (): void { + $recorder = new Recorder; + $recorder->recordOnly(fn (string $testFile): bool => false); + $recorder->reset(); + $recorder->activateLinkTracking(); + + $recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php'); + $recorder->linkSource('/project/app/Known.php'); + $recorder->endTest(); + + expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/KnownTest.php' => ['/project/app/Known.php']]); + }); +}); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 0d10f0c1..c2859b99 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -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, 36 skipped, 1989 passed (4141 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 36 skipped, 1991 passed (4144 assertions)'; expect($output) ->toContain("Tests: {$expected}")