Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion bin/worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,10 @@
exit;
}

$exitCode = $application->runTest(realpath(trim($testPath)));
[$testFile, $testFilter] = array_pad(explode("\0", trim($testPath), 2), 2, null);
$testPath = realpath($testFile).($testFilter === null ? '' : "\0".$testFilter);

$exitCode = $application->runTest($testPath);

fwrite($statusFile, (string) $exitCode);
fflush($statusFile);
Expand Down
13 changes: 11 additions & 2 deletions overrides/Runner/TestSuiteLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ final class TestSuiteLoader
*/
private static array $declaredClasses = [];

/**
* @psalm-var array<string, ReflectionClass>
*/
private static array $classesBySuiteClassFile = [];

public function __construct()
{
if (empty(self::$declaredClasses)) {
Expand All @@ -53,6 +58,10 @@ public function __construct()
*/
public function load(string $suiteClassFile): ReflectionClass
{
if (array_key_exists($suiteClassFile, self::$classesBySuiteClassFile)) {
return self::$classesBySuiteClassFile[$suiteClassFile];
}

$suiteClassName = $this->classNameFromFileName($suiteClassFile);

(static function () use ($suiteClassFile) {
Expand Down Expand Up @@ -151,7 +160,7 @@ public function load(string $suiteClassFile): ReflectionClass
// @codeCoverageIgnoreEnd

if ($class->isSubclassOf(TestCase::class) && ! $class->isAbstract()) {
return $class;
return self::$classesBySuiteClassFile[$suiteClassFile] = $class;
}

if ($class->hasMethod('suite')) {
Expand All @@ -164,7 +173,7 @@ public function load(string $suiteClassFile): ReflectionClass
// @codeCoverageIgnoreEnd

if (! $method->isAbstract() && $method->isPublic() && $method->isStatic()) {
return $class;
return self::$classesBySuiteClassFile[$suiteClassFile] = $class;
}
}

Expand Down
3 changes: 3 additions & 0 deletions overrides/TextUI/TestSuiteFilterProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use Pest\Plugins\Only;
use Pest\Runner\Filter\EnsureTestCaseIsInitiatedFilter;
use Pest\TestSuite as PestTestSuite;
use PHPUnit\Event;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Metadata\Api\Groups;
Expand All @@ -36,6 +37,8 @@ public function __construct(private Event\Emitter $emitter) {}
*/
public function process(Configuration $configuration, TestSuite $suite): void
{
PestTestSuite::getInstance()->filteredTestSuite = $suite;

$factory = new Factory;

// @phpstan-ignore-next-line
Expand Down
68 changes: 68 additions & 0 deletions src/Plugins/Parallel/Paratest/WrapperRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use const DIRECTORY_SEPARATOR;

use Generator;
use NunoMaduro\Collision\Adapters\Phpunit\Support\ResultReflection;
use ParaTest\JUnit\LogMerger;
use ParaTest\JUnit\Writer;
Expand All @@ -14,13 +15,17 @@
use ParaTest\WrapperRunner\MissingResultsException;
use ParaTest\WrapperRunner\SuiteLoader;
use ParaTest\WrapperRunner\WrapperWorker;
use Pest\Contracts\HasPrintableTestCaseName;
use Pest\Plugins\Tia;
use Pest\Result;
use Pest\TestSuite;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\Event\Test\AfterLastTestMethodFailed;
use PHPUnit\Event\TestRunner\WarningTriggered;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite as PHPUnitTestSuite;
use PHPUnit\Runner\CodeCoverage;
use PHPUnit\Runner\Phpt\TestCase as PhptTestCase;
use PHPUnit\Runner\TestRunHistory\DefaultTestRunHistory;
use PHPUnit\TestRunner\TestResult\Facade as TestResultFacade;
use PHPUnit\TestRunner\TestResult\TestResult;
Expand All @@ -41,18 +46,25 @@
use function array_merge;
use function array_merge_recursive;
use function array_shift;
use function array_unique;
use function array_values;
use function assert;
use function bin2hex;
use function count;
use function dirname;
use function file_get_contents;
use function filesize;
use function is_file;
use function is_string;
use function iterator_to_array;
use function max;
use function mkdir;
use function preg_quote;
use function property_exists;
use function random_bytes;
use function realpath;
use function rmdir;
use function rtrim;
use function sprintf;
use function str_starts_with;
use function unlink;
Expand Down Expand Up @@ -638,6 +650,10 @@ private function clearFiles(array $files): void
*/
private function getTestFiles(SuiteLoader $suiteLoader): array
{
if ($this->options->functional) {
return $this->getFunctionalTests($suiteLoader);
}

/** @var array<non-empty-string, null> $files */
$files = [];

Expand All @@ -661,6 +677,58 @@ private function getTestFiles(SuiteLoader $suiteLoader): array
return array_keys($files);
}

/**
* @return array<int, non-empty-string>
*/
private function getFunctionalTests(SuiteLoader $suiteLoader): array
{
$testSuite = TestSuite::getInstance()->filteredTestSuite;

assert($testSuite instanceof PHPUnitTestSuite);

$testCases = iterator_to_array($this->testCasesOf($testSuite), false);

assert(count($testCases) === count($suiteLoader->tests));

$tests = [];

foreach ($testCases as $index => $testCase) {
$tests[] = $testCase instanceof HasPrintableTestCaseName
? $this->getFunctionalPestTest($testCase)
: $suiteLoader->tests[$index];
}

return array_values(array_unique($tests));
}

/**
* @return non-empty-string
*/
private function getFunctionalPestTest(HasPrintableTestCaseName&TestCase $testCase): string
{
$className = $testCase::class;

assert(property_exists($className, '__filename') && is_string($className::$__filename));

$name = rtrim($testCase->getPrintableTestCaseMethodName().$testCase->dataSetAsString());

return $className::$__filename."\0/^[^:]+::".preg_quote($name, '/').'$/';
}

/**
* @return Generator<int, TestCase|PhptTestCase>
*/
private function testCasesOf(PHPUnitTestSuite $testSuite): Generator
{
foreach ($testSuite as $test) {
if ($test instanceof PHPUnitTestSuite) {
yield from $this->testCasesOf($test);
} elseif ($test instanceof TestCase || $test instanceof PhptTestCase) {
yield $test;
}
}
}

private function shouldIncludeBootstrappedTestFile(string $filename): bool
{
if (! $this->options->configuration->hasCliArguments()) {
Expand Down
2 changes: 1 addition & 1 deletion src/Plugins/Shard.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private function removeParallelArguments(array $arguments): array
{
return array_values(array_filter(
$arguments,
fn (string $argument): bool => ! in_array($argument, ['--parallel', '-p'], strict: true)
fn (string $argument): bool => ! in_array($argument, ['--parallel', '-p', '--functional'], strict: true)
&& ! str_starts_with($argument, '--processes'),
));
}
Expand Down
3 changes: 3 additions & 0 deletions src/TestSuite.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Pest\Repositories\TestRepository;
use Pest\Support\Str;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite as PHPUnitTestSuite;

/**
* @internal
Expand All @@ -33,6 +34,8 @@ final class TestSuite

public SnapshotRepository $snapshots;

public ?PHPUnitTestSuite $filteredTestSuite = null;

public string $rootPath;

private static ?TestSuite $instance = null;
Expand Down
9 changes: 8 additions & 1 deletion tests/.snapshots/success.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2259,6 +2259,13 @@
✓ parallel reports invalid datasets as failures
✓ parallel can have multiple exclude-groups
✓ parallel can have multiple groups
✓ parallel functional gives each test to a worker on its own
✓ parallel functional runs the tests of a file whose name gives no class name
✓ parallel functional runs the tests of its shard
✓ parallel functional runs the selected cases of tests that share a description across files with dataset "without a filter"
✓ parallel functional runs the selected cases of tests that share a description across files with dataset "filtered by the description"
✓ parallel functional runs the selected cases of tests that share a description across files with dataset "filtered by the file"
✓ parallel functional runs the selected cases of tests that share a description across files with dataset "filtered by the data set"

PASS Tests\Visual\ParallelNestedDatasets
✓ parallel loads nested datasets from nested directories
Expand Down Expand Up @@ -2292,4 +2299,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, 36 skipped, 1624 passed (3587 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 36 skipped, 1631 passed (3602 assertions)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

it('shares a description', function (int $value) {
expect($value)->toBeInt();
})->with(['only first' => 1, 'shared' => 2]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

it('shares a description', function (int $value) {
expect($value)->toBeInt()->toBeGreaterThan(2);
})->with(['only second' => 3, 'shared' => 4]);
17 changes: 17 additions & 0 deletions tests/Fixtures/Suites/ParallelFunctional/Spread/PestTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

it('runs the first test', function () {
expect(true)->toBeTrue();
});

it('runs the second test', function () {
expect(true)->toBeTrue();
});

it('runs the third test', function () {
expect(true)->toBeTrue();
});

test('calls Foo::it runs the third test', function () {
expect(true)->toBeTrue();
});
30 changes: 30 additions & 0 deletions tests/Fixtures/Suites/ParallelFunctional/Spread/PhpUnitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Tests\Fixtures\Suites\ParallelFunctional\Spread;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class PhpUnitTest extends TestCase
{
public function test_it_runs_the_first_test(): void
{
$this->assertTrue(true);
}

#[DataProvider('values')]
public function test_it_runs_a_data_set(int $value): void
{
$this->assertIsInt($value);
}

/**
* @return array<string, array{int}>
*/
public static function values(): array
{
return ['one' => [1], 'two' => [2]];
}
}
32 changes: 32 additions & 0 deletions tests/Visual/Parallel.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,35 @@
->toContain('Tests: 2 passed (2 assertions)')
->toContain('Parallel: 3 processes');
})->skipOnWindows();

test('parallel functional gives each test to a worker on its own', function () use ($run): void {
$output = $run('tests/Fixtures/Suites/ParallelFunctional/Spread', '--functional', '--verbose');

expect(preg_match_all('/executing: .+(PestTest|PhpUnitTest)\.php.+(runs the \w+ test|runs_the_first_test|runs_a_data_set)/', (string) $output))->toBe(7)
->and($output)
->toContain('Tests: 7 passed (7 assertions)')
->toContain('Parallel: 3 processes');
})->skipOnWindows();

test('parallel functional runs the tests of a file whose name gives no class name', function () use ($run): void {
expect($run('tests/PHPUnit/CustomAffixes/@#$%^&()-_=+.php', '--functional'))
->toContain('Tests: 1 passed (1 assertions)')
->toContain('Parallel: 3 processes');
})->skipOnWindows();

test('parallel functional runs the tests of its shard', function () use ($run): void {
expect($run('tests/Fixtures/Suites/ParallelFunctional', '--functional', '--shard=1/2'))
->toContain('Tests: 6 passed (6 assertions)')
->toContain('Shard: 1 of 2 — 2 files ran, out of 4.');
})->skipOnWindows();

test('parallel functional runs the selected cases of tests that share a description across files', function (array $arguments, string $expected) use ($run): void {
expect($run('tests/Fixtures/Suites/ParallelFunctional/SameDescription', '--functional', ...$arguments))
->toContain("Tests: {$expected}")
->toContain('Parallel: 3 processes');
})->with([
'without a filter' => [[], '4 passed (6 assertions)'],
'filtered by the description' => [['--filter=shares a description'], '4 passed (6 assertions)'],
'filtered by the file' => [['--filter=SecondTest'], '2 passed (4 assertions)'],
'filtered by the data set' => [['--filter=shared'], '2 passed (3 assertions)'],
])->skipOnWindows();