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>
This commit is contained in:
Maks Oleksyuk
2026-11-20 21:33:33 +02:00
committed by GitHub
parent 996b5ee8f5
commit 9a6ceb0699
6 changed files with 592 additions and 61 deletions
+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");
@@ -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
+22 -1
View File
@@ -1941,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
@@ -2602,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, 1894 passed (4340 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1915 passed (4368 assertions)
+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);
}
});
});
+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, 1767 passed (3815 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1788 passed (3843 assertions)';
expect($output)
->toContain("Tests: {$expected}")