fix(parallel): support --include-path (#2075)

* fix(parallel): support --include-path

* fix(parallel): keep an include path with an equals sign in the parent process

* fix(parallel): apply the include path before the bootstrap file

* chore(rector): skip the parallel include path fixture

* fix(parallel): apply the command line include path before the XML one in the bootstrap file

Register `--include-path` on the ParaTest command, so ParaTest passes it to
the PHPUnit configuration of the parent process. PHPUnit then puts the
command line paths before the XML `<includePath>` before it includes the
`--bootstrap` file.

Read the value and the arguments the option consumes through PHPUnit's
`Builder`, and write the value back in a form that PHPUnit reads unchanged,
for the parent process and for each worker. Run the include path handler
first, so it reads only the arguments of the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(parallel): declare strict types and refresh the success snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
Jhon Farias
2026-12-03 21:18:02 +01:00
committed by GitHub
parent f5874c12ca
commit 12bddc0137
18 changed files with 429 additions and 1 deletions
+1
View File
@@ -19,6 +19,7 @@
<directory suffix=".php">./tests-external</directory>
<exclude>./tests/.snapshots</exclude>
<exclude>./tests/Fixtures/Inheritance</exclude>
<exclude>./tests/Fixtures/ParallelIncludePath</exclude>
<exclude>./tests/Fixtures/Suites</exclude>
<exclude>./tests/Fixtures/Tia</exclude>
</testsuite>
+1
View File
@@ -28,6 +28,7 @@ return RectorConfig::configure()
__DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php',
__DIR__.'/tests/Fixtures/Arch',
__DIR__.'/tests/Fixtures/Suites',
__DIR__.'/tests/Fixtures/ParallelIncludePath',
ReturnNeverTypeRector::class,
ArrowFunctionDelegatingCallToFirstClassCallableRector::class,
NarrowObjectReturnTypeRector::class,
+2
View File
@@ -26,6 +26,7 @@ final class Parallel implements HandlesArguments
private const string GLOBAL_PREFIX = 'PEST_PARALLEL_GLOBAL_';
private const array HANDLERS = [
Parallel\Handlers\IncludePath::class,
Parallel\Handlers\Parallel::class,
Parallel\Handlers\Pest::class,
Parallel\Handlers\Laravel::class,
@@ -150,6 +151,7 @@ final class Parallel implements HandlesArguments
$command->setVersion(version());
Parallel\Handlers\StopOn::configureOptions($command->find('paratest')->getDefinition());
Parallel\Handlers\IncludePath::configureOptions($command->find('paratest')->getDefinition());
return $command;
}
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Handlers;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugins\Parallel as ParallelPlugin;
use Pest\Plugins\Parallel\Contracts\HandlersWorkerArguments;
use Pest\Subscribers\EnsureCommandLineIncludePathComesFirst;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\Configuration;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Throwable;
final class IncludePath implements HandlersWorkerArguments, HandlesArguments
{
private const string OPTION = '--include-path';
private const string GLOBAL_KEY = 'INCLUDE_PATH';
private const string PROGRAM = 'pest';
public function handleArguments(array $arguments): array
{
$arguments = array_values($arguments);
$includePath = null;
$argumentsForParatest = [];
$separatorAndArgumentsAfterIt = [];
for ($index = 0; $index < count($arguments); $index++) {
$argument = trim($arguments[$index]);
if ($argument === '--') {
$separatorAndArgumentsAfterIt = array_slice($arguments, $index);
break;
}
if ($argument === self::OPTION || str_starts_with($argument, self::OPTION.'=')) {
$optionArguments = $this->optionArgumentsPhpunitReads($arguments, $index);
$includePath = $this->includePathPhpunitReads($optionArguments);
$index += count($optionArguments) - 1;
continue;
}
$argumentsForParatest[] = $arguments[$index];
}
ParallelPlugin::setGlobal(self::GLOBAL_KEY, $includePath === null ? false : base64_encode($includePath));
if ($includePath !== null) {
$commandLineIncludePathComesFirst = new EnsureCommandLineIncludePathComesFirst($includePath);
$commandLineIncludePathComesFirst->apply();
EventFacade::instance()->registerSubscriber($commandLineIncludePathComesFirst);
}
if ($includePath !== null && $this->survivesThePhpunitParser($includePath)) {
array_push($argumentsForParatest, ...$this->argumentsPhpunitReadsAs($includePath));
}
return [...$argumentsForParatest, ...$separatorAndArgumentsAfterIt];
}
public static function configureOptions(InputDefinition $definition): void
{
$definition->addOption(new InputOption(substr(self::OPTION, 2), null, InputOption::VALUE_REQUIRED));
}
public function handleWorkerArguments(array $arguments): array
{
$encodedIncludePath = ParallelPlugin::getGlobal(self::GLOBAL_KEY);
$includePath = is_string($encodedIncludePath) ? base64_decode($encodedIncludePath, true) : false;
if (! is_string($includePath) || $includePath === '') {
return $arguments;
}
return [...$arguments, ...$this->argumentsPhpunitReadsAs($includePath)];
}
/**
* @param list<string> $arguments
* @return list<string>
*/
private function optionArgumentsPhpunitReads(array $arguments, int $index): array
{
if ($this->phpunitConfiguration([$arguments[$index]]) instanceof Configuration) {
return [$arguments[$index]];
}
return array_slice($arguments, $index, 2);
}
/**
* @param list<string> $optionArguments
*/
private function includePathPhpunitReads(array $optionArguments): ?string
{
$configuration = $this->phpunitConfiguration($optionArguments);
return $configuration instanceof Configuration && $configuration->hasIncludePath() ? $configuration->includePath() : null;
}
/**
* @param list<string> $parameters
*/
private function phpunitConfiguration(array $parameters): ?Configuration
{
try {
return new Builder(EventFacade::emitter())->fromParameters([self::PROGRAM, ...$parameters]);
} catch (Throwable) {
return null;
}
}
/**
* @return list<string>
*/
private function argumentsPhpunitReadsAs(string $includePath): array
{
if (! $this->survivesThePhpunitParser($includePath)) {
return [self::OPTION, $includePath];
}
return [self::OPTION.'='.$includePath.$this->closingEqualsSignThatStopsTheTrim($includePath)];
}
private function closingEqualsSignThatStopsTheTrim(string $includePath): string
{
return rtrim($includePath) === $includePath ? '' : '=';
}
private function survivesThePhpunitParser(string $includePath): bool
{
return $includePath !== '' && ! str_contains($includePath, '=');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Pest\Subscribers;
use PHPUnit\Event\TestRunner\EventFacadeSealed;
use PHPUnit\Event\TestRunner\EventFacadeSealedSubscriber;
final readonly class EnsureCommandLineIncludePathComesFirst implements EventFacadeSealedSubscriber
{
/**
* @var list<string>
*/
private array $directories;
public function __construct(string $includePath)
{
$this->directories = array_values(array_filter(
explode(PATH_SEPARATOR, $includePath),
fn (string $directory): bool => $directory !== '',
));
}
public function notify(EventFacadeSealed $event): void
{
$this->apply();
}
public function apply(): void
{
if ($this->directories === []) {
return;
}
$otherDirectories = array_filter(
explode(PATH_SEPARATOR, (string) get_include_path()),
fn (string $directory): bool => ! in_array($directory, $this->directories, true),
);
ini_set('include_path', implode(PATH_SEPARATOR, [...$this->directories, ...$otherDirectories]));
}
}
+29 -1
View File
@@ -2736,6 +2736,34 @@
✓ parallel group-filtered run is not considered empty when a worker ends on a fully filtered file
✓ parallel group-filtered run still fails when the selection matches no tests
PASS Tests\Visual\ParallelIncludePath
✓ parallel resolves requires through the include path with dataset "value in the same argument"
✓ parallel resolves requires through the include path with dataset "value as a separate argument"
✓ parallel resolves requires through the include path with dataset "absolute path"
✓ parallel resolves requires through the include path with dataset "several paths"
✓ parallel resolves requires through the include path with dataset "directory name with an equals sign"
✓ parallel resolves requires through the include path with dataset "absolute directory name with an equals sign"
✓ parallel resolves requires through the include path with dataset "require in the bootstrap file"
✓ parallel resolves requires through the include path with dataset "command line before the XML include path"
✓ parallel resolves requires through the include path with dataset "command line before the XML include path in the bootstrap file"
✓ parallel places the include path before the argument separator
✓ parallel fails to resolve requires without the include path
PASS Tests\Visual\ParallelIncludePathLeadingSpace
✓ parallel keeps the leading space of an include path in the same argument as serial phpunit does
PASS Tests\Visual\ParallelIncludePathOptionWithLeadingSpace
✓ parallel reads an include path option with a leading space as serial phpunit does
PASS Tests\Visual\ParallelIncludePathTrailingSpace
✓ parallel workers keep the trailing space of an include path as serial phpunit does
PASS Tests\Visual\ParallelIncludePathWhitespace
✓ parallel accepts an include path of whitespace as serial phpunit does
PASS Tests\Visual\ParallelIncludePathWithoutValue
✓ parallel keeps the pest runner when the include path option has no value
PASS Tests\Visual\ParallelNestedDatasets
✓ parallel loads nested datasets from nested directories
@@ -2854,4 +2882,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, 2120 passed (4671 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2136 passed (4703 assertions)
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../../vendor/autoload.php">
<php>
<includePath>ParallelIncludePath/xml-lib</includePath>
</php>
</phpunit>
@@ -0,0 +1,11 @@
<?php
$valueRequiredWhileLoading = require 'parallel-include-path.inc';
test('requires a file through the include path while loading', function () use ($valueRequiredWhileLoading) {
expect($valueRequiredWhileLoading)->toBe('resolved through the include path');
});
test('requires a file through the include path while running', function () {
expect(require 'parallel-include-path.inc')->toBe('resolved through the include path');
});
@@ -0,0 +1,7 @@
<?php
require_once __DIR__.'/../../../vendor/autoload.php';
if ((require 'parallel-include-path.inc') !== 'resolved through the include path') {
throw new RuntimeException('The bootstrap file did not resolve the command line include path first.');
}
@@ -0,0 +1,3 @@
<?php
return 'resolved through the include path';
@@ -0,0 +1,3 @@
<?php
return 'resolved through the include path';
@@ -0,0 +1,3 @@
<?php
throw new RuntimeException('The XML include path came before the command line include path.');
+53
View File
@@ -0,0 +1,53 @@
<?php
use Symfony\Component\Process\Process;
$run = function (array $arguments): Process {
$process = new Process(
['php', 'bin/pest', '--parallel', '--processes=2', ...$arguments, 'tests/Fixtures/ParallelIncludePath'],
dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
);
$process->run();
return $process;
};
test('parallel resolves requires through the include path', function (array $arguments) use ($run): void {
$process = $run($arguments);
$output = (string) removeAnsiEscapeSequences($process->getOutput());
expect($process->getExitCode())->toBe(0, $process->getErrorOutput().$output)
->and($output)->toContain('Tests: 2 passed');
})->with([
'value in the same argument' => [['--include-path=tests/Fixtures/ParallelIncludePath/lib']],
'value as a separate argument' => [['--include-path', 'tests/Fixtures/ParallelIncludePath/lib']],
'absolute path' => [['--include-path='.__DIR__.'/../Fixtures/ParallelIncludePath/lib']],
'several paths' => [['--include-path=tests/Fixtures/Inheritance'.PATH_SEPARATOR.'tests/Fixtures/ParallelIncludePath/lib']],
'directory name with an equals sign' => [['--include-path', 'tests/Fixtures/ParallelIncludePath/include=path']],
'absolute directory name with an equals sign' => [['--include-path', __DIR__.'/../Fixtures/ParallelIncludePath/include=path']],
'require in the bootstrap file' => [['--bootstrap=tests/Fixtures/ParallelIncludePath/bootstrap.inc', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
'command line before the XML include path' => [['--configuration=tests/Fixtures/ParallelIncludePath.xml', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
'command line before the XML include path in the bootstrap file' => [['--configuration=tests/Fixtures/ParallelIncludePath.xml', '--bootstrap=tests/Fixtures/ParallelIncludePath/bootstrap.inc', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
])->skipOnWindows();
test('parallel places the include path before the argument separator', function (): void {
$process = new Process(
['php', '-r', 'require "vendor/autoload.php"; echo json_encode((new Pest\\Plugins\\Parallel\\Handlers\\IncludePath)->handleArguments(["--include-path", "lib", "--", "tests/Foo"]));'],
dirname(__DIR__, 2),
);
$process->run();
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true))->toBe(['--include-path=lib', '--', 'tests/Foo']);
});
test('parallel fails to resolve requires without the include path', function () use ($run): void {
$process = $run([]);
$output = (string) removeAnsiEscapeSequences($process->getOutput().$process->getErrorOutput());
expect($process->getExitCode())->not->toBe(0)
->and($output)->toContain("Failed opening required 'parallel-include-path.inc'");
})->skipOnWindows();
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('parallel keeps the leading space of an include path in the same argument as serial phpunit does', function (): void {
$script = <<<'PHP_WRAP'
require "vendor/autoload.php";
$serial = (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["--include-path= lib"])->includePath();
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
$forwarded = $handler->handleArguments(["--include-path= lib"]);
echo json_encode(["serial" => $serial, "forwarded" => $forwarded, "first" => explode(PATH_SEPARATOR, get_include_path())[0], "worker" => $handler->handleWorkerArguments([])]);
PHP_WRAP;
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true))->toBe([
'serial' => ' lib',
'forwarded' => ['--include-path= lib'],
'first' => ' lib',
'worker' => ['--include-path= lib'],
]);
});
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('parallel reads an include path option with a leading space as serial phpunit does', function (): void {
$script = <<<'PHP_WRAP'
require "vendor/autoload.php";
$arguments = ["--include-path=first", " --include-path=lib"];
$serial = (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["phpunit", ...$arguments])->includePath();
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
$forwarded = $handler->handleArguments($arguments);
echo json_encode(["serial" => $serial, "forwarded" => $forwarded, "worker" => $handler->handleWorkerArguments([])]);
PHP_WRAP;
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true))->toBe([
'serial' => 'lib',
'forwarded' => ['--include-path=lib'],
'worker' => ['--include-path=lib'],
]);
});
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('parallel workers keep the trailing space of an include path as serial phpunit does', function (): void {
$script = <<<'PHP_WRAP'
require "vendor/autoload.php";
$read = fn (array $arguments): string => (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["phpunit", ...$arguments])->includePath();
$arguments = ["--include-path=lib =extra"];
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
$forwarded = $handler->handleArguments($arguments);
echo json_encode(["serial" => $read($arguments), "forwarded" => $read($forwarded), "worker" => $read($handler->handleWorkerArguments([]))]);
PHP_WRAP;
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true))->toBe([
'serial' => 'lib ',
'forwarded' => 'lib ',
'worker' => 'lib ',
]);
});
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('parallel accepts an include path of whitespace as serial phpunit does', function (): void {
$process = new Process(
['php', 'bin/pest', '--parallel', '--processes=2', '--configuration=tests/Fixtures/ParallelIncludePath.xml', '--include-path', ' '],
dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
);
$process->run();
$output = (string) removeAnsiEscapeSequences($process->getOutput().$process->getErrorOutput());
expect($output)->not->toContain('Required argument for option "--include-path" is missing')
->and($process->getExitCode())->toBe(0, $output);
})->skipOnWindows();
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('parallel keeps the pest runner when the include path option has no value', function (): void {
$script = <<<'PHP_WRAP'
require "vendor/autoload.php";
$handlers = array_values(array_intersect(
(new ReflectionClassConstant(Pest\Plugins\Parallel::class, "HANDLERS"))->getValue(),
[Pest\Plugins\Parallel\Handlers\Parallel::class, Pest\Plugins\Parallel\Handlers\IncludePath::class],
));
$forwarded = array_reduce($handlers, fn (array $arguments, string $handler): array => (new $handler)->handleArguments($arguments), ["--parallel", "--include-path="]);
echo json_encode(["runner" => in_array("--runner=".Pest\Plugins\Parallel\Paratest\WrapperRunner::class, $forwarded, true)]);
PHP_WRAP;
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true))->toBe(['runner' => true]);
});