From 89cdbd5bc905fea55860aa93d2a7f7ff320b00af Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Sat, 14 Nov 2026 13:03:34 -0300 Subject: [PATCH] Support --profile when running tests in parallel (#1795) * feat: support profiling parallel tests * test: preserve success snapshot totals * test: preserve visual suite snapshot * fix: stabilize checks on pull requests * fix: align TIA fixture branch resolution * chore: keep parallel profile changes scoped * fix: align TIA fixture branch resolution * Revert unrelated TIA branch fallback change --------- Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com> --- .../Parallel/Paratest/ResultPrinter.php | 12 +- .../Parallel/Support/CompactPrinter.php | 10 +- src/Plugins/Profile.php | 119 +++++++++++++++++- tests/Visual/Parallel.php | 8 +- 4 files changed, 141 insertions(+), 8 deletions(-) diff --git a/src/Plugins/Parallel/Paratest/ResultPrinter.php b/src/Plugins/Parallel/Paratest/ResultPrinter.php index 72b952c0..2e5f131b 100644 --- a/src/Plugins/Parallel/Paratest/ResultPrinter.php +++ b/src/Plugins/Parallel/Paratest/ResultPrinter.php @@ -6,6 +6,8 @@ namespace Pest\Plugins\Parallel\Paratest; use ParaTest\Options; use Pest\Plugins\Parallel\Support\CompactPrinter; +use Pest\Plugins\Profile; +use Pest\Result; use Pest\Support\StateGenerator; use PHPUnit\TestRunner\TestResult\TestResult; use PHPUnit\TextUI\Output\Printer; @@ -130,6 +132,8 @@ final class ResultPrinter */ public function printResults(TestResult $testResult, array $teamcityFiles, array $testdoxFiles, Duration $duration): void { + $profile = Profile::results(); + if ($this->options->needsTeamcity) { $teamcityProgress = $this->tailMultiple($teamcityFiles); @@ -166,7 +170,13 @@ final class ResultPrinter if (! isset($_SERVER['PEST_PARALLEL_NO_OUTPUT'])) { $this->compactPrinter->errors($state); - $this->compactPrinter->recap($state, $testResult, $duration, $this->options); + $this->compactPrinter->recap( + $state, + $testResult, + $duration, + $this->options, + Result::ok($this->options->configuration, $testResult) ? $profile : [], + ); } } diff --git a/src/Plugins/Parallel/Support/CompactPrinter.php b/src/Plugins/Parallel/Support/CompactPrinter.php index ee70d845..a46bb5c6 100644 --- a/src/Plugins/Parallel/Support/CompactPrinter.php +++ b/src/Plugins/Parallel/Support/CompactPrinter.php @@ -6,6 +6,7 @@ namespace Pest\Plugins\Parallel\Support; use NunoMaduro\Collision\Adapters\Phpunit\State; use NunoMaduro\Collision\Adapters\Phpunit\Style; +use NunoMaduro\Collision\Adapters\Phpunit\TestResult; use ParaTest\Options; use PHPUnit\Event\Telemetry\CpuTime; use PHPUnit\Event\Telemetry\GarbageCollectorStatus; @@ -96,7 +97,10 @@ final class CompactPrinter $this->style->writeErrorsSummary($state); } - public function recap(State $state, PHPUnitTestResult $testResult, Duration $duration, Options $options): void + /** + * @param list $profile + */ + public function recap(State $state, PHPUnitTestResult $testResult, Duration $duration, Options $options, array $profile = []): void { assert($this->output instanceof ConsoleOutput); @@ -156,5 +160,9 @@ final class CompactPrinter "\n", "\n", ]); + + if ($profile !== []) { + $this->style->writeSlowTests($profile, $telemetry); + } } } diff --git a/src/Plugins/Profile.php b/src/Plugins/Profile.php index 0f723a2c..c954ded7 100644 --- a/src/Plugins/Profile.php +++ b/src/Plugins/Profile.php @@ -4,29 +4,138 @@ declare(strict_types=1); namespace Pest\Plugins; +use const DIRECTORY_SEPARATOR; + +use NunoMaduro\Collision\Adapters\Phpunit\TestResult; use Pest\Contracts\Plugins\HandlesArguments; -use Pest\Exceptions\InvalidOption; +use PHPUnit\Event; +use PHPUnit\Event\Telemetry\HRTime; +use PHPUnit\Event\Test\Finished; +use PHPUnit\Event\Test\FinishedSubscriber; +use PHPUnit\Event\Test\PreparationStarted; +use PHPUnit\Event\Test\PreparationStartedSubscriber; /** * @internal */ final class Profile implements HandlesArguments { - use Concerns\HandleArguments; + /** @var array */ + private static array $startTimes = []; /** * {@inheritDoc} */ public function handleArguments(array $arguments): array { - if (! $this->hasArgument('--profile', $arguments)) { + $runId = Parallel::getGlobal('PROFILE_RUN_ID'); + + if (! isset($_SERVER['COLLISION_PRINTER_PROFILE']) && ! is_string($runId)) { return $arguments; } - if ($this->hasArgument('--parallel', $arguments)) { - throw new InvalidOption('The [--profile] option is not supported when running in parallel.'); + if (Parallel::isWorker() && is_string($runId)) { + Event\Facade::instance()->registerSubscriber(new class implements PreparationStartedSubscriber + { + public function notify(PreparationStarted $event): void + { + Profile::started($event); + } + }); + + Event\Facade::instance()->registerSubscriber(new class implements FinishedSubscriber + { + public function notify(Finished $event): void + { + Profile::finished($event); + } + }); + + return $arguments; + } + + if (Parallel::isEnabled()) { + Parallel::setGlobal('PROFILE_RUN_ID', bin2hex(random_bytes(16))); } return $arguments; } + + public static function started(PreparationStarted $event): void + { + self::$startTimes[$event->test()->id()] = $event->telemetryInfo()->time(); + } + + public static function finished(Finished $event): void + { + $test = $event->test(); + + if (! isset(self::$startTimes[$test->id()])) { + return; + } + + $duration = $event->telemetryInfo()->time()->duration(self::$startTimes[$test->id()]); + $result = TestResult::fromPestParallelTestCase($test, TestResult::PASS); + $result->setDuration($duration->asFloat() * 1000); + + unset(self::$startTimes[$test->id()]); + + $runId = Parallel::getGlobal('PROFILE_RUN_ID'); + + if (is_string($runId)) { + file_put_contents( + self::resultPath($runId), + base64_encode(serialize($result)).PHP_EOL, + FILE_APPEND | LOCK_EX, + ); + } + } + + /** @return list */ + public static function results(): array + { + $runId = Parallel::getGlobal('PROFILE_RUN_ID'); + + if (! is_string($runId)) { + return []; + } + + $path = self::resultPath($runId); + + if (! is_file($path)) { + return []; + } + + $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + unlink($path); + + if ($lines === false) { + return []; + } + + $results = []; + + foreach ($lines as $line) { + $serializedResult = base64_decode($line, true); + + if ($serializedResult === false) { + continue; + } + + $result = unserialize($serializedResult, ['allowed_classes' => [TestResult::class]]); + + if ($result instanceof TestResult) { + $results[] = $result; + } + } + + usort($results, fn (TestResult $a, TestResult $b): int => $b->duration <=> $a->duration); + + return array_slice($results, 0, 10); + } + + private static function resultPath(string $runId): string + { + return sys_get_temp_dir().DIRECTORY_SEPARATOR.'__pest_profile_'.$runId.'.txt'; + } } diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 7b1072db..73af80d7 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -19,12 +19,18 @@ $run = function (): ?string { test('parallel', function () use ($run): void { $output = $run('--exclude-group=integration'); $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, 29 skipped, 1636 passed (3623 assertions)'; expect($output) ->toContain("Tests: {$expected}") - ->toContain('Parallel: 3 processes'); + ->and( + str_contains($output, 'Parallel: 3 processes') + && str_contains((string) $profileOutput, 'Top 10 slowest tests:') + && str_contains((string) $profileOutput, 'can pass with comparison') + && str_contains((string) $profileOutput, 'can also pass'), + )->toBeTrue(); })->skipOnWindows(); test('a parallel test can extend another test with same name', function () use ($run): void {