fix(tia): run the full suite when code the project loads from outside its root changes (#1915)

* fix(tia): run the full suite when code the project loads from outside its root changes

* test(tia): cover the configuration fingerprint of a nested project

* fix(tia): run the full suite when a declared external root holds files git ignores

* fix(tia): track ignored inputs under external roots by content hash

* fix(tia): harden external source tracking from the review loop

* test: update the suite totals for the external source tests

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jhon Farias
2026-11-28 09:39:05 +01:00
committed by GitHub
parent d314fc0540
commit b5851d67ff
17 changed files with 4095 additions and 47 deletions
+240 -12
View File
@@ -27,6 +27,7 @@ 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\ExternalSources;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
use Pest\Plugins\Tia\JsModuleGraph;
@@ -192,6 +193,16 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
private ?string $startSha = null;
/**
* @var array<string, string>|null
*/
private ?array $ignoredInputsAtStart = null;
/**
* @var array<int, string>
*/
private array $ignoredInputsChangedDuringRun = [];
private bool $piggybackCoverage = false;
private bool $recordingActive = false;
@@ -204,6 +215,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
private bool $writesSuppressed = false;
private bool $dirtyExternalSourcesResolved = false;
/** @var array<int, string>|null */
private ?array $dirtyExternalSources = null;
private bool $resultsOnlyWrites = false;
private bool $flushesWorkerResults = false;
@@ -494,6 +510,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$configurationPlugin = Container::getInstance()->get(Configuration::class);
assert($configurationPlugin instanceof Configuration);
$this->configuration = ConfigurationFile::fromArguments($arguments, $configurationPlugin->generatedConfigurationPath());
ExternalSources::pinWorkingDirectory(TestSuite::getInstance()->rootPath);
$isWorker = Parallel::isWorker();
$recordingGlobal = $isWorker && (string) Parallel::getGlobal(self::RECORDING_GLOBAL) === '1';
@@ -653,7 +670,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -672,12 +689,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return;
}
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
$this->renderExternalSourcesChangedDuringRun('discarding recorded edges');
$recorder->reset();
$this->coverageCollector->reset();
return;
}
$graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot);
$graph->setFingerprint($currentFingerprint);
$graph->setRecordedAtSha($this->branch, $currentSha);
$graph->setLastRunTree(
$this->branch,
$changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []),
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
);
$graph->replaceEdges($perTest, keepExisting: $this->piggybackCoverage);
$graph->replaceTestTables($perTestTables);
@@ -747,7 +772,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -770,12 +795,22 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $exitCode;
}
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
$this->renderExternalSourcesChangedDuringRun('discarding recorded edges');
foreach ($partialKeys as $key) {
$this->state->delete($key);
}
return $exitCode;
}
$graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot);
$graph->setFingerprint($currentFingerprint);
$graph->setRecordedAtSha($this->branch, $currentSha);
$graph->setLastRunTree(
$this->branch,
$changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []),
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
);
[$finalised, $finalisedTables, $finalisedInertia] = $this->consumePartials($partialKeys);
@@ -892,9 +927,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
: new TiaRequiresRemote);
}
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration);
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
$this->startFingerprint = $fingerprint;
$this->startSha = new ChangedFiles($projectRoot)->currentSha();
$this->ignoredInputsAtStart = $this->ignoredInputHashes($projectRoot);
if ($forceRebuild && $this->canRebuildGraph()) {
$this->purgeState();
@@ -930,6 +966,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
}
}
if ($this->holdsDirtyExternalSources($projectRoot) || $this->holdsUnverifiableExternalSources($projectRoot)) {
return $arguments;
}
$uncommittedPhpChanges = $this->uncommittedPhpChangesOutsideProject($projectRoot);
if ($uncommittedPhpChanges !== []) {
@@ -965,6 +1005,134 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $this->enterRecordMode($arguments);
}
private function holdsUnverifiableExternalSources(string $projectRoot): bool
{
$unverifiable = ExternalSources::unverifiable($projectRoot, $this->originalArguments);
if ($unverifiable === []) {
return false;
}
$this->writesSuppressed = true;
$this->renderBadge('WARN', sprintf(
'This project loads %d path%s whose changes git cannot report.',
count($unverifiable),
count($unverifiable) === 1 ? '' : 's',
));
foreach (array_slice($unverifiable, 0, $this->output->isVerbose() ? count($unverifiable) : 5) as $path) {
$this->output->writeln(sprintf(' <fg=gray>%s</>', $path));
}
$this->renderChild('Running the full suite, and recording nothing — git reports no change there, so no result could stand behind a replay.');
$this->renderChild('Move what the project loads into the repository to let TIA select tests again.');
return true;
}
private function holdsDirtyExternalSources(string $projectRoot): bool
{
$dirty = $this->dirtyExternalSources($projectRoot);
if ($dirty === []) {
return false;
}
$this->writesSuppressed = true;
if ($dirty === null) {
$this->renderBadge('WARN', 'Git could not read the working tree of the code this project loads from outside its root.');
$this->renderChild('Running the full suite, and recording nothing.');
return true;
}
$this->renderBadge('WARN', sprintf(
'Detected %d uncommitted change%s this project loads from outside its root.',
count($dirty),
count($dirty) === 1 ? '' : 's',
));
foreach (array_slice($dirty, 0, $this->output->isVerbose() ? count($dirty) : 5) as $file) {
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
}
$this->renderChild('Running the full suite, and recording nothing — git stops reporting such an edit once it is undone.');
$this->renderChild('Commit what you changed there to let a run leave a baseline behind.');
return true;
}
private function externalSourcesChangedDuringRun(string $projectRoot): bool
{
$this->dirtyExternalSourcesResolved = false;
$this->ignoredInputsChangedDuringRun = $this->ignoredInputsAtStart === null
? []
: new ChangedFiles($projectRoot)->changedExternalInputs($this->ignoredInputsAtStart, $this->ignoredInputHashes($projectRoot));
return $this->dirtyExternalSources($projectRoot) !== [] || $this->ignoredInputsChangedDuringRun !== [];
}
/**
* @return array<string, string>
*/
private function ignoredInputHashes(string $projectRoot): array
{
$ignored = ExternalSources::ignoredState($projectRoot, $this->originalArguments);
return new ChangedFiles($projectRoot)->externalInputHashes($ignored['inputs'], $ignored['repositories'], [...$ignored['failed'], ...$ignored['unreadable']]);
}
private function renderExternalSourcesChangedDuringRun(string $consequence): void
{
$this->renderBadge('WARN', 'Code this project loads from outside its root changed during the run — '.$consequence.'.');
if ($this->ignoredInputsChangedDuringRun !== []) {
foreach (array_slice($this->ignoredInputsChangedDuringRun, 0, $this->output->isVerbose() ? count($this->ignoredInputsChangedDuringRun) : 5) as $file) {
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
}
$this->renderChild('These files changed during the run, or git stopped ignoring them. Keep what the run writes out of the paths this project loads to let TIA record again.');
}
if ($this->ignoredInputsChangedDuringRun === [] || $this->dirtyExternalSources !== []) {
$this->renderChild('Re-run --tia after your edits settle to record a fresh dependency graph.');
}
}
/**
* @return array<int, string>|null
*/
private function dirtyExternalSources(string $projectRoot): ?array
{
if ($this->dirtyExternalSourcesResolved) {
return $this->dirtyExternalSources;
}
$this->dirtyExternalSourcesResolved = true;
if (ExternalSources::rootsFor($projectRoot, $this->originalArguments) === []) {
return $this->dirtyExternalSources = [];
}
$changedFiles = new ChangedFiles($projectRoot);
try {
$changedFiles->since(null);
} catch (MissingDependency) {
return $this->dirtyExternalSources = [];
} catch (TiaGitFailed) {
return $this->dirtyExternalSources = null;
}
return $this->dirtyExternalSources = ExternalSources::matching(
$projectRoot,
$changedFiles->outsideProjectDirty(),
$this->originalArguments,
);
}
private function purgeState(): void
{
foreach ([
@@ -1119,17 +1287,60 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$outsideProject = $changedFiles->outsideProject();
[$changed, $changedExternalInputs] = $changedFiles->changedSinceLastRun(
$changed,
ExternalSources::ignoredInputs($projectRoot, $this->originalArguments),
$graph->lastRunTree($this->branch),
);
$externalChanges = array_values(array_unique([
...ExternalSources::matching($projectRoot, $outsideProject, $this->originalArguments),
...$changedExternalInputs,
]));
if ($externalChanges !== []) {
$this->renderBadge('WARN', sprintf(
'Detected changes in %d file%s this project loads from outside its root.',
count($externalChanges),
count($externalChanges) === 1 ? '' : 's',
));
foreach (array_slice($externalChanges, 0, $this->output->isVerbose() ? count($externalChanges) : 5) as $file) {
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
}
if ($this->canRebuildGraph()) {
$this->deleteState(self::KEY_GRAPH);
$this->deleteState(self::KEY_COVERAGE_CACHE);
$this->freshGraphReason = 'code this project loads from outside its root changed';
return $this->enterRecordMode($arguments);
}
$this->requestWorkerResults();
$this->renderChild('Running the full suite — the dependency graph only reaches files under the project root.');
if ($this->piggybackCoverage) {
$this->renderChild('Run --tia without --coverage to record a fresh dependency graph.');
return $arguments;
}
$this->fullSuiteFallbackRan = true;
$this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after changes outside the project root.');
return $arguments;
}
$phpChangesOutsideProject = $this->phpFiles($outsideProject);
if ($phpChangesOutsideProject !== []) {
return $this->runFullSuiteForPhpChangesOutsideProject($phpChangesOutsideProject, $arguments);
}
$changed = $changedFiles->filterUnchangedSinceLastRun(
$changed,
$graph->lastRunTree($this->branch),
);
$hasProjectPhpSourceChanges = $this->hasProjectPhpSourceChanges($changed);
$coverageAvailable = $this->piggybackCoverage || $this->recorder->driverAvailable();
@@ -1874,12 +2085,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return;
}
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
$this->renderExternalSourcesChangedDuringRun('keeping the baseline from before the run');
return;
}
if ($currentSha !== null) {
$graph->setRecordedAtSha($this->branch, $currentSha);
}
$workingTreeFiles = $changedFiles->since($currentSha) ?? [];
$graph->setLastRunTree($this->branch, $changedFiles->snapshotTree($workingTreeFiles));
$graph->setLastRunTree(
$this->branch,
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
);
$this->saveGraph($graph);
}
@@ -2003,6 +2222,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return;
}
if ($this->externalSourcesChangedDuringRun($projectRoot)
|| ExternalSources::unverifiable($projectRoot, $this->originalArguments) !== []) {
$collector->reset();
return;
}
try {
$this->resolveBranch($projectRoot);
} catch (MissingDependency|TiaGitFailed) {
@@ -2390,6 +2616,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
'pest_factory' => 'Pest internals',
'pest_method_factory' => 'Pest internals',
'project_prefix' => 'project location in the repository',
'external_roots' => 'the roots this project loads from outside itself',
'include_path' => 'the include path',
];
$seen = [];
+115 -21
View File
@@ -77,17 +77,17 @@ final class ChangedFiles
/**
* @return array<int, string>
*/
public function outsideProject(): array
public function outsideProjectDirty(): array
{
return Arr::stringKeys($this->outsideProject);
return Arr::stringKeys($this->outsideProjectDirty);
}
/**
* @return array<int, string>
*/
public function outsideProjectDirty(): array
public function outsideProject(): array
{
return Arr::stringKeys($this->outsideProjectDirty);
return Arr::stringKeys($this->outsideProject);
}
/**
@@ -121,6 +121,100 @@ final class ChangedFiles
return $remaining;
}
/**
* @param array<int, string> $repositoryRelativeInputs
* @return array<string, string>
*/
public function baselineTree(?string $sha, array $repositoryRelativeInputs): array
{
return $this->snapshotTree([...($this->since($sha) ?? []), ...$this->externalKeys($repositoryRelativeInputs)]);
}
/**
* @param array<int, string> $repositoryRelativeInputs
* @param array<int, string> $repositoryRelativeRepositories
* @param array<int, string> $repositoryRelativeUnlisted
* @return array<string, string>
*/
public function externalInputHashes(array $repositoryRelativeInputs, array $repositoryRelativeRepositories = [], array $repositoryRelativeUnlisted = []): array
{
$hashes = $this->snapshotTree($this->externalKeys($repositoryRelativeInputs));
foreach ($this->externalKeys($repositoryRelativeRepositories) as $key) {
$hashes[$key] = 'repository';
}
foreach ($this->externalKeys($repositoryRelativeUnlisted) as $key) {
$hashes[$key] = 'unlisted';
}
return $hashes;
}
/**
* @param array<string, string> $before
* @param array<string, string> $after
* @return array<int, string>
*/
public function changedExternalInputs(array $before, array $after): array
{
$parent = $this->parentPath();
$changed = [];
foreach (Arr::stringKeys([...$before, ...$after]) as $key) {
if (($before[$key] ?? null) !== ($after[$key] ?? null)) {
$changed[] = $parent !== '' && str_starts_with($key, $parent) ? substr($key, strlen($parent)) : $key;
}
}
sort($changed);
return $changed;
}
/**
* @param array<int, string> $files
* @param array<int, string> $repositoryRelativeInputs
* @param array<string, string> $lastRunTree
* @return array{0: array<int, string>, 1: array<int, string>}
*/
public function changedSinceLastRun(array $files, array $repositoryRelativeInputs, array $lastRunTree): array
{
$parent = $this->parentPath();
$projectFiles = [];
$externalInputsChanged = [];
foreach ($this->filterUnchangedSinceLastRun([...$files, ...$this->externalKeys($repositoryRelativeInputs)], $lastRunTree) as $file) {
if ($parent !== '' && str_starts_with($file, $parent)) {
$externalInputsChanged[] = substr($file, strlen($parent));
} else {
$projectFiles[] = $file;
}
}
return [$projectFiles, $externalInputsChanged];
}
/**
* @param array<int, string> $repositoryRelativeInputs
* @return array<int, string>
*/
private function externalKeys(array $repositoryRelativeInputs): array
{
$parent = $this->parentPath();
if ($parent === '') {
return [];
}
return array_map(static fn (string $input): string => $parent.$input, $repositoryRelativeInputs);
}
private function parentPath(): string
{
return str_repeat('../', substr_count($this->gitPrefix(), '/'));
}
private function currentHash(string $relativePath): ?string
{
$absolute = $this->projectRoot.DIRECTORY_SEPARATOR.$relativePath;
@@ -129,11 +223,22 @@ final class ChangedFiles
return null;
}
$hash = ContentHash::of($absolute);
$hash = $this->hashOf($relativePath, $absolute);
return $hash === false ? null : $hash;
}
private function hashOf(string $relativePath, string $absolute): string|false
{
$parent = $this->parentPath();
if ($parent !== '' && str_starts_with($relativePath, $parent)) {
return @hash_file('xxh128', $absolute);
}
return ContentHash::of($absolute);
}
/**
* @param array<int, string> $files
* @return array<string, string> path → xxh128 content hash
@@ -151,7 +256,7 @@ final class ChangedFiles
continue;
}
$hash = ContentHash::of($absolute);
$hash = $this->hashOf($file, $absolute);
if ($hash !== false) {
$out[$file] = $hash;
@@ -276,25 +381,14 @@ final class ChangedFiles
return $candidates;
}
$result = $git->result(
['check-ignore', '-z', '--stdin'],
implode("\x00", array_keys($candidates)),
);
$result = $git->checkIgnore(Arr::stringKeys($candidates));
if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) {
throw $this->gitFailure($result);
throw $this->gitFailure(['exitCode' => $result['exitCode'], 'output' => '', 'errorOutput' => $result['errorOutput']]);
}
$output = $result['output'];
if ($output === '') {
return $candidates;
}
foreach (explode("\x00", rtrim($output, "\x00")) as $ignored) {
if ($ignored !== '') {
unset($candidates[$ignored]);
}
foreach ($result['ignored'] as $ignored) {
unset($candidates[$ignored]);
}
return $candidates;
File diff suppressed because it is too large Load Diff
+17 -2
View File
@@ -23,12 +23,13 @@ final readonly class Fingerprint
];
/**
* @param array<int, string> $arguments
* @return array{
* structural: array<string, int|string|null>,
* environmental: array<string, int|string|null>,
* }
*/
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null, array $arguments = []): array
{
$configuration ??= ConfigurationFile::projectDefault();
@@ -48,6 +49,18 @@ final readonly class Fingerprint
$structural['project_prefix'] = $prefix;
}
$externalRoots = ExternalSources::rootsFor($projectRoot, $arguments);
if ($externalRoots !== []) {
$structural['external_roots'] = hash('xxh128', serialize($externalRoots));
}
$includePaths = ExternalSources::includePaths($projectRoot, $arguments);
if ($includePaths !== []) {
$structural['include_path'] = hash('xxh128', serialize($includePaths));
}
return [
'structural' => $structural,
'environmental' => [
@@ -302,10 +315,12 @@ final readonly class Fingerprint
}
try {
return $cache[$key] = ! new Git($projectRoot)->succeeds(['check-ignore', '-q', '--', $relativePath]);
$result = new Git($projectRoot)->checkIgnore([$relativePath]);
} catch (ProcessException) {
return $cache[$key] = true;
}
return $cache[$key] = $result['exitCode'] !== 0;
}
private static function projectPrefix(string $projectRoot): string
+8
View File
@@ -33,6 +33,14 @@ final class SourceScope
'bootstrap/cache',
];
/**
* @return list<string>
*/
public static function noiseDirectories(): array
{
return [...self::TOP_LEVEL_NOISE, ...self::NESTED_NOISE];
}
/**
* @param list<string> $includes Absolute, normalised directory paths.
* @param list<array{path: string, prefix: string, suffix: string}> $excludes Absolute, normalised directory paths with the file name prefix and suffix they apply to.
+1 -1
View File
@@ -115,7 +115,7 @@ final class XdebugRestarter implements Restarter
return Fingerprint::structuralMatches(
$graph->fingerprint(),
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments)),
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments), $arguments),
);
}
}
+7 -2
View File
@@ -20,9 +20,14 @@ final class ComposerProject
return $rootPath;
}
/** @var array{root: array{install_path: string}} $installed */
$installed = require $metadataPath;
$root = is_array($installed) ? ($installed['root'] ?? null) : null;
$installPath = is_array($root) ? ($root['install_path'] ?? null) : null;
return realpath($installed['root']['install_path']) ?: $rootPath;
if (! is_string($installPath)) {
return $rootPath;
}
return realpath($installPath) ?: $rootPath;
}
}
+23 -1
View File
@@ -73,13 +73,35 @@ final readonly class Git
return $this->result($arguments)['exitCode'] === 0;
}
/**
* @param array<int, string> $paths
* @return array{exitCode: int, ignored: array<int, string>, errorOutput: string}
*/
public function checkIgnore(array $paths): array
{
$result = $this->result(
['check-ignore', '-z', '--stdin'],
implode("\x00", array_map(static fn (string $path): string => './'.$path, $paths)),
);
$ignored = [];
foreach (explode("\x00", rtrim($result['output'], "\x00")) as $path) {
if ($path !== '') {
$ignored[] = str_starts_with($path, './') ? substr($path, 2) : $path;
}
}
return ['exitCode' => $result['exitCode'], 'ignored' => $ignored, 'errorOutput' => $result['errorOutput']];
}
/**
* @param array<int, string> $arguments
* @return array{exitCode: int, output: string, errorOutput: string}
*/
public function result(array $arguments, ?string $input = null): array
{
$process = new Process(['git', ...$arguments], $this->directory, ['LC_ALL' => 'C', 'LANGUAGE' => '']);
$process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']);
$process->setTimeout($this->timeout);
if ($input !== null) {
+98 -1
View File
@@ -2002,8 +2002,15 @@
✓ it keeps a tracked outside change and drops an untracked ignored one
✓ it keeps a tracked project change that the ignore rules match
✓ it reads committed paths from the repository root even when git is told to be relative
✓ it tells a working tree change outside the project from a committed one
✓ it keeps a changed file whose name is a number as a string
✓ it keeps a changed file outside the project whose name is a number as a string
✓ it matches no external root for a changed file whose name is a number
✓ it hashes an external input without reading it into memory
✓ it sees a whitespace change inside an external input
✓ it reports a changed file whose name looks like a pathspec
✓ it reports an external input that the listing no longer names
✓ it reports no change for an external input it cannot read
✓ it keeps a snapshotted file whose name is a number as a string
✓ it keeps a branch whose name is a number as a string
@@ -2073,6 +2080,89 @@
WARN Tests\Unit\Plugins\Tia\DeletedTestCoverage
- cached hits of a deleted test are dropped while a replayed test stays → Coverage is not available
WARN Tests\Unit\Plugins\Tia\ExternalSources
✓ it finds a psr-4 root that escapes the project
✓ it finds a path repository
✓ it finds a phpunit source directory outside the project
✓ it finds nothing when the project only loads its own code
✓ it finds nothing for a project at the repository root
✓ it reports a root that sits outside the repository as unverifiable
✓ it reports nothing unverifiable when every declaration stays inside the repository
✓ it reports a bootstrap outside the repository as unverifiable
✓ it matches only the changes that fall under an external root
✓ it finds an autoload file that escapes the project and matches it exactly
✓ it finds a phpunit bootstrap that escapes the project
✓ it keeps a declared root that no longer exists on disk
✓ it treats a classmap entry as a file only when it names one
✓ it finds a testsuite directory outside the project
✓ it keeps the directory before a wildcard in a path repository
✓ it keeps the directory before a single character wildcard
✓ it matches a deleted package that a wildcard declared
✓ it covers the whole repository when a declaration reaches its root
✓ it reads the configuration that the command line selects
✓ it accepts the configuration argument in its joined form
✓ it resolves a configuration path against its own directory
✓ it follows a symlink that leaves the project
✓ it keeps a real directory inside the project out of the roots
✓ it finds a bootstrap file that the command line names
✓ it finds every directory that an include path names
✓ it resolves a command line path against the directory the command ran in
✓ it keeps a declaration that a commit deleted under the directory the command ran in
✓ it watches the paths of the configuration Pest generates in the directory the command ran in
✓ it treats a classmap directory that carries a dot as a directory
✓ it accepts the configuration argument attached to its short flag
✓ it reads no configuration when the run asks for none
✓ it reads no default configuration when the command line names one
✓ it finds an include path that the configuration names
✓ it matches a submodule that a commit moved
✓ it matches a submodule that holds a declared file
✓ it reads the configuration of the directory the command ran in
✓ it reads a configuration that a directory argument names
✓ it reads the dist name that phpunit tries before the older one
✓ it finds a bootstrap that a single test suite names
✓ it watches the directory before a wildcard that a configuration names
✓ it lists the files of a root that the repository ignores as ignored inputs
✓ it lists the ignored files under a declared root as ignored inputs
✓ it lists an ignored bootstrap file inside vendor as an ignored input
✓ it lists the ignored files under a declared root inside a dot directory
✓ it lists an ignored link to a file but no ignored link to a directory or to nothing
✓ it watches the path that composer resolved for a path repository
✓ it watches the path that composer installed when the project has no lock file
✓ it watches the path that composer installed into a custom vendor directory
✓ it watches the path that composer installed into the vendor directory the run loaded
✓ it watches the installed path and the locked path when they differ
✓ it reads a path that composer resolved as a literal path
✓ it reads the manifest and the lock file that the COMPOSER variable names
✓ it lists the ignored files when git is told to read every pathspec literally
- it treats a network path as absolute on Windows → Network paths only exist on Windows.
✓ it reports an ignored repository under a declared root as unverifiable
✓ it finds a root that the repository ignores next to a file whose name looks like a pathspec
✓ it reports no repository that sits in a noise directory under a declared root as unverifiable
✓ it reports a repository under an inner declared root even when an outer root counts it as noise
✓ it reports a root inside an ignored repository as unverifiable
✓ it reads a bootstrap whose name holds a wildcard character as a literal file
✓ it reads a psr-4 directory whose name holds a wildcard character as a literal directory
✓ it reads an include path whose name holds a wildcard character as a literal directory
✓ it reads every path of an include path list
✓ it watches the configuration directory when an include path list starts with a separator
✓ it watches nothing for an empty include path, as PHPUnit adds nothing
✓ it resolves every path of an include path list after the first one from the working directory
✓ it watches the directory before a bracket and a brace path as it is
✓ it watches the directory an escaped brace names
✓ it watches every directory a double star pattern reaches like PHPUnit
✓ it also watches a directory whose real name looks like a pattern
✓ it keeps an existing absolute directory with brackets in its path as it is
✓ it watches the directories a bracket pattern matches even when its literal name also exists
✓ it cuts a path at a brace only when the glob of its reader expands braces
✓ it lists no ignored file of the project itself as an ignored input
✓ it keeps the roots of the run when a test changes the working directory
- it keeps the drive letter when it resolves a missing directory against a Windows base → Drive letters exist only on Windows.
✓ it resolves a path that starts with a drive letter against its base outside Windows
- it treats a path from the root of the current drive as absolute on Windows → Paths from the root of the current drive exist only on Windows.
- it keeps the current drive when it resolves a missing path from the root of that drive → Paths from the root of the current drive exist only on Windows.
- it keeps the network share when it resolves a missing directory against a UNC base → UNC paths exist only on Windows.
✓ it reads a leading double slash as the root outside Windows
PASS Tests\Unit\Plugins\Tia\FileState
✓ keysWithPrefix() → it lists keys matching the prefix
✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes
@@ -2083,6 +2173,9 @@
✓ compute() → it excludes gitignored untracked files from the fingerprint
✓ compute() → it keeps the command line bootstrap and include path out of a run that sets neither
✓ compute() → it tells a bootstrap whose name looks like an include path apart from a bootstrap and an include path
✓ compute() → it tells a relative include path from the absolute path it names
✓ compute() → it stores an include path whose name is not utf-8 as text json can encode
✓ compute() → it changes when the order of the include path changes and not when its spelling does
PASS Tests\Unit\Plugins\Tia\Graph
✓ shouldRerunStatus() → it re-runs failures and errors, replays successes
@@ -2441,6 +2534,10 @@
PASS Tests\Unit\Support\Backtrace
✓ it gets file name from called file
PASS Tests\Unit\Support\ComposerProject
✓ it reads the project root that composer recorded
✓ it falls back to the parent of the vendor directory when composer recorded no install path
PASS Tests\Unit\Support\Container
✓ it exists
✓ it gets an instance
@@ -2742,4 +2839,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, 39 skipped, 2019 passed (4528 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2107 passed (4644 assertions)
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('a run without tia finishes when git cannot read the working tree', function (): void {
$project = Project::make('master');
$project->seed('master');
file_put_contents($project->path('.git/index'), 'not an index');
$result = $project->pest();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->not->toContain('could not read the git repository')
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
File diff suppressed because it is too large Load Diff
+48 -6
View File
@@ -9,6 +9,7 @@ use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ByteSafeJson;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\ExternalSources;
use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
@@ -161,14 +162,28 @@ final class Project
return $this->pestWithEnvironment($directory, [], ...$arguments);
}
public function pestFrom(string $directory, string $workingDirectory, string ...$arguments): PestResult
{
return $this->run($directory, $workingDirectory, [], array_values($arguments));
}
/**
* @param array<string, string|false> $environment
*/
public function pestWithEnvironment(string $directory, array $environment, string ...$arguments): PestResult
{
return $this->run($directory, $directory, $environment, array_values($arguments));
}
/**
* @param array<string, string|false> $environment
* @param array<int, string> $arguments
*/
private function run(string $directory, string $workingDirectory, array $environment, array $arguments): PestResult
{
$process = new Process(
[PHP_BINARY, $directory.'/vendor/pestphp/pest/bin/pest', ...$arguments],
$directory,
$workingDirectory,
[
...GitRepo::ENV,
'COLLISION_PRINTER' => 'DefaultPrinter',
@@ -185,6 +200,7 @@ final class Project
'GITHUB_REF_NAME' => false,
'GITLAB_CI' => false,
'CIRCLECI' => false,
'COMPOSER' => false,
...$environment,
],
);
@@ -193,7 +209,7 @@ final class Project
$process->run();
return new PestResult(
array_values($arguments),
$arguments,
$process->getOutput().$process->getErrorOutput(),
(int) $process->getExitCode(),
);
@@ -204,24 +220,50 @@ final class Project
*/
public function seed(string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
{
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration);
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration === null ? [] : ['--configuration', $configuration]);
}
/**
* @param array<int, string> $failing
* @param array<int, string> $arguments
*/
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], array $arguments = []): void
{
$this->graphRoot = $root;
ExternalSources::flush();
$previous = getcwd();
if ($previous !== false) {
chdir($root);
}
try {
$this->seedGraphFor($root, $branch, $sentinel, $failing, $arguments);
} finally {
if ($previous !== false) {
chdir($previous);
}
}
}
/**
* @param array<int, string> $failing
* @param array<int, string> $arguments
*/
private function seedGraphFor(string $root, string $branch, bool $sentinel, array $failing, array $arguments): void
{
putenv('COMPOSER');
$changedFiles = new ChangedFiles($root);
$sha = new GitRepo($root)->sha();
$graph = new Graph($root);
$graph->setFingerprint(Fingerprint::compute($root, $configuration === null ? null : ConfigurationFile::at($root.DIRECTORY_SEPARATOR.$configuration)));
$graph->setFingerprint(Fingerprint::compute($root, ConfigurationFile::fromArguments($arguments), $arguments));
$graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
$graph->setLastRunTree($branch, $changedFiles->baselineTree($sha, ExternalSources::ignoredInputs($root, $arguments)));
$graph->markKnownTestFiles(array_keys(self::EDGES));
+116
View File
@@ -3,6 +3,7 @@
declare(strict_types=1);
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ExternalSources;
use Pest\Plugins\Tia\Fingerprint;
use Symfony\Component\Process\Process;
use Tests\Fixtures\Tia\GitRepo;
@@ -289,6 +290,21 @@ it('reads committed paths from the repository root even when git is told to be r
->and($changedFiles->outsideProject())->toBe(['frontend/widget.php']);
})->skipOnWindows();
it('tells a working tree change outside the project from a committed one', function (): void {
$monorepo = tiaMonorepoRepository();
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
$monorepo['repo']->commit('rework the widget');
file_put_contents($monorepo['root'].'/frontend/other.php', "<?php\n\$other = 1;\n");
$changedFiles = new ChangedFiles($monorepo['project']);
$changedFiles->since($monorepo['sha']);
expect($changedFiles->outsideProject())->toBe(['frontend/widget.php', 'frontend/other.php'])
->and($changedFiles->outsideProjectDirty())->toBe(['frontend/other.php']);
})->skipOnWindows();
it('keeps a changed file whose name is a number as a string', function (): void {
$project = Project::make();
$sha = $project->git()->sha();
@@ -312,6 +328,106 @@ it('keeps a changed file outside the project whose name is a number as a string'
->and($changedFiles->outsideProject())->toBe(['123']);
})->skipOnWindows();
it('matches no external root for a changed file whose name is a number', function (): void {
$monorepo = tiaMonorepoRepository();
$previous = (string) getcwd();
mkdir($monorepo['root'].'/packages/shared/src', 0755, true);
file_put_contents($monorepo['root'].'/packages/shared/src/Shared.php', "<?php\n\$shared = 1;\n");
file_put_contents($monorepo['project'].'/composer.json', (string) json_encode([
'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']],
], JSON_PRETTY_PRINT));
$monorepo['repo']->commit('let the project load a sibling package');
$sha = $monorepo['repo']->sha();
file_put_contents($monorepo['root'].'/123', "changed\n");
$monorepo['repo']->commit('add a file with a numeric name');
chdir($monorepo['project']);
ExternalSources::flush();
try {
$changedFiles = new ChangedFiles($monorepo['project']);
$changedFiles->since($sha);
$matched = ExternalSources::matching($monorepo['project'], $changedFiles->outsideProject());
} finally {
chdir($previous);
ExternalSources::flush();
}
expect($matched)->toBeEmpty();
})->skipOnWindows();
it('hashes an external input without reading it into memory', function (): void {
$monorepo = tiaMonorepoRepository();
$handle = fopen($monorepo['root'].'/frontend/database.sqlite', 'wb');
ftruncate($handle, 64 * 1024 * 1024);
fclose($handle);
$changedFiles = new ChangedFiles($monorepo['project']);
memory_reset_peak_usage();
$before = memory_get_peak_usage();
$tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/database.sqlite']);
expect(memory_get_peak_usage() - $before)->toBeLessThan(8 * 1024 * 1024)
->and($tree)->toHaveKey('../frontend/database.sqlite');
})->skipOnWindows();
it('sees a whitespace change inside an external input', function (): void {
$monorepo = tiaMonorepoRepository();
file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n");
$changedFiles = new ChangedFiles($monorepo['project']);
$tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/data.js']);
file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n");
expect($changedFiles->changedSinceLastRun([], ['frontend/data.js'], $tree))->toBe([[], ['frontend/data.js']]);
})->skipOnWindows();
it('reports a changed file whose name looks like a pathspec', function (): void {
$monorepo = tiaMonorepoRepository();
file_put_contents($monorepo['project'].'/:(fixtures).php', "<?php\n");
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))->toContain(':(fixtures).php');
})->skipOnWindows();
it('reports an external input that the listing no longer names', function (): void {
$monorepo = tiaMonorepoRepository();
file_put_contents($monorepo['root'].'/frontend/generated.php', "<?php\n");
$changedFiles = new ChangedFiles($monorepo['project']);
$before = $changedFiles->externalInputHashes(['frontend/generated.php']);
expect($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes([])))->toBe(['frontend/generated.php'])
->and($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes(['frontend/generated.php'])))->toBeEmpty();
})->skipOnWindows();
it('reports no change for an external input it cannot read', function (): void {
$monorepo = tiaMonorepoRepository();
file_put_contents($monorepo['root'].'/frontend/secret.php', "<?php\n");
chmod($monorepo['root'].'/frontend/secret.php', 0000);
try {
$changedFiles = new ChangedFiles($monorepo['project']);
expect($changedFiles->changedExternalInputs(
$changedFiles->externalInputHashes(['frontend/secret.php']),
$changedFiles->externalInputHashes(['frontend/secret.php']),
))->toBeEmpty();
} finally {
chmod($monorepo['root'].'/frontend/secret.php', 0644);
}
})->skipOnWindows()->skip(function_exists('posix_geteuid') && posix_geteuid() === 0, 'root reads every file.');
it('keeps a snapshotted file whose name is a number as a string', function (): void {
$project = Project::make();
File diff suppressed because it is too large Load Diff
+57
View File
@@ -3,6 +3,7 @@
declare(strict_types=1);
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\ExternalSources;
use Pest\Plugins\Tia\Fingerprint;
use Symfony\Component\Process\Process;
@@ -107,6 +108,7 @@ describe('compute()', function (): void {
fingerprintRemoveDirectory($clone);
}
});
it('keeps the command line bootstrap and include path out of a run that sets neither', function (): void {
$root = fingerprintRepository();
@@ -133,4 +135,59 @@ describe('compute()', function (): void {
fingerprintRemoveDirectory($root);
}
});
it('tells a relative include path from the absolute path it names', function (): void {
$root = (string) realpath(fingerprintRepository());
$previous = getcwd();
chdir($root);
try {
$relativeFirst = Fingerprint::compute($root, null, ['--include-path', '.'.PATH_SEPARATOR.$root]);
$absoluteFirst = Fingerprint::compute($root, null, ['--include-path', $root.PATH_SEPARATOR.'.']);
expect(Fingerprint::structuralMatches($relativeFirst, $absoluteFirst))->toBeFalse();
} finally {
chdir((string) $previous);
fingerprintRemoveDirectory($root);
}
});
it('stores an include path whose name is not utf-8 as text json can encode', function (): void {
$root = (string) realpath(fingerprintRepository());
mkdir($root.'/app');
file_put_contents($root.'/app/composer.json', '{}');
fingerprintGit($root, 'add', '-A');
fingerprintGit($root, 'commit', '-q', '-m', 'init');
$previous = getcwd();
chdir($root.'/app');
ExternalSources::flush();
try {
$fingerprint = Fingerprint::compute($root.'/app', null, ['--include-path', "../optional-\xff"]);
expect($fingerprint['structural'])->toHaveKeys(['external_roots', 'include_path'])
->and(json_encode($fingerprint))->toBeString();
} finally {
chdir((string) $previous);
ExternalSources::flush();
fingerprintRemoveDirectory($root);
}
});
it('changes when the order of the include path changes and not when its spelling does', function (): void {
$root = (string) realpath(fingerprintRepository());
mkdir($root.'/a');
mkdir($root.'/b');
try {
$forward = Fingerprint::compute($root, null, ['--include-path', $root.'/a'.PATH_SEPARATOR.$root.'/b']);
$respelled = Fingerprint::compute($root, null, ['--include-path', $root.'/./a/'.PATH_SEPARATOR.$root.'/b']);
$reversed = Fingerprint::compute($root, null, ['--include-path', $root.'/b'.PATH_SEPARATOR.$root.'/a']);
expect(Fingerprint::structuralMatches($forward, $respelled))->toBeTrue()
->and(Fingerprint::structuralMatches($forward, $reversed))->toBeFalse();
} finally {
fingerprintRemoveDirectory($root);
}
});
});
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Pest\Support\ComposerProject;
use Symfony\Component\Process\Process;
it('reads the project root that composer recorded', function (): void {
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-composer-project-'.bin2hex(random_bytes(8));
mkdir($root.'/app/lib/deps/composer', 0755, true);
file_put_contents($root.'/app/lib/deps/composer/installed.php', "<?php\n\nreturn ['root' => ['install_path' => ".var_export($root.'/app', true)."]];\n");
try {
expect(ComposerProject::rootPath($root.'/app/lib/deps/autoload.php'))->toBe(realpath($root.'/app'));
} finally {
new Process(['rm', '-rf', $root])->run();
}
})->skipOnWindows();
it('falls back to the parent of the vendor directory when composer recorded no install path', function (): void {
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-composer-project-'.bin2hex(random_bytes(8));
mkdir($root.'/vendor/composer', 0755, true);
file_put_contents($root.'/vendor/composer/installed.php', "<?php\n\nreturn ['root' => ['name' => '__root__'], 'versions' => []];\n");
try {
expect(ComposerProject::rootPath($root.'/vendor/autoload.php'))->toBe(realpath($root));
} finally {
new Process(['rm', '-rf', $root])->run();
}
})->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, 31 skipped, 1888 passed (3998 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 36 skipped, 1976 passed (4114 assertions)';
expect($output)
->toContain("Tests: {$expected}")