Skip to content

Commit c0ff210

Browse files
schlesseraclaude
andcommitted
Collect code coverage in parallel workers and shards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cb149a3 commit c0ff210

4 files changed

Lines changed: 123 additions & 10 deletions

File tree

‎bin/run-behat-tests‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -341,18 +341,18 @@ if [ -n "${PARALLEL}" ] && [ "${PARALLEL}" != "1" ]; then
341341
if ! is_numeric "${PARALLEL}"; then
342342
echo "Warning: WP_CLI_TEST_PARALLEL is not a number of workers, running the scenarios one after the other." >&2
343343
PARALLEL=""
344-
elif [[ "${WP_CLI_TEST_COVERAGE}" == "true" ]]; then
345-
echo "Code coverage is collected, running the scenarios one after the other." >&2
346-
PARALLEL=""
347344
elif [ "${WP_CLI_TEST_DBTYPE-}" != "sqlite" ] && ! ${DB_CLIENT} ${HOST_STRING} --user="${USER}" ${PASSWORD_ARG} --execute="CREATE DATABASE IF NOT EXISTS \`${DBNAME}_1\`; DROP DATABASE \`${DBNAME}_1\`;" 2>/dev/null; then
348345
echo "Warning: The test user cannot create the databases of parallel workers, running the scenarios one after the other." >&2
349346
echo "Run 'composer prepare-tests' once to allow it." >&2
350347
PARALLEL=""
351348
fi
352349
fi
353350

354-
if [ -n "${PARALLEL}" ] && [ "${PARALLEL}" != "1" ]; then
355-
exec php "$WP_CLI_TESTS_ROOT"/utils/behat-parallel.php "${PARALLEL}" --snippets-for="WP_CLI\Tests\Context\FeatureContext" "${FORMAT_ARGS[@]}" "$BEHAT_TAGS" --strict "${BEHAT_EXTRA_ARGS[@]}" -- "$@"
351+
# WP_CLI_TEST_SHARD set to "<index>/<total>", for example "2/3", runs only that share of the
352+
# scenarios, so that the suite can be split across several machines. Every share is picked
353+
# from the same cost-balanced distribution, so together they cover every scenario exactly once.
354+
if [ -n "${WP_CLI_TEST_SHARD-}" ] || { [ -n "${PARALLEL}" ] && [ "${PARALLEL}" != "1" ]; }; then
355+
exec php "$WP_CLI_TESTS_ROOT"/utils/behat-parallel.php "${PARALLEL:-1}" --snippets-for="WP_CLI\Tests\Context\FeatureContext" "${FORMAT_ARGS[@]}" "$BEHAT_TAGS" --strict "${BEHAT_EXTRA_ARGS[@]}" -- "$@"
356356
fi
357357

358358
vendor/bin/behat --snippets-for="WP_CLI\Tests\Context\FeatureContext" "${FORMAT_ARGS[@]}" "$BEHAT_TAGS" --strict "${BEHAT_EXTRA_ARGS[@]}" "$@"

‎src/Context/FeatureContext.php‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,18 @@ class_exists( Selector::class ) ? ( new Selector() )->forLineCoverage( $filter )
320320
$filter
321321
);
322322

323-
foreach ( new DirectoryIterator( self::$behat_run_dir . '/build/logs' ) as $file ) {
323+
// Parallel workers each merge the coverage they collected into a report of their own,
324+
// as they would otherwise merge, and remove, each other's files while those are written.
325+
$coverage_id = self::get_coverage_id();
326+
$logs_dir = self::$behat_run_dir . '/build/logs';
327+
$source_dir = '' !== $coverage_id ? "{$logs_dir}/behat-{$coverage_id}" : $logs_dir;
328+
$report = '' !== $coverage_id ? "{$logs_dir}/behat-coverage-{$coverage_id}.xml" : "{$logs_dir}/behat-coverage.xml";
329+
330+
if ( ! is_dir( $source_dir ) ) {
331+
return;
332+
}
333+
334+
foreach ( new DirectoryIterator( $source_dir ) as $file ) {
324335
if ( ! $file->isFile() || 'cov' !== $file->getExtension() ) {
325336
continue;
326337
}
@@ -329,7 +340,20 @@ class_exists( Selector::class ) ? ( new Selector() )->forLineCoverage( $filter )
329340
unlink( $file->getPathname() );
330341
}
331342

332-
( new Clover() )->process( $coverage, self::$behat_run_dir . '/build/logs/behat-coverage.xml' );
343+
( new Clover() )->process( $coverage, $report );
344+
345+
if ( $source_dir !== $logs_dir ) {
346+
@rmdir( $source_dir );
347+
}
348+
}
349+
350+
/**
351+
* Get the identifier of the parallel worker the code coverage is collected for, if any.
352+
*
353+
* @return string
354+
*/
355+
private static function get_coverage_id() {
356+
return (string) preg_replace( '/[^A-Za-z0-9_-]+/', '-', (string) getenv( 'WP_CLI_TEST_COVERAGE_ID' ) );
333357
}
334358

335359
/**
@@ -506,6 +530,11 @@ private static function get_process_env_variables(): array {
506530
$current = getenv( 'WP_CLI_REQUIRE' );
507531
$updated = $current ? "{$current},{$coverage_require_file}" : $coverage_require_file;
508532
$env['WP_CLI_REQUIRE'] = $updated;
533+
534+
$coverage_id = self::get_coverage_id();
535+
if ( '' !== $coverage_id ) {
536+
$env['WP_CLI_TEST_COVERAGE_ID'] = $coverage_id;
537+
}
509538
}
510539

511540
$env = array_filter(

‎utils/behat-parallel.php‎

Lines changed: 83 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,64 @@ static function ( $a, $b ) {
239239
return $shards;
240240
}
241241

242+
/**
243+
* Get the share of the scenarios to run, as set through WP_CLI_TEST_SHARD to "<index>/<total>".
244+
*
245+
* @return array{int, int}|null One-based index and total number of shards, or null to run all of them.
246+
*/
247+
function wp_cli_tests_shard() {
248+
$value = trim( (string) getenv( 'WP_CLI_TEST_SHARD' ) );
249+
250+
if ( '' === $value ) {
251+
return null;
252+
}
253+
254+
if ( ! preg_match( '#^(\d+)/(\d+)$#', $value, $matches ) || (int) $matches[1] < 1 || (int) $matches[1] > (int) $matches[2] ) {
255+
fwrite( STDERR, "Warning: WP_CLI_TEST_SHARD is not of the form <index>/<total>, like 2/3, running all scenarios.\n" );
256+
return null;
257+
}
258+
259+
return [ (int) $matches[1], (int) $matches[2] ];
260+
}
261+
262+
/**
263+
* Pick one shard of the scenarios, out of a cost-balanced distribution over all shards.
264+
*
265+
* Scenarios that rely on shared resources are spread over the shards as well, as every shard runs
266+
* on a machine of its own. The distribution only depends on the scenarios, so every shard computes
267+
* the same one and together they run every scenario exactly once.
268+
*
269+
* @param array<array{path: string, cost: int, shared: bool}> $scenarios
270+
* @param int $index One-based.
271+
* @param int $total
272+
* @return array<array{path: string, cost: int, shared: bool}>
273+
*/
274+
function wp_cli_tests_pick_shard( array $scenarios, $index, $total ) {
275+
$order = array_keys( $scenarios );
276+
277+
usort(
278+
$order,
279+
static function ( $a, $b ) use ( $scenarios ) {
280+
return ( $scenarios[ $b ]['cost'] - $scenarios[ $a ]['cost'] ) ?: ( $a - $b );
281+
}
282+
);
283+
284+
$load = array_fill( 0, $total, 0 );
285+
$picked = [];
286+
287+
foreach ( $order as $key ) {
288+
$shard = (int) array_search( min( $load ), $load, true );
289+
$load[ $shard ] += $scenarios[ $key ]['cost'];
290+
if ( $shard === $index - 1 ) {
291+
$picked[ $key ] = $scenarios[ $key ];
292+
}
293+
}
294+
295+
ksort( $picked );
296+
297+
return array_values( $picked );
298+
}
299+
242300
/**
243301
* Get the Docker image of the database server the tests run against on the host, so that the
244302
* containers test against the same type and version of database server.
@@ -628,7 +686,9 @@ function wp_cli_tests_docker_worker_command( $name, $php_image, $db_image, array
628686
}
629687
}
630688

631-
if ( ( $workers < 2 && ! $docker ) || DIRECTORY_SEPARATOR === '\\' || ( $selects_scenarios && null === $rerun_paths && ! $docker ) ) {
689+
$shard = $selects_scenarios || null !== $rerun_paths ? null : wp_cli_tests_shard();
690+
691+
if ( ( $workers < 2 && ! $docker && null === $shard ) || DIRECTORY_SEPARATOR === '\\' || ( $selects_scenarios && null === $rerun_paths && ! $docker ) ) {
632692
wp_cli_tests_run_behat_and_exit( $all_args );
633693
}
634694

@@ -737,10 +797,28 @@ static function ( $path ) {
737797
$scenarios = wp_cli_tests_collect_scenarios( $features_folder, $tags );
738798
}
739799

800+
if ( null !== $shard ) {
801+
$all_scenarios = count( $scenarios );
802+
$scenarios = wp_cli_tests_pick_shard( $scenarios, $shard[0], $shard[1] );
803+
printf( "Running shard %d of %d, with %d of %d scenarios.\n", $shard[0], $shard[1], count( $scenarios ), $all_scenarios );
804+
}
805+
740806
$workers = min( max( 1, $workers ), max( 1, count( $scenarios ) ) );
741807

742808
if ( $workers < 2 && ! $docker ) {
743-
wp_cli_tests_run_behat_and_exit( $all_args );
809+
if ( null === $shard ) {
810+
wp_cli_tests_run_behat_and_exit( $all_args );
811+
}
812+
813+
if ( ! is_dir( $base_dir ) ) {
814+
mkdir( $base_dir, 0777, true );
815+
}
816+
$list = "{$base_dir}/shard.scenarios";
817+
file_put_contents( $list, implode( "\n", array_column( $scenarios, 'path' ) ) . "\n" );
818+
if ( count( $scenarios ) > 0 ) {
819+
wp_cli_tests_run_behat_and_exit( array_merge( $all_args, [ $list ] ) );
820+
}
821+
exit( 0 );
744822
}
745823

746824
// Containers do not share ports or temporary directories, so any of them can run any scenario.
@@ -778,6 +856,9 @@ static function () use ( &$containers ) {
778856

779857
$env = getenv();
780858

859+
// Every worker merges the code coverage of its own scenarios into a report of its own.
860+
$env['WP_CLI_TEST_COVERAGE_ID'] = ( null !== $shard ? "shard-{$shard[0]}-" : '' ) . "worker-{$index}";
861+
781862
if ( $index > 0 ) {
782863
$env['TMPDIR'] = "{$base_dir}/worker-{$index}";
783864
$env['WP_CLI_TEST_DBNAME'] = "{$db_name}_{$index}";

‎utils/generate-coverage.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,10 @@ static function () use ( $coverage, $feature, $scenario, $step_line, $name, $pro
9696
$feature_suffix = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $feature ) );
9797
$scenario_suffix = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $scenario ) );
9898
$db_type = strtolower( getenv( 'WP_CLI_TEST_DBTYPE' ) );
99-
$destination = "$project_dir/build/logs/$feature_suffix-$scenario_suffix-$step_line-$db_type.cov";
99+
// Parallel workers each collect into a directory of their own, see FeatureContext::merge_coverage_reports().
100+
$coverage_id = preg_replace( '/[^A-Za-z0-9_-]+/', '-', (string) getenv( 'WP_CLI_TEST_COVERAGE_ID' ) );
101+
$coverage_dir = '' !== $coverage_id ? "$project_dir/build/logs/behat-$coverage_id" : "$project_dir/build/logs";
102+
$destination = "$coverage_dir/$feature_suffix-$scenario_suffix-$step_line-$db_type.cov";
100103

101104
$dir = dirname( $destination );
102105
if ( ! file_exists( $dir ) ) {

0 commit comments

Comments
 (0)