Compare commits

...

4 Commits

Author SHA1 Message Date
Maks Oleksyuk 9a6ceb0699 feat: let a shard unit bundle several test classes (#1829)
* feat: let a shard unit bundle several test classes

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

* fix: own unknown shard units in every shard and clean up worker timings

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

* fix: drop removed test classes from shard units and consume coverage option values

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

* fix: preserve empty shard units and consume more option values in discovery

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 01:03:33 +05:30
Jeremy Braband 996b5ee8f5 [5.x] TIA: stat once in ReadCapture::url_stat() (#2038)
* Stat once in ReadCapture url_stat

* Keep quiet url_stat probes away from error handlers

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 00:33:18 +05:30
Florian 776a44a391 Add an observer for the exit code after output plugins (#1905)
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 00:12:46 +05:30
nuno maduro 89999bdaed chore: updates sponsors 2026-11-20 17:07:24 +00:00
12 changed files with 774 additions and 82 deletions
+2 -4
View File
@@ -32,16 +32,14 @@ We cannot thank our sponsors enough for their incredible support in funding Pest
- **[PhpStorm](https://jb.gg/nuno)**
- **[CodeRabbit](https://coderabbit.link/nunomaduro)**
- **[SerpApi](https://serpapi.com/?ref=nunomaduro)**
- **[Bento](https://bentonow.com/?ref=nunomaduro)**
- **[CMS Max](https://cmsmax.com/?ref=nunomaduro)**
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
- **[Typesense](https://typesense.org/?ref=nunomaduro)**
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)**
- **[NativePHP](https://nativephp.com/?ref=nunomaduro)**
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
- [Zapiet](https://zapiet.com/?ref=nunomaduro)
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
- [Route4Me](https://route4me.com/?ref=nunomaduro)
- [Nerdify](https://getnerdify.com/?ref=nunomaduro)
- [Pushery](https://www.pushery.com/?ref=nunomaduro)
- [LFCarry](https://lfcarry.com/?ref=nunomaduro)
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Pest\Contracts\Plugins;
interface ObservesExitCode
{
public function observeExitCode(int $exitCode): void;
}
+8 -4
View File
@@ -7,20 +7,24 @@ namespace Pest\Plugins\Actions;
use Pest\Contracts\Plugins;
use Pest\Plugin\Loader;
/**
* @internal
*/
final class CallsAddsOutput
{
public static function execute(int $exitCode): int
{
$plugins = Loader::getPlugins(Plugins\AddsOutput::class);
/** @var Plugins\AddsOutput $plugin */
foreach ($plugins as $plugin) {
assert($plugin instanceof Plugins\AddsOutput);
$exitCode = $plugin->addOutput($exitCode);
}
foreach (Loader::getPlugins(Plugins\ObservesExitCode::class) as $plugin) {
assert($plugin instanceof Plugins\ObservesExitCode);
$plugin->observeExitCode($exitCode);
}
return $exitCode;
}
}
+1 -1
View File
@@ -146,7 +146,7 @@ final readonly class Help implements HandlesArguments
],
[
'arg' => '--update-shards',
'desc' => 'Update shards.json with test timing data for time-balanced sharding',
'desc' => 'Update the shards file with timing data for time-balanced sharding',
],
], ...$content['Execution']];
+260 -57
View File
@@ -43,6 +43,23 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $updateShards = false;
private static ?string $timingsFilename = null;
/**
* @var array<string, float|array{time: float, tests: list<string>}>|null
*/
private static ?array $externalTimings = null;
/**
* @var array<string, bool>|null
*/
private static ?array $ownership = null;
/**
* @var array<string, scalar>
*/
private static array $metadata = [];
private static bool $timeBalanced = false;
private static bool $shardsOutdated = false;
@@ -50,7 +67,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $passed = false;
/**
* @var array<string, float>|null
* @var array<string, float|array{time: float, tests: list<string>}>|null
*/
private static ?array $collectedTimings = null;
@@ -65,6 +82,48 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
//
}
public static function useTimingsFile(string $filename): void
{
self::$timingsFilename = $filename;
}
/**
* @param array<string, float|array{time: float, tests: list<string>}> $units
* @param array<string, scalar> $metadata Stored alongside the units, and read back
* by {@see self::metadata()} on sharded runs.
*/
public static function useTimings(array $units, array $metadata = []): void
{
self::$externalTimings = $units;
if ($metadata !== []) {
self::$metadata = $metadata;
}
}
/**
* @return array<string, scalar>
*/
public static function metadata(): array
{
return self::$metadata;
}
public static function owns(string $unit): bool
{
if (self::$ownership === null) {
return true;
}
if (! isset(self::$ownership[$unit])) {
self::$shardsOutdated = true;
return true;
}
return self::$ownership[$unit];
}
/**
* {@inheritDoc}
*/
@@ -98,20 +157,33 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$tests = $this->allTests($arguments);
$timings = $this->loadShardsFile();
if ($timings !== null) {
$knownTests = array_values(array_filter($tests, fn (string $test): bool => isset($timings[$test])));
$newTests = array_values(array_diff($tests, $knownTests));
$units = $this->loadShardsFile();
if ($units !== null) {
$hasRemovedTests = array_diff($this->testsOf($units), $tests) !== [];
$partitions = $this->partitionByTime($knownTests, $timings, $total);
$units = $this->withoutRemovedTests($units, $tests);
$newTests = array_values(array_diff($tests, $this->testsOf($units)));
$partitions = $this->partitionByTime($units, $total);
$median = $this->medianTime($units);
foreach ($newTests as $i => $test) {
$partitions[$i % $total][] = $test;
$partitions[$i % $total][$test] = ['time' => $median, 'tests' => [$test]];
}
$testsToRun = $partitions[$index - 1] ?? [];
$selected = $partitions[$index - 1] ?? [];
self::$ownership = [];
foreach ($partitions as $i => $partition) {
self::$ownership += array_fill_keys(array_keys($partition), $i === $index - 1);
}
self::$timeBalanced = true;
self::$shardsOutdated = $newTests !== [];
self::$shardsOutdated = $newTests !== [] || $hasRemovedTests;
$testsToRun = array_values(array_intersect($tests, $this->testsOf($selected)));
} else {
$isInCurrentShard = fn (int $key): bool => $key % $total === ($index - 1);
$testsToRun = array_values(array_filter($tests, $isInCurrentShard, ARRAY_FILTER_USE_KEY));
@@ -198,7 +270,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
}
if ($argument === '--runner') {
if (in_array($argument, ['--runner', '--processes'], strict: true)) {
$skipNext = true;
continue;
@@ -222,7 +294,28 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
*/
private function buildListTestsCommand(array $arguments, string $testPath): array
{
$filtered = $this->removeParallelArguments($arguments);
$filtered = [];
$skipNext = false;
foreach ($this->removeParallelArguments($arguments) as $argument) {
if ($skipNext) {
$skipNext = false;
if (! str_starts_with($argument, '-')) {
continue;
}
}
if (preg_match('/^--(?:coverage-(?:php|html|clover|xml|cobertura|crap4j|openclover|jsonl|filter)|min|exactly)$/', $argument) === 1) {
$skipNext = true;
continue;
}
if (! str_starts_with($argument, '--coverage')) {
$filtered[] = $argument;
}
}
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests'];
}
@@ -314,15 +407,16 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
{
self::$passed = $exitCode === 0;
if (self::$updateShards && self::$passed && ! Parallel::isWorker()) {
if (self::$updateShards && (self::$passed || self::$externalTimings !== null) && ! Parallel::isWorker()) {
self::$collectedTimings = $this->collectTimings();
}
$count = self::$knownTests !== null
? count(array_intersect_key(self::$collectedTimings, array_flip(self::$knownTests)))
: count(self::$collectedTimings);
if (self::$collectedTimings !== null && self::$collectedTimings !== []) {
$count = count($this->unitsToWrite(self::$collectedTimings));
$this->output->writeln(sprintf(
' <fg=gray>Shards:</> <fg=default>shards.json updated with timings for %d test class%s.</>',
' <fg=gray>Shards:</> <fg=default>%s updated with timings for %d test class%s.</>',
$this->timingsFilename(),
$count,
$count === 1 ? '' : 'es',
));
@@ -350,7 +444,10 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
));
if (self::$shardsOutdated) {
$this->output->writeln(' <fg=yellow;options=bold>WARN</> <fg=default>The [tests/.pest/shards.json] file is out of date. Run [--update-shards] to update it.</>');
$this->output->writeln(sprintf(
' <fg=yellow;options=bold>WARN</> <fg=default>The [%s] file is out of date. Run [--update-shards] to update it.</>',
$this->relativeTimingsPath(),
));
}
return $exitCode;
@@ -368,7 +465,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return;
}
if (! self::$passed) {
if (! self::$passed && self::$externalTimings === null) {
return;
}
@@ -382,17 +479,17 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
/**
* @return array<string, float>
* @return array<string, float|array{time: float, tests: list<string>}>
*/
private function collectTimings(): array
{
$runId = Parallel::getGlobal('SHARD_RUN_ID');
if (is_string($runId)) {
return $this->readWorkerTimings($runId);
}
$collected = is_string($runId)
? $this->readWorkerTimings($runId)
: EnsureShardTimingsAreCollected::timings();
return EnsureShardTimingsAreCollected::timings();
return self::$externalTimings ?? $collected;
}
private function writeWorkerTimings(): void
@@ -447,15 +544,46 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return $merged;
}
private function timingsFilename(): string
{
return self::$timingsFilename ?? 'shards.json';
}
private function relativeTimingsPath(): string
{
return implode(DIRECTORY_SEPARATOR, [TestSuite::getInstance()->testPath, '.pest', $this->timingsFilename()]);
}
private function shardsPath(): string
{
$testSuite = TestSuite::getInstance();
return implode(DIRECTORY_SEPARATOR, [$testSuite->rootPath, $testSuite->testPath, '.pest', 'shards.json']);
return TestSuite::getInstance()->rootPath.DIRECTORY_SEPARATOR.$this->relativeTimingsPath();
}
/**
* @return array<string, float>|null
* @param array<string, mixed> $units
* @return array<string, array{time: float, tests: list<string>}>
*/
private function normaliseUnits(array $units): array
{
$normalised = [];
foreach ($units as $key => $unit) {
if (is_array($unit) && isset($unit['time']) && isset($unit['tests']) && is_array($unit['tests'])) {
$normalised[$key] = ['time' => (float) $unit['time'], 'tests' => array_values(array_map(strval(...), $unit['tests']))];
continue;
}
if (is_float($unit) || is_int($unit)) {
$normalised[$key] = ['time' => (float) $unit, 'tests' => [$key]];
}
}
return $normalised;
}
/**
* @return array<string, array{time: float, tests: list<string>}>|null
*/
private function loadShardsFile(): ?array
{
@@ -468,50 +596,95 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$contents = file_get_contents($path);
if ($contents === false) {
throw new InvalidOption('The [tests/.pest/shards.json] file could not be read. Delete it or run [--update-shards] to regenerate.');
throw new InvalidOption(sprintf('The [%s] file could not be read. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
}
$data = json_decode($contents, true);
if (! is_array($data) || ! isset($data['timings']) || ! is_array($data['timings'])) {
throw new InvalidOption('The [tests/.pest/shards.json] file is corrupted. Delete it or run [--update-shards] to regenerate.');
$units = null;
if (is_array($data)) {
$units = $data['units'] ?? $data['timings'] ?? null;
}
return $data['timings'];
if (! is_array($units)) {
throw new InvalidOption(sprintf('The [%s] file is corrupted. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
}
if (isset($data['metadata']) && is_array($data['metadata'])) {
self::$metadata = array_filter($data['metadata'], is_scalar(...));
}
return $this->normaliseUnits($units);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @param list<string> $tests
* @param array<string, float> $timings
* @return list<list<string>>
* @return array<string, array{time: float, tests: list<string>}>
*/
private function partitionByTime(array $tests, array $timings, int $total): array
private function withoutRemovedTests(array $units, array $tests): array
{
$knownTimings = array_filter(
array_map(fn (string $test): ?float => $timings[$test] ?? null, $tests),
fn (?float $t): bool => $t !== null,
);
$live = [];
$median = $knownTimings !== [] ? $this->median(array_values($knownTimings)) : 1.0;
foreach ($units as $key => $unit) {
$declared = $unit['tests'];
$unit['tests'] = array_values(array_intersect($declared, $tests));
$testsWithTimings = array_map(
fn (string $test): array => ['test' => $test, 'time' => $timings[$test] ?? $median],
$tests,
);
if ($declared === [] || $unit['tests'] !== []) {
$live[$key] = $unit;
}
}
usort($testsWithTimings, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
return $live;
}
/** @var list<list<string>> */
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<string>
*/
private function testsOf(array $units): array
{
$tests = [];
foreach ($units as $unit) {
foreach ($unit['tests'] as $test) {
$tests[$test] = true;
}
}
return array_keys($tests);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
*/
private function medianTime(array $units): float
{
$times = array_column($units, 'time');
return $times === [] ? 1.0 : $this->median($times);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<array<string, array{time: float, tests: list<string>}>>
*/
private function partitionByTime(array $units, int $total): array
{
uasort($units, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
/** @var list<array<string, array{time: float, tests: list<string>}>> */
$bins = array_fill(0, $total, []);
/** @var non-empty-list<float> */
$binTimes = array_fill(0, $total, 0.0);
foreach ($testsWithTimings as $item) {
foreach ($units as $key => $unit) {
$minIndex = array_search(min($binTimes), $binTimes, strict: true);
assert(is_int($minIndex));
$bins[$minIndex][] = $item['test'];
$binTimes[$minIndex] += $item['time'];
$bins[$minIndex][$key] = $unit;
$binTimes[$minIndex] += $unit['time'];
}
return $bins;
@@ -535,9 +708,32 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
/**
* @param array<string, float> $timings
* @param array<string, float|array{time: float, tests: list<string>}> $units
* @return array<string, array{time: float, tests: list<string>}>
*/
private function writeTimings(array $timings): void
private function unitsToWrite(array $units): array
{
$units = $this->normaliseUnits($units);
if (self::$knownTests === null) {
return $units;
}
$known = self::$knownTests;
$units = array_filter($units, fn (array $unit): bool => $unit['tests'] === [] || array_intersect($unit['tests'], $known) !== []);
foreach (array_diff($known, $this->testsOf($units)) as $test) {
$units[$test] = ['time' => 0.0, 'tests' => [$test]];
}
return $units;
}
/**
* @param array<string, float|array{time: float, tests: list<string>}> $units
*/
private function writeTimings(array $units): void
{
$path = $this->shardsPath();
@@ -546,18 +742,25 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
mkdir($directory, 0755, true);
}
if (self::$knownTests !== null) {
$knownSet = array_flip(self::$knownTests);
$timings = array_intersect_key($timings, $knownSet);
}
$bundled = self::$externalTimings !== null && array_filter($units, is_array(...)) !== [];
ksort($timings);
$units = $this->unitsToWrite($units);
$canonical = self::$knownTests ?? array_keys($timings);
ksort($units);
$canonical = self::$knownTests ?? $this->testsOf($units);
sort($canonical);
$payload = $bundled
? ['units' => $units]
: ['timings' => array_map(fn (array $unit): float => $unit['time'], $units)];
if (self::$metadata !== []) {
$payload['metadata'] = self::$metadata;
}
file_put_contents($path, json_encode([
'timings' => $timings,
...$payload,
'checksum' => md5(implode("\n", $canonical)),
'updated_at' => date('c'),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
+5 -13
View File
@@ -286,21 +286,13 @@ final class ReadCapture
public function url_stat(string $path, int $flags): array|false
{
return $this->withOriginalWrapper(function () use ($path, $flags): array|false {
$isQuiet = ($flags & STREAM_URL_STAT_QUIET) !== 0;
set_error_handler(static fn (): bool => true);
if (($flags & STREAM_URL_STAT_LINK) !== 0) {
if ($isQuiet && ! is_link($path) && ! file_exists($path)) {
return false;
}
return @lstat($path);
try {
return ($flags & STREAM_URL_STAT_LINK) !== 0 ? lstat($path) : stat($path);
} finally {
restore_error_handler();
}
if ($isQuiet && ! file_exists($path)) {
return false;
}
return @stat($path);
});
}
@@ -54,7 +54,7 @@
EXECUTION OPTIONS:
--parallel ........................................... Run tests in parallel
--update-snapshots Update snapshots for tests using the "toMatchSnapshot" expectation
--update-shards Update shards.json with test timing data for time-balanced sharding
--update-shards Update the shards file with timing data for time-balanced sharding
--globals-backup ................. Backup and restore $GLOBALS for each test
--static-backup ......... Backup and restore static properties for each test
--strict-coverage ................... Be strict about code coverage metadata
+32 -1
View File
@@ -1860,6 +1860,15 @@
PASS Tests\Unit\Overrides\ThrowableBuilder
✓ collision editor can be added to the stack trace
PASS Tests\Unit\Plugins\Actions\CallsAddsOutput
✓ exit code observers run after every output plugin
✓ exit code observers receive unchanged codes when there are no output plugins with (0)
✓ exit code observers receive unchanged codes when there are no output plugins with (1)
✓ exit code observers receive unchanged codes when there are no output plugins with (2)
✓ exit code observers receive unchanged codes when there are no output plugins with (42)
✓ output plugins work without exit code observers
✓ exit code observers are not called when an output plugin throws
PASS Tests\Unit\Plugins\Concerns\HandleArguments
✓ method hasArgument with ('--long-argument', true)
✓ method hasArgument with ('-a', true)
@@ -1932,6 +1941,27 @@
✓ addOutput → it displays shard information after test execution
✓ addOutput → it uses singular form for single test file
✓ addOutput → it returns original exit code when shard is not set
✓ timings file → it reads and writes shards.json until a plugin overrides the filename
✓ timings file → it prefers timings supplied by a plugin over the ones collected from the test run
✓ timings file → it records known tests without supplied timings as zero
✓ timings file → it keeps timings supplied by a plugin even when the test suite did not pass
✓ timings file → it strips coverage arguments when building the list-tests command
✓ timings file → it strips the separate path of a coverage argument when building the list-tests command
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-jsonl')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-filter')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--min')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--exactly')
✓ timings file → it strips the separate value of the parallel processes option when building the list-tests command
✓ timings file → it keeps a unit saved with no test classes, but drops one emptied by removed classes
✓ timings file → it drops test classes that no longer exist from the stored units
✓ units → it treats a bare timing as a unit bundling only its own test class
✓ units → it keeps the test classes a unit bundles together in one shard
✓ units → it owns every unit when the run is not time-balanced
✓ units → it owns only the units allocated to the current shard
✓ units → it owns a unit the timings file does not know in every shard, and reports the file as out of date
✓ units → it keeps a unit that bundles no test class when writing
✓ units → it collects every test class the given units bundle
✓ units → it writes bundled units, and reads back both shapes
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
✓ it fingerprints the path and the content of the configuration file
@@ -2070,6 +2100,7 @@
✓ the file wrapper → it is restored when the recorder resets
✓ the file wrapper → it passes filesystem operations through while a test records
✓ the file wrapper → it writes with LOCK_EX while a test records
✓ the file wrapper → it reports a missing path to the error handler as plain PHP does while a test records
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file"
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link"
✓ a wrapper already registered for file:// → it opens reads through it and still links them
@@ -2592,4 +2623,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, 38 skipped, 1886 passed (4325 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1915 passed (4368 assertions)
@@ -0,0 +1,114 @@
<?php
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\ObservesExitCode;
use Pest\Plugin\Loader;
use Pest\Plugins\Actions\CallsAddsOutput;
function withExitCodePlugins(array $plugins, Closure $test): void
{
$loader = new ReflectionClass(Loader::class);
$instances = $loader->getProperty('instances');
$loaded = $loader->getProperty('loaded');
$previousInstances = $instances->getValue();
$previousLoaded = $loaded->getValue();
try {
$instances->setValue(null, $plugins);
$loaded->setValue(null, true);
$test();
} finally {
$instances->setValue(null, $previousInstances);
$loaded->setValue(null, $previousLoaded);
}
}
test('exit code observers run after every output plugin', function (): void {
$events = new ArrayObject;
$observer = new readonly class($events) implements ObservesExitCode
{
public function __construct(private ArrayObject $events) {}
public function observeExitCode(int $exitCode): void
{
$this->events[] = ['observed', $exitCode];
}
};
$output = new readonly class($events) implements AddsOutput
{
public function __construct(private ArrayObject $events) {}
public function addOutput(int $exitCode): int
{
$this->events[] = ['output', $exitCode];
return $exitCode + 1;
}
};
withExitCodePlugins([$observer, $output, clone $observer, clone $output], function () use ($events): void {
expect(CallsAddsOutput::execute(0))->toBe(2)
->and($events->getArrayCopy())->toBe([
['output', 0],
['output', 1],
['observed', 2],
['observed', 2],
]);
});
});
test('exit code observers receive unchanged codes when there are no output plugins', function (int $exitCode): void {
$observer = new class implements ObservesExitCode
{
public ?int $exitCode = null;
public function observeExitCode(int $exitCode): void
{
$this->exitCode = $exitCode;
}
};
withExitCodePlugins([$observer], function () use ($observer, $exitCode): void {
expect(CallsAddsOutput::execute($exitCode))->toBe($exitCode)
->and($observer->exitCode)->toBe($exitCode);
});
})->with([0, 1, 2, 42]);
test('output plugins work without exit code observers', function (): void {
$output = new class implements AddsOutput
{
public function addOutput(int $exitCode): int
{
return 42;
}
};
withExitCodePlugins([$output], function (): void {
expect(CallsAddsOutput::execute(0))->toBe(42);
});
});
test('exit code observers are not called when an output plugin throws', function (): void {
$observer = new class implements ObservesExitCode
{
public bool $called = false;
public function observeExitCode(int $exitCode): void
{
$this->called = true;
}
};
$output = new class implements AddsOutput
{
public function addOutput(int $exitCode): int
{
throw new RuntimeException('Output failed');
}
};
withExitCodePlugins([$observer, $output], function () use ($observer): void {
expect(fn (): int => CallsAddsOutput::execute(0))->toThrow(RuntimeException::class, 'Output failed')
->and($observer->called)->toBeFalse();
});
});
+307
View File
@@ -2,6 +2,8 @@
use Pest\Exceptions\InvalidOption;
use Pest\Plugins\Shard;
use Pest\Subscribers\EnsureShardTimingsAreCollected;
use Pest\Support\Arr;
use SebastianBergmann\CliParser\Parser;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\BufferedOutput;
@@ -624,3 +626,308 @@ describe('addOutput', function (): void {
->and($outputText)->not->toContain('Shard:');
});
});
describe('timings file', function (): void {
afterEach(function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('timingsFilename')->setValue(null, null);
$reflection->getProperty('externalTimings')->setValue(null, null);
$reflection->getProperty('collectedTimings')->setValue(null, null);
$reflection->getProperty('knownTests')->setValue(null, null);
$reflection->getProperty('updateShards')->setValue(null, false);
$reflection->getProperty('shard')->setValue(null, null);
new ReflectionClass(EnsureShardTimingsAreCollected::class)
->getProperty('timings')
->setValue(null, []);
});
it('reads and writes shards.json until a plugin overrides the filename', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('shardsPath');
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'shards.json');
Shard::useTimingsFile('mutation-shards.json');
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'mutation-shards.json');
});
it('prefers timings supplied by a plugin over the ones collected from the test run', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
new ReflectionClass(EnsureShardTimingsAreCollected::class)
->getProperty('timings')
->setValue(null, ['Tests\\Unit\\CollectedTest' => 9.0]);
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
$method = new ReflectionClass($shard)->getMethod('collectTimings');
expect($method->invoke($shard))->toBe(['Tests\\Unit\\SuppliedTest' => 1.5]);
});
it('records known tests without supplied timings as zero', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\MutatedTest', 'Tests\\Unit\\PlainTest']);
Shard::useTimingsFile('shards-fixture.json');
Shard::useTimings($timings = ['Tests\\Unit\\MutatedTest' => 4.5]);
$path = $reflection->getMethod('shardsPath')->invoke($shard);
try {
$reflection->getMethod('writeTimings')->invoke($shard, $timings);
expect(json_decode((string) file_get_contents($path), true)['timings'])->toEqual([
'Tests\\Unit\\MutatedTest' => 4.5,
'Tests\\Unit\\PlainTest' => 0.0,
]);
} finally {
@unlink($path);
}
});
it('keeps timings supplied by a plugin even when the test suite did not pass', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
new ReflectionClass($shard)->getProperty('updateShards')->setValue(null, true);
Shard::useTimingsFile('mutation-shards.json');
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
$paratest = Arr::get($_SERVER, 'PARATEST');
unset($_SERVER['PARATEST']);
try {
expect($shard->addOutput(1))->toBe(1)
->and($output->fetch())->toContain('mutation-shards.json updated with timings for 1 test class.');
} finally {
if ($paratest !== null) {
$_SERVER['PARATEST'] = $paratest;
}
}
});
it('strips coverage arguments when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--coverage-php=/tmp/coverage.php', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('strips the separate path of a coverage argument when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--coverage-php', '/tmp/coverage.php', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('strips the separate value of a coverage option when building the list-tests command', function (string $option): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', $option, '/tmp/value', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
})->with(['--coverage-jsonl', '--coverage-filter', '--min', '--exactly']);
it('strips the separate value of the parallel processes option when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--parallel', '--processes', '4', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('keeps a unit saved with no test classes, but drops one emptied by removed classes', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
$units = [
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
'src/Emptied.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
];
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
]);
});
it('drops test classes that no longer exist from the stored units', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
$units = [
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
'Tests\\Unit\\RemovedTest' => ['time' => 100.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest', 'Tests\\Unit\\RemovedTest']],
];
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest']],
]);
});
});
describe('units', function (): void {
afterEach(function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('timingsFilename')->setValue(null, null);
$reflection->getProperty('externalTimings')->setValue(null, null);
$reflection->getProperty('collectedTimings')->setValue(null, null);
$reflection->getProperty('knownTests')->setValue(null, null);
$reflection->getProperty('ownership')->setValue(null, null);
$reflection->getProperty('shardsOutdated')->setValue(null, false);
});
it('treats a bare timing as a unit bundling only its own test class', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('normaliseUnits');
expect($method->invoke($shard, ['Tests\\Unit\\FooTest' => 1.5]))->toBe([
'Tests\\Unit\\FooTest' => ['time' => 1.5, 'tests' => ['Tests\\Unit\\FooTest']],
]);
});
it('keeps the test classes a unit bundles together in one shard', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('partitionByTime');
$partitions = $method->invoke($shard, [
'app/Heavy.php' => ['time' => 10.0, 'tests' => ['Tests\\Unit\\OneTest', 'Tests\\Unit\\TwoTest']],
'app/Light.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\ThreeTest']],
'app/Medium.php' => ['time' => 4.0, 'tests' => ['Tests\\Unit\\FourTest']],
], 2);
expect(array_keys($partitions[0]))->toBe(['app/Heavy.php'])
->and(array_keys($partitions[1]))->toBe(['app/Medium.php', 'app/Light.php']);
});
it('owns every unit when the run is not time-balanced', function (): void {
expect(Shard::owns('app/Anything.php'))->toBeTrue();
});
it('owns only the units allocated to the current shard', function (): void {
new ReflectionClass(Shard::class)->getProperty('ownership')->setValue(null, [
'app/Mine.php' => true,
'app/Theirs.php' => false,
]);
expect(Shard::owns('app/Mine.php'))->toBeTrue()
->and(Shard::owns('app/Theirs.php'))->toBeFalse()
->and(new ReflectionClass(Shard::class)->getProperty('shardsOutdated')->getValue())->toBeFalse();
});
it('owns a unit the timings file does not know in every shard, and reports the file as out of date', function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('ownership')->setValue(null, ['app/Theirs.php' => false]);
expect(Shard::owns('app/New.php'))->toBeTrue()
->and($reflection->getProperty('shardsOutdated')->getValue())->toBeTrue();
});
it('keeps a unit that bundles no test class when writing', function (): void {
$shard = new Shard(new BufferedOutput);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest']);
expect(array_keys($reflection->getMethod('unitsToWrite')->invoke($shard, [
'app/Uncovered.php' => ['time' => 0.0, 'tests' => []],
'app/Gone.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\GoneTest']],
])))->toBe(['app/Uncovered.php', 'Tests\\Unit\\FooTest']);
});
it('collects every test class the given units bundle', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('testsOf');
expect($method->invoke($shard, [
'app/One.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']],
'app/Two.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\BarTest']],
]))->toBe(['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
});
it('writes bundled units, and reads back both shapes', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
Shard::useTimingsFile('units-fixture.json');
Shard::useTimings($units = [
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
]);
$path = $reflection->getMethod('shardsPath')->invoke($shard);
try {
$reflection->getMethod('writeTimings')->invoke($shard, $units);
expect(json_decode((string) file_get_contents($path), true))->toHaveKey('units')
->and($reflection->getMethod('loadShardsFile')->invoke($shard))->toEqual([
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
'Tests\\Unit\\BarTest' => ['time' => 0.0, 'tests' => ['Tests\\Unit\\BarTest']],
]);
} finally {
@unlink($path);
}
});
});
+33
View File
@@ -205,6 +205,39 @@ describe('the file wrapper', function (): void {
}
});
it('reports a missing path to the error handler as plain PHP does while a test records', function (): void {
$missing = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-missing-'.bin2hex(random_bytes(8));
$warnings = [];
$results = [];
set_error_handler(function (int $level, string $message) use (&$warnings): bool {
$warnings[] = $message;
return true;
});
try {
tiaReadCaptureLinks(function () use ($missing, &$warnings, &$results): void {
clearstatcache();
$results['quiet'] = [file_exists($missing), is_file($missing), is_dir($missing), is_link($missing)];
$results['warnings after quiet probes'] = count($warnings);
$results['stat'] = stat($missing);
$results['warnings after stat'] = count($warnings);
});
} finally {
restore_error_handler();
}
expect($results)->toBe([
'quiet' => [false, false, false, false],
'warnings after quiet probes' => 0,
'stat' => false,
'warnings after stat' => 1,
]);
});
it('reports symlinks as links while a test records', function (bool $targetExists, bool $expectedExists): void {
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-'.bin2hex(random_bytes(8));
mkdir($directory);
+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, 30 skipped, 1759 passed (3800 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1788 passed (3843 assertions)';
expect($output)
->toContain("Tests: {$expected}")