fix(tia): restrict Xdebug coverage to the source scope before tracing (#2091)

* fix(tia): restrict Xdebug coverage to the source scope before tracing

* fix(tia): set the Xdebug exclude filter before the bootstrap and keep case twins traced

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
Jhon Farias
2026-12-04 09:43:25 +01:00
committed by GitHub
parent 586add8ff2
commit cd5bae7e91
10 changed files with 395 additions and 28 deletions
+4 -4
View File
@@ -1218,7 +1218,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
return $arguments;
@@ -1290,7 +1290,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
return $arguments;
@@ -1428,7 +1428,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
if ($this->piggybackCoverage) {
$this->recorder->activateLinkTracking();
} else {
$this->recorder->activate();
$this->recorder->activate($this->configuration);
}
$this->recordingActive = true;
@@ -1716,7 +1716,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
if ($this->driftLabel !== null || $this->freshGraphReason !== null) {
+51 -4
View File
@@ -4,9 +4,20 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\Event\Dispatcher;
use PHPUnit\Event\DispatchingEmitter;
use PHPUnit\Event\Emitter;
use PHPUnit\Event\Event;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\Event\Telemetry\System;
use PHPUnit\Event\Telemetry\SystemCpuTimeMeter;
use PHPUnit\Event\Telemetry\SystemGarbageCollectorStatusProvider;
use PHPUnit\Event\Telemetry\SystemMemoryMeter;
use PHPUnit\Event\Telemetry\SystemStopWatch;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use PHPUnit\TextUI\XmlConfiguration\DefaultConfiguration;
use PHPUnit\TextUI\XmlConfiguration\Loader;
use Throwable;
/**
@@ -18,16 +29,18 @@ final readonly class ConfigurationFile
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path'];
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path', '--coverage-filter'];
/**
* @param list<string>|null $includePaths
* @param list<string> $coverageFilter
*/
private function __construct(
private ?string $path,
private bool $suppressed,
private ?string $bootstrap = null,
private ?array $includePaths = null,
private array $coverageFilter = [],
) {}
/**
@@ -45,19 +58,20 @@ final readonly class ConfigurationFile
$includePaths = $configuration->hasIncludePath()
? array_map(self::resolved(...), explode(PATH_SEPARATOR, $configuration->includePath()))
: null;
$coverageFilter = $configuration->hasCoverageFilter() ? $configuration->coverageFilter() : [];
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
return new self(null, true, $bootstrap, $includePaths);
return new self(null, true, $bootstrap, $includePaths, $coverageFilter);
}
$file = new XmlConfigurationFileFinder()->find($configuration);
$path = $file === false ? false : realpath($file);
if ($path !== false && $generatedPath !== null && $path === realpath($generatedPath)) {
return new self(null, false, $bootstrap, $includePaths);
return new self(null, false, $bootstrap, $includePaths, $coverageFilter);
}
return new self($path === false ? null : $path, false, $bootstrap, $includePaths);
return new self($path === false ? null : $path, false, $bootstrap, $includePaths, $coverageFilter);
}
public static function at(string $path): self
@@ -70,6 +84,23 @@ final readonly class ConfigurationFile
return new self(null, false);
}
public function sourceScope(string $projectRoot): ?SourceScope
{
$path = $this->suppressed ? null : ($this->path ?? $this->defaultIn($projectRoot));
if ($path === null) {
return SourceScope::fromSource($projectRoot, DefaultConfiguration::create()->source(), $this->coverageFilter);
}
try {
$source = new Loader($this->silentEmitter())->load($path)->source();
} catch (Throwable) {
return null;
}
return SourceScope::fromSource($projectRoot, $source, $this->coverageFilter);
}
public function bootstrapFingerprint(string $projectRoot): ?string
{
return $this->bootstrap === null ? null : $this->relativeTo($projectRoot, $this->bootstrap);
@@ -174,6 +205,22 @@ final readonly class ConfigurationFile
return $argument;
}
private function silentEmitter(): Emitter
{
return new DispatchingEmitter(
new class implements Dispatcher
{
public function dispatch(Event $event): void {}
},
new System(
new SystemStopWatch,
new SystemMemoryMeter,
new SystemGarbageCollectorStatusProvider,
new SystemCpuTimeMeter,
),
);
}
private function withForwardSlashes(string $path): string
{
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
+36 -1
View File
@@ -47,13 +47,19 @@ final class Recorder
private ?SourceScope $sourceScope = null;
private bool $coverageFilterApplied = false;
/** @var (Closure(string): bool)|null */
private ?Closure $recordsTestFile = null;
public function activate(): void
public function activate(?ConfigurationFile $configuration = null): void
{
$this->active = true;
$this->captureCoverage = true;
if ($configuration instanceof ConfigurationFile) {
$this->restrictCoverageToSourceScope($configuration);
}
}
public function activateLinkTracking(): void
@@ -427,6 +433,30 @@ final class Recorder
return $out;
}
private function restrictCoverageToSourceScope(ConfigurationFile $configuration): void
{
if ($this->coverageFilterApplied || ! $this->driverAvailable() || $this->driver !== 'xdebug') {
return;
}
$projectRoot = TestSuite::getInstance()->rootPath;
$scope = $configuration->sourceScope($projectRoot);
if (! $scope instanceof SourceScope) {
return;
}
$excludedPaths = $scope->coverageExcludePaths($projectRoot);
if ($excludedPaths === []) {
return;
}
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_PATH_EXCLUDE, $excludedPaths);
$this->coverageFilterApplied = true;
}
private function sourceScope(): SourceScope
{
return $this->sourceScope ??= SourceScope::fromProjectRoot(TestSuite::getInstance()->rootPath);
@@ -436,6 +466,11 @@ final class Recorder
{
ReadCapture::stop();
if ($this->coverageFilterApplied) {
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_FILTER_NONE, []);
$this->coverageFilterApplied = false;
}
$this->currentTestFile = null;
$this->perTestFiles = [];
$this->perTestTables = [];
+113 -16
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\TextUI\Configuration\Registry;
use PHPUnit\TextUI\Configuration\Source;
use Throwable;
/**
@@ -52,27 +53,44 @@ final class SourceScope
public static function fromProjectRoot(string $projectRoot): self
{
$phpunitIncludes = [];
$phpunitExcludes = [];
try {
$source = Registry::get()->source();
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
} catch (Throwable) {
//
return self::build($projectRoot, [], []);
}
return self::fromSource($projectRoot, $source, []);
}
/**
* @param list<string> $coverageFilter
*/
public static function fromSource(string $projectRoot, Source $source, array $coverageFilter): self
{
$phpunitIncludes = array_map(self::normalise(...), $coverageFilter);
$phpunitExcludes = [];
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
return self::build($projectRoot, $phpunitIncludes, $phpunitExcludes);
}
/**
* @param list<string> $phpunitIncludes
* @param list<array{path: string, prefix: string, suffix: string}> $phpunitExcludes
*/
private static function build(string $projectRoot, array $phpunitIncludes, array $phpunitExcludes): self
{
$rootIncludes = self::topLevelProjectDirs($projectRoot);
$includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes]));
@@ -112,6 +130,30 @@ final class SourceScope
return array_values(array_unique($out));
}
/**
* @return list<string>
*/
public function coverageExcludePaths(string $projectRoot): array
{
$out = [];
foreach (self::noiseDirectories() as $relative) {
$real = @realpath($projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative));
if ($real === false || ! is_dir($real)) {
continue;
}
$directory = self::normalise($real);
if ($this->rejectsEveryFileIn($directory) && ! $this->hasCaseTwin($directory)) {
$out[] = $directory.DIRECTORY_SEPARATOR;
}
}
return $out;
}
public function contains(string $absoluteFile): bool
{
if (isset($this->containsCache[$absoluteFile])) {
@@ -194,6 +236,61 @@ final class SourceScope
return $out;
}
private function rejectsEveryFileIn(string $directory): bool
{
foreach ($this->includes as $included) {
if ($this->overlapsIgnoringCase($directory, $included) && ! $this->overlaps($directory, $included)) {
return false;
}
}
foreach ($this->excludes as $excluded) {
if ($excluded['prefix'] === '' && $excluded['suffix'] === '' && $this->startsWithDir($directory, $excluded['path'])) {
return true;
}
}
return array_all($this->includes, fn (string $included): bool => ! $this->overlapsIgnoringCase($directory, $included));
}
private function hasCaseTwin(string $directory): bool
{
$segments = explode(DIRECTORY_SEPARATOR, $directory);
$parent = array_shift($segments).DIRECTORY_SEPARATOR;
foreach ($segments as $segment) {
if ($segment === '') {
continue;
}
$entries = @scandir($parent);
if ($entries === false) {
return true;
}
foreach ($entries as $entry) {
if ($entry !== $segment && strtolower($entry) === strtolower($segment)) {
return true;
}
}
$parent = rtrim($parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$segment;
}
return false;
}
private function overlaps(string $first, string $second): bool
{
return $this->startsWithDir($first, $second) || $this->startsWithDir($second, $first);
}
private function overlapsIgnoringCase(string $first, string $second): bool
{
return $this->overlaps(strtolower($first), strtolower($second));
}
private static function normalise(string $path): string
{
return rtrim($path, '/\\');
+12 -2
View File
@@ -2048,6 +2048,8 @@
✓ it keeps an empty include path entry empty
✓ it keeps the fingerprint of a relative bootstrap when the working directory changes during the run
✓ it tells an include path through a symlink to a directory with a separator in its name apart from two include paths
✓ it builds the source scope from the coverage filter and the source of the configuration
✓ it gives no source scope when the configuration cannot be read
PASS Tests\Unit\Plugins\Tia\ContentHash
✓ of() → it returns false when file does not exist
@@ -2308,11 +2310,12 @@
✓ 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
WARN Tests\Unit\Plugins\Tia\Recorder
✓ activateLinkTracking() → it tracks tables without a coverage driver
✓ activateLinkTracking() → it tracks inertia components without a coverage driver
✓ activateLinkTracking() → it tracks linked sources across consecutive tests
✓ activateLinkTracking() → it records nothing while inactive
- activate() → it keeps xdebug from tracing the vendor directory of the project → Xdebug is not installed.
✓ recordOnly() → it records only the test files it accepts
✓ recordOnly() → it records each test file again after a reset
@@ -2325,6 +2328,13 @@
✓ contains() → it excludes only the files matching the suffix of an excluded directory
✓ contains() → it excludes only the files matching the prefix of an excluded directory
✓ contains() → it excludes every file of an excluded directory without a prefix or suffix
✓ coverageExcludePaths() → it excludes each noise directory of the project that the scope rejects
✓ coverageExcludePaths() → it keeps a noise directory that holds an included directory
✓ coverageExcludePaths() → it keeps a noise directory below an included directory
✓ coverageExcludePaths() → it keeps a noise directory whose name an included directory shares in another case
✓ coverageExcludePaths() → it keeps a noise directory that has a sibling with the same name in another case
✓ coverageExcludePaths() → it keeps each noise directory when an included directory is the project root in another case
✓ coverageExcludePaths() → it keeps a linked noise directory whose target has a sibling with the same name in another case
WARN Tests\Unit\Plugins\Tia\StaleCoverageLines
- a remeasured file drops line numbers that the current file no longer has → Coverage is not available
@@ -2888,4 +2898,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, 2142 passed (4720 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 45 skipped, 2151 passed (4730 assertions)
+1
View File
@@ -14,6 +14,7 @@ arch()->preset()->php()->ignoring([
'xdebug_start_code_coverage',
'xdebug_stop_code_coverage',
'xdebug_get_code_coverage',
'xdebug_set_filter',
]);
arch()->preset()->strict()->ignoring([
@@ -215,3 +215,28 @@ it('tells an include path through a symlink to a directory with a separator in i
}
}
})->skipOnWindows();
it('builds the source scope from the coverage filter and the source of the configuration', function (): void {
mkdir($this->projectRoot.'/vendor/acme', 0755, true);
file_put_contents($this->projectRoot.'/phpunit.xml', "<?xml version=\"1.0\"?>\n<phpunit><source><include><directory>lib</directory></include></source></phpunit>\n");
$realRoot = (string) realpath($this->projectRoot);
$withoutFilter = ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml'])
->sourceScope($this->projectRoot)
?->coverageExcludePaths($this->projectRoot);
$withFilter = ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml', '--coverage-filter', $realRoot.'/vendor/acme'])
->sourceScope($this->projectRoot)
?->coverageExcludePaths($this->projectRoot);
rmdir($this->projectRoot.'/vendor/acme');
rmdir($this->projectRoot.'/vendor');
expect($withoutFilter)->toBe([$realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR])
->and($withFilter)->toBe([]);
});
it('gives no source scope when the configuration cannot be read', function (): void {
file_put_contents($this->projectRoot.'/phpunit.xml', '<phpunit');
expect(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->sourceScope($this->projectRoot))->toBeNull();
});
+51
View File
@@ -3,6 +3,7 @@
declare(strict_types=1);
use Pest\Plugins\Tia\Recorder;
use Symfony\Component\Process\Process;
describe('activateLinkTracking()', function (): void {
it('tracks tables without a coverage driver', function (): void {
@@ -59,6 +60,56 @@ describe('activateLinkTracking()', function (): void {
});
});
describe('activate()', function (): void {
it('keeps xdebug from tracing the vendor directory of the project', function (): void {
$projectRoot = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-xdebug-filter-'.bin2hex(random_bytes(4));
mkdir($projectRoot.'/app', 0755, true);
mkdir($projectRoot.'/vendor/acme', 0755, true);
file_put_contents($projectRoot.'/app/Inside.php', "<?php\nfunction pest_tia_inside(): int\n{\n return 1;\n}\n");
file_put_contents($projectRoot.'/vendor/acme/Outside.php', "<?php\nfunction pest_tia_outside(): int\n{\n return 2;\n}\n");
file_put_contents($projectRoot.'/record.php', sprintf(<<<'PHP'
<?php
require %s;
\Pest\TestSuite::getInstance(%s, 'tests');
(new \Pest\Plugins\Tia\Recorder)->activate(\Pest\Plugins\Tia\ConfigurationFile::projectDefault());
require %s;
require %s;
\xdebug_start_code_coverage();
pest_tia_inside();
pest_tia_outside();
echo json_encode(array_keys(\xdebug_get_code_coverage()));
PHP,
var_export(dirname(__DIR__, 4).'/vendor/autoload.php', true),
var_export($projectRoot, true),
var_export($projectRoot.'/app/Inside.php', true),
var_export($projectRoot.'/vendor/acme/Outside.php', true),
));
$process = new Process(
[PHP_BINARY, '-d', 'pcov.enabled=0', $projectRoot.'/record.php'],
$projectRoot,
['XDEBUG_MODE' => 'coverage'],
);
$process->run();
$realRoot = (string) realpath($projectRoot);
$traced = json_decode($process->getOutput(), true);
foreach (['app/Inside.php', 'vendor/acme/Outside.php', 'record.php'] as $file) {
unlink($projectRoot.'/'.$file);
}
rmdir($projectRoot.'/vendor/acme');
rmdir($projectRoot.'/vendor');
rmdir($projectRoot.'/app');
rmdir($projectRoot);
expect($traced)->toBeArray($process->getErrorOutput().$process->getOutput())
->toContain($realRoot.'/app/Inside.php')
->not->toContain($realRoot.'/vendor/acme/Outside.php');
})->skip(! extension_loaded('xdebug'), 'Xdebug is not installed.')->skipOnWindows();
});
describe('recordOnly()', function (): void {
it('records only the test files it accepts', function (): void {
$recorder = new Recorder;
+101
View File
@@ -35,3 +35,104 @@ describe('contains()', function (): void {
->and($scope->contains('/project/storage/framework/views/compiled.php'))->toBeFalse();
});
});
describe('coverageExcludePaths()', function (): void {
beforeEach(function (): void {
$this->projectRoot = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-scope-'.bin2hex(random_bytes(4));
mkdir($this->projectRoot.'/vendor/acme', 0755, true);
mkdir($this->projectRoot.'/storage/framework', 0755, true);
$this->realRoot = (string) realpath($this->projectRoot);
});
afterEach(function (): void {
if (is_link($this->projectRoot.'/storage/framework')) {
unlink($this->projectRoot.'/storage/framework');
}
foreach (['vendor/acme', 'vendor', 'storage/framework', 'storage/Framework', 'storage/generated', 'storage/Generated', 'storage'] as $directory) {
if (is_dir($this->projectRoot.'/'.$directory)) {
rmdir($this->projectRoot.'/'.$directory);
}
}
rmdir($this->projectRoot);
});
it('excludes each noise directory of the project that the scope rejects', function (): void {
$scope = new SourceScope(
[$this->realRoot.'/app'],
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
);
expect($scope->coverageExcludePaths($this->projectRoot))->toBe([
$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR,
$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR,
]);
});
it('keeps a noise directory that holds an included directory', function (): void {
$scope = new SourceScope([$this->realRoot.'/vendor/acme'], []);
expect($scope->coverageExcludePaths($this->projectRoot))
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR]);
});
it('keeps a noise directory below an included directory', function (): void {
$scope = new SourceScope([$this->realRoot], []);
expect($scope->coverageExcludePaths($this->projectRoot))->toBeEmpty();
});
it('keeps a noise directory whose name an included directory shares in another case', function (): void {
$scope = new SourceScope([$this->realRoot.'/Vendor'], []);
expect($scope->coverageExcludePaths($this->projectRoot))
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR]);
});
it('keeps a noise directory that has a sibling with the same name in another case', function (): void {
rmdir($this->projectRoot.'/storage/framework');
mkdir($this->projectRoot.'/storage/Framework');
if (! is_dir($this->projectRoot.'/storage/framework')) {
mkdir($this->projectRoot.'/storage/framework');
}
$scope = new SourceScope(
[$this->realRoot.'/storage'],
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
);
expect($scope->coverageExcludePaths($this->projectRoot))
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR]);
});
it('keeps each noise directory when an included directory is the project root in another case', function (): void {
$twinRoot = dirname($this->realRoot).DIRECTORY_SEPARATOR.strtoupper(basename($this->realRoot));
$scope = new SourceScope(
[$this->realRoot.'/app', $twinRoot],
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
);
expect($scope->coverageExcludePaths($this->projectRoot))->toBeEmpty();
});
it('keeps a linked noise directory whose target has a sibling with the same name in another case', function (): void {
rmdir($this->projectRoot.'/storage/framework');
mkdir($this->projectRoot.'/storage/Generated');
if (! is_dir($this->projectRoot.'/storage/generated')) {
mkdir($this->projectRoot.'/storage/generated');
}
symlink('generated', $this->projectRoot.'/storage/framework');
$scope = new SourceScope(
[$this->realRoot.'/storage'],
[['path' => $this->realRoot.'/storage/generated', 'prefix' => '', 'suffix' => '']],
);
expect($scope->coverageExcludePaths($this->projectRoot))
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR]);
})->skipOnWindows();
});
+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, 36 skipped, 1995 passed (4158 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 37 skipped, 2004 passed (4168 assertions)';
expect($output)
->toContain("Tests: {$expected}")