diff --git a/src/Plugins/Tia/Configuration.php b/src/Plugins/Tia/Configuration.php index ec32ac20..f471d86d 100644 --- a/src/Plugins/Tia/Configuration.php +++ b/src/Plugins/Tia/Configuration.php @@ -115,4 +115,17 @@ final class Configuration return $this; } + + /** + * @param list|null $patterns Project-relative globs to exclude, or null to disable read capture. Use watch() for excluded files that an existing watch pattern does not cover. + * @return $this + */ + public function withoutReadCapture(?array $patterns = null): self + { + /** @var WatchPatterns $watchPatterns */ + $watchPatterns = Container::getInstance()->get(WatchPatterns::class); + $watchPatterns->excludeReads($patterns); + + return $this; + } } diff --git a/src/Plugins/Tia/Recorder.php b/src/Plugins/Tia/Recorder.php index 47750dc2..7a7d8c69 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 Pest\Support\Container; use Pest\TestSuite; use ReflectionClass; @@ -103,7 +104,9 @@ final class Recorder $this->currentTestFile = $file; - ReadCapture::start($this); + if ($this->watchPatterns()->isReadCaptureEnabled()) { + ReadCapture::start($this); + } if ($this->classUsesDatabase($className)) { $this->perTestUsesDatabase[$file] = true; @@ -201,9 +204,34 @@ final class Recorder return; } + $relative = $this->projectRelative($real); + + if ($relative !== null && $this->watchPatterns()->excludesRead($relative)) { + return; + } + $this->linkSource($real); } + private function projectRelative(string $realPath): ?string + { + $root = rtrim(TestSuite::getInstance()->rootPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; + + if (! str_starts_with($realPath, $root)) { + return null; + } + + return str_replace(DIRECTORY_SEPARATOR, '/', substr($realPath, strlen($root))); + } + + private function watchPatterns(): WatchPatterns + { + $watchPatterns = Container::getInstance()->get(WatchPatterns::class); + assert($watchPatterns instanceof WatchPatterns); + + return $watchPatterns; + } + private function classUsesDatabase(string $className): bool { if (array_key_exists($className, $this->classUsesDatabaseCache)) { diff --git a/src/Plugins/Tia/WatchPatterns.php b/src/Plugins/Tia/WatchPatterns.php index fc1b9e29..c1d32579 100644 --- a/src/Plugins/Tia/WatchPatterns.php +++ b/src/Plugins/Tia/WatchPatterns.php @@ -43,6 +43,13 @@ final class WatchPatterns private bool $defaultsEnabled = true; + /** + * @var list + */ + private array $excludedReadPatterns = []; + + private bool $readCaptureEnabled = true; + /** * @var array, allowDotfiles: bool}> */ @@ -110,6 +117,39 @@ final class WatchPatterns ])); } + /** + * @param list|null $patterns + */ + public function excludeReads(?array $patterns = null): void + { + if ($patterns === null) { + $this->readCaptureEnabled = false; + + return; + } + + $this->excludedReadPatterns = array_values(array_unique([ + ...$this->excludedReadPatterns, + ...$patterns, + ])); + } + + public function isReadCaptureEnabled(): bool + { + return $this->readCaptureEnabled; + } + + /** + * @param string $file Project-relative path. + */ + public function excludesRead(string $file): bool + { + return array_any( + $this->excludedReadPatterns, + fn (string $pattern): bool => $this->keyMatches($pattern, $file), + ); + } + /** * @param string $projectRoot Absolute path. * @param array $changedFiles Project-relative paths. @@ -279,6 +319,8 @@ final class WatchPatterns $this->defaultPatterns = []; $this->excludedDefaultPatterns = []; $this->defaultsEnabled = true; + $this->excludedReadPatterns = []; + $this->readCaptureEnabled = true; $this->parsed = []; $this->enabled = false; $this->locally = false; diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 6112430c..1e298acb 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -2069,6 +2069,13 @@ ✓ a wrapper already registered for file:// → it opens reads through it and still links them ✓ a wrapper already registered for file:// → it keeps the include flag for the files a test includes ✓ a wrapper already registered for file:// → it is registered again after the test + ✓ withoutReadCapture() → it does not link a file matching an excluded glob + ✓ withoutReadCapture() → it still links a file outside the excluded globs + ✓ withoutReadCapture() → it keeps the file wrapper registered while globs are excluded + ✓ withoutReadCapture() → it links every read when the list of globs is empty + ✓ withoutReadCapture() → it registers no wrapper and links no read when called without globs + ✓ withoutReadCapture() → it keeps the explicit links when called without globs + ✓ withoutReadCapture() → it leaves a wrapper already registered for file:// untouched when called without globs PASS Tests\Unit\Plugins\Tia\Recorder ✓ activateLinkTracking() → it tracks tables without a coverage driver @@ -2259,6 +2266,16 @@ ✓ it retains recorded Inertia dependencies when default watches are disabled ✓ it retains recorded migration tables when default watches are disabled ✓ it uses custom mappings for an unknown Vue page with defaults disabled + ✓ it captures every read by default + ✓ it excludes reads of files matching a glob + ✓ it matches read globs like watch patterns + ✓ it does not exclude a dotfile unless the glob names it + ✓ it accumulates read exclusions from repeated calls + ✓ it does not turn read capture off for an empty exclusion list + ✓ it turns read capture off without a list of globs + ✓ it keeps read capture off when globs are added afterwards + ✓ it captures reads again on reset + ✓ it does not change the default watch fallbacks of an excluded read PASS Tests\Unit\Plugins\Tia\WorkerToken ✓ prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens @@ -2569,4 +2586,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, 1863 passed (4281 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1880 passed (4316 assertions) \ No newline at end of file diff --git a/tests/Features/Tia/ReadCapture.php b/tests/Features/Tia/ReadCapture.php index 89d816af..8ddaf3bc 100644 --- a/tests/Features/Tia/ReadCapture.php +++ b/tests/Features/Tia/ReadCapture.php @@ -25,6 +25,19 @@ function tiaRecordWithSourceReadingTest(Project $project, string ...$arguments): $project->pest('--tia', ...$arguments); } +/** + * @return array + */ +function tiaEdgeFiles(Project $project, string $testFile): array +{ + $graph = $project->graph() ?? []; + + return array_map( + fn (int $id): string => $graph['files'][$id], + $graph['edges'][$testFile] ?? [], + ); +} + test('a test that reads a file records an edge to it', function (array $arguments): void { $project = Project::make('master'); @@ -108,3 +121,68 @@ test('a file a test reads does not select it when another file changes', functio expect($result->affected())->toBe(4, $result->describe()) ->and($result->replayed())->toBe(3, $result->describe()); })->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('a test that reads an excluded file records no edge to it', function (array $arguments): void { + $project = Project::make('master'); + $project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')). + "\npest()->tia()->withoutReadCapture(['app/Greeter.php']);\n"); + + tiaRecordWithSourceReadingTest($project, ...$arguments); + + expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php') + ->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('a test that reads a file outside the excluded globs still records an edge to it', function (array $arguments): void { + $project = Project::make('master'); + $project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')). + "\npest()->tia()->withoutReadCapture(['lang/*.json']);\n"); + + tiaRecordWithSourceReadingTest($project, ...$arguments); + + expect(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->toContain('app/Greeter.php'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('no read records an edge when read capture is off', function (array $arguments): void { + $project = Project::make('master'); + $project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')). + "\npest()->tia()->withoutReadCapture();\n"); + + tiaRecordWithSourceReadingTest($project, ...$arguments); + + expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php') + ->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('a watch pattern reruns tests after an excluded file changes', function (array $arguments): void { + $project = Project::make('master'); + + $project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).<<<'PHP' + + pest()->tia() + ->withoutReadCapture(['data/*.json']) + ->watch(['data/*.json' => 'tests/Unit/GreeterTest.php']); + + PHP); + $project->write('data/status.json', '"ready"'); + + $testFile = 'tests/Unit/GreeterTest.php'; + $project->write($testFile, str_replace( + ' expect((new Greeter)->greet(\'Nuno\'))->toBe(\'Hello, Nuno!\');', + ' expect(file_get_contents(__DIR__.\'/../../data/status.json\'))->toBe(\'"ready"\');', + file_get_contents($project->path($testFile)), + )); + + $project->git()->commit('add a watched JSON fixture'); + $project->seed('master'); + + $project->write('data/status.json', '"broken"'); + $project->git()->commit('change the watched fixture'); + + $result = $project->pest('--tia', ...$arguments); + + expect($result->exitCode)->toBe(1, $result->describe()) + ->and($result->affected())->toBe(2, $result->describe()) + ->and($result->replayed())->toBe(4, $result->describe()) + ->and($result->output)->toContain('greets a person', 'broken'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); diff --git a/tests/Unit/Plugins/Tia/ReadCapture.php b/tests/Unit/Plugins/Tia/ReadCapture.php index 373619ba..16038c4f 100644 --- a/tests/Unit/Plugins/Tia/ReadCapture.php +++ b/tests/Unit/Plugins/Tia/ReadCapture.php @@ -2,8 +2,11 @@ declare(strict_types=1); +use Pest\Plugins\Tia\Configuration; use Pest\Plugins\Tia\ReadCapture; use Pest\Plugins\Tia\Recorder; +use Pest\Plugins\Tia\WatchPatterns; +use Pest\Support\Container; use Tests\Fixtures\Tia\LoggingFileWrapper; /** @@ -294,3 +297,100 @@ describe('a wrapper already registered for file://', function (): void { ->and(tiaReadCaptureWrapperClass())->toBe(LoggingFileWrapper::class); }); }); + +describe('withoutReadCapture()', function (): void { + beforeEach(function (): void { + Container::getInstance()->add(WatchPatterns::class, new WatchPatterns); + + $this->excluded = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php'); + $this->kept = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/Recorder.php'); + }); + + afterEach(function (): void { + Container::getInstance()->add(WatchPatterns::class, new WatchPatterns); + }); + + it('does not link a file matching an excluded glob', function (): void { + (new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']); + + expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBeEmpty(); + }); + + it('still links a file outside the excluded globs', function (): void { + (new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']); + + $links = tiaReadCaptureLinks(function (): void { + file_get_contents($this->excluded); + file_get_contents($this->kept); + }); + + expect($links)->toBe([$this->kept]); + }); + + it('keeps the file wrapper registered while globs are excluded', function (): void { + (new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']); + + $during = ''; + + tiaReadCaptureLinks(function () use (&$during): void { + $during = tiaReadCaptureWrapperType(); + }); + + expect($during)->toBe('user-space'); + }); + + it('links every read when the list of globs is empty', function (): void { + (new Configuration)->withoutReadCapture([]); + + expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBe([$this->excluded]); + }); + + it('registers no wrapper and links no read when called without globs', function (): void { + (new Configuration)->withoutReadCapture(); + + $during = ''; + + $links = tiaReadCaptureLinks(function () use (&$during): void { + $during = tiaReadCaptureWrapperType(); + file_get_contents($this->kept); + }); + + expect($during)->toBe('plainfile') + ->and($links)->toBeEmpty() + ->and(tiaReadCaptureWrapperType())->toBe('plainfile'); + }); + + it('keeps the explicit links when called without globs', function (): void { + (new Configuration)->withoutReadCapture(); + + $recorder = new Recorder; + $recorder->activateLinkTracking(); + + $recorder->beginTest('Some\Missing\TestClass', 'it links', '/project/tests/Feature/LinksTest.php'); + $recorder->linkSource('/project/resources/views/welcome.blade.php'); + $recorder->endTest(); + + expect($recorder->perTestFiles()) + ->toBe(['/project/tests/Feature/LinksTest.php' => ['/project/resources/views/welcome.blade.php']]); + }); + + it('leaves a wrapper already registered for file:// untouched when called without globs', function (): void { + (new Configuration)->withoutReadCapture(); + + LoggingFileWrapper::enable(); + + try { + $during = null; + + $links = tiaReadCaptureLinks(function () use (&$during): void { + $during = tiaReadCaptureWrapperClass(); + file_get_contents($this->kept); + }); + } finally { + LoggingFileWrapper::disable(); + } + + expect($during)->toBe(LoggingFileWrapper::class) + ->and($links)->toBeEmpty(); + }); +}); diff --git a/tests/Unit/Plugins/Tia/WatchPatterns.php b/tests/Unit/Plugins/Tia/WatchPatterns.php index 77fca052..e7dd3339 100644 --- a/tests/Unit/Plugins/Tia/WatchPatterns.php +++ b/tests/Unit/Plugins/Tia/WatchPatterns.php @@ -181,3 +181,88 @@ it('uses custom mappings for an unknown Vue page with defaults disabled', functi expect($graph->affected(['resources/js/Pages/Enroll.vue']))->toBe(['tests/Unit/CalculatorTest.php']); }); + +it('captures every read by default', function (): void { + expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse(); +}); + +it('excludes reads of files matching a glob', function (): void { + $configuration = new Configuration; + + expect($configuration->withoutReadCapture(['lang/*.json']))->toBe($configuration) + ->and($this->watchPatterns->isReadCaptureEnabled())->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeFalse() + ->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeFalse() + ->and($this->watchPatterns->excludesRead('lang/fr.php'))->toBeFalse(); +}); + +it('matches read globs like watch patterns', function (): void { + (new Configuration)->withoutReadCapture([ + 'lang/**/*.json !lang/vendor/keep/**', + 'tests/Fixtures/*.csv', + '.env.testing', + ]); + + expect($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/vendor/keep/fr.json'))->toBeFalse() + ->and($this->watchPatterns->excludesRead('tests/Fixtures/orders.csv'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('tests/Fixtures/nested/orders.csv'))->toBeFalse() + ->and($this->watchPatterns->excludesRead('.env.testing'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('.env.local'))->toBeFalse(); +}); + +it('does not exclude a dotfile unless the glob names it', function (): void { + (new Configuration)->withoutReadCapture(['**']); + + expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('.env.testing'))->toBeFalse(); +}); + +it('accumulates read exclusions from repeated calls', function (): void { + (new Configuration) + ->withoutReadCapture(['lang/*.json']) + ->withoutReadCapture(['resources/lang/*.json']); + + expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue() + ->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeTrue(); +}); + +it('does not turn read capture off for an empty exclusion list', function (): void { + (new Configuration)->withoutReadCapture([]); + + expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse(); +}); + +it('turns read capture off without a list of globs', function (): void { + (new Configuration)->withoutReadCapture(); + + expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse(); +}); + +it('keeps read capture off when globs are added afterwards', function (): void { + (new Configuration) + ->withoutReadCapture() + ->withoutReadCapture(['lang/*.json']); + + expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse(); +}); + +it('captures reads again on reset', function (): void { + (new Configuration) + ->withoutReadCapture() + ->withoutReadCapture(['lang/*.json']); + + $this->watchPatterns->reset(); + + expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue() + ->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse(); +}); + +it('does not change the default watch fallbacks of an excluded read', function (): void { + (new Configuration)->withoutReadCapture(['.env.testing']); + + expect($this->watchPatterns->matchedDirectories(getcwd(), ['.env.testing']))->toBe(['tests']); +}); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index aa2f6ba5..4f7cacdc 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, 30 skipped, 1736 passed (3756 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1753 passed (3791 assertions)'; expect($output) ->toContain("Tests: {$expected}")