Skip to content

Commit e0760cf

Browse files
schlesseraclaude
andcommitted
Test splitting the scenarios across shards, and document it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 37466e9 commit e0760cf

2 files changed

Lines changed: 272 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,17 @@ Set `WP_CLI_TEST_PARALLEL` to a number of workers to spread the scenarios over t
272272
WP_CLI_TEST_PARALLEL=4 composer behat
273273
```
274274
275-
Every worker but the first gets its own temporary directory, and with it its own home directory, caches and run directories, as well as its own test database, named after the test database with a numeric suffix (`wp_cli_test_1`, `wp_cli_test_2`, ...). Run `composer prepare-tests` once to allow the test user to create these databases. Without that permission, the scenarios are run one after the other, as they are on Windows, when collecting code coverage, or when selecting scenarios by path or name.
275+
Every worker but the first gets its own temporary directory, and with it its own home directory, caches and run directories, as well as its own test database, named after the test database with a numeric suffix (`wp_cli_test_1`, `wp_cli_test_2`, ...). Run `composer prepare-tests` once to allow the test user to create these databases. Without that permission, the scenarios are run one after the other, as they are on Windows or when selecting scenarios by path or name. When collecting code coverage, every worker writes a report of its own to `build/logs`.
276276
277277
Scenarios that rely on resources shared across the system, such as a fixed port or a fixed path in the system's temporary directory, are all run by the first worker, one after the other. `composer behat-rerun` re-runs exactly the scenarios that failed in the last parallel run.
278278

279+
Set `WP_CLI_TEST_SHARD` to `<index>/<total>` to run only that share of the scenarios, to split them across several machines:
280+
```bash
281+
WP_CLI_TEST_SHARD=2/4 WP_CLI_TEST_PARALLEL=4 composer behat
282+
```
283+
284+
Every machine spreads the scenarios over the shards by their expected cost in the same way, so that together they run every scenario once and finish at about the same time. Selecting scenarios by path or name runs them regardless of the shard.
285+
279286
Set `WP_CLI_TEST_DOCKER` to run the scenarios in throwaway Docker containers instead, every worker in its own:
280287
```bash
281288
WP_CLI_TEST_DOCKER=auto WP_CLI_TEST_PARALLEL=4 composer behat

‎tests/tests/TestBehatParallel.php‎

Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
<?php
2+
3+
namespace WP_CLI\Tests\Tests;
4+
5+
use WP_CLI\Tests\TestCase;
6+
use WP_CLI\Utils;
7+
8+
/**
9+
* Splitting the scenarios across machines through WP_CLI_TEST_SHARD.
10+
*
11+
* The runner is exercised the way run-behat-tests uses it, over feature files in a temporary
12+
* project. With a single worker, it writes the scenarios of the shard to a list that it hands
13+
* to Behat, which is what these tests look at. Behat itself runs with --dry-run.
14+
*/
15+
class TestBehatParallel extends TestCase {
16+
17+
/**
18+
* @var string|null
19+
*/
20+
private $temp_dir;
21+
22+
protected function set_up(): void {
23+
parent::set_up();
24+
25+
if ( DIRECTORY_SEPARATOR === '\\' ) {
26+
$this->markTestSkipped( 'The runner does not split the scenarios on Windows.' );
27+
}
28+
29+
$this->temp_dir = Utils\get_temp_dir() . uniqid( 'wp-cli-test-behat-parallel-', true );
30+
mkdir( $this->temp_dir . '/features', 0777, true );
31+
file_put_contents( $this->temp_dir . '/behat.yml', "default:\n suites:\n default:\n contexts: []\n" );
32+
33+
// The runner loads the Gherkin parser and Behat from the project it runs in.
34+
$vendor = dirname( dirname( __DIR__ ) ) . '/vendor';
35+
if ( ! @symlink( $vendor, $this->temp_dir . '/vendor' ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Skipped below.
36+
$this->markTestSkipped( 'The vendor directory cannot be linked into the temporary project.' );
37+
}
38+
}
39+
40+
protected function tear_down(): void {
41+
if ( null === $this->temp_dir ) {
42+
parent::tear_down();
43+
return;
44+
}
45+
46+
if ( is_link( $this->temp_dir . '/vendor' ) ) {
47+
unlink( $this->temp_dir . '/vendor' );
48+
}
49+
$this->remove_dir( $this->get_base_dir() );
50+
$this->remove_dir( $this->temp_dir );
51+
52+
parent::tear_down();
53+
}
54+
55+
public function test_shards_run_every_scenario_once(): void {
56+
$expected = $this->write_features();
57+
58+
$picked = [];
59+
for ( $index = 1; $index <= 3; $index++ ) {
60+
$result = $this->run_shard( "{$index}/3" );
61+
$this->assertSame( 0, $result['exit_code'], $result['output'] );
62+
63+
$shard = $this->get_shard_scenarios();
64+
$this->assertNotEmpty( $shard, "Shard {$index} of 3 got no scenarios." );
65+
$this->assertStringContainsString( sprintf( 'Running shard %d of 3, with %d of %d scenarios.', $index, count( $shard ), count( $expected ) ), $result['output'] );
66+
67+
$picked = array_merge( $picked, $shard );
68+
}
69+
70+
sort( $picked );
71+
$this->assertSame( $expected, $picked );
72+
}
73+
74+
public function test_shards_are_balanced_by_cost(): void {
75+
$this->write_feature(
76+
'install.feature',
77+
[
78+
'Install one' => [ 'Given a WP install' ],
79+
'Install two' => [ 'Given a WP install' ],
80+
]
81+
);
82+
$this->write_feature(
83+
'cheap.feature',
84+
[
85+
'Cheap one' => [ 'Given an empty directory' ],
86+
'Cheap two' => [ 'Given an empty directory' ],
87+
'Cheap three' => [ 'Given an empty directory' ],
88+
'Cheap four' => [ 'Given an empty directory' ],
89+
]
90+
);
91+
92+
// The two installations are the most expensive by far, so each shard gets one of them.
93+
foreach ( [ '1/2', '2/2' ] as $shard ) {
94+
$this->run_shard( $shard );
95+
$installs = array_filter(
96+
$this->get_shard_scenarios(),
97+
static function ( $path ) {
98+
return false !== strpos( $path, 'install.feature' );
99+
}
100+
);
101+
$this->assertCount( 1, $installs, "Shard {$shard}" );
102+
}
103+
}
104+
105+
public function test_shard_without_scenarios_succeeds(): void {
106+
$this->write_feature( 'only.feature', [ 'The only one' => [ 'Given an empty directory' ] ] );
107+
108+
$result = $this->run_shard( '2/2' );
109+
110+
$this->assertSame( 0, $result['exit_code'], $result['output'] );
111+
$this->assertStringContainsString( 'Running shard 2 of 2, with 0 of 1 scenarios.', $result['output'] );
112+
$this->assertSame( [], $this->get_shard_scenarios() );
113+
}
114+
115+
public function test_invalid_shard_runs_all_scenarios(): void {
116+
$this->write_features();
117+
118+
$result = $this->run_shard( '3/2' );
119+
120+
$this->assertStringContainsString( 'WP_CLI_TEST_SHARD is not of the form <index>/<total>', $result['output'] );
121+
$this->assertStringNotContainsString( 'Running shard', $result['output'] );
122+
}
123+
124+
public function test_selected_scenarios_ignore_the_shard(): void {
125+
$this->write_features();
126+
127+
$result = $this->run_shard( '1/3', [ 'features/a.feature' ] );
128+
129+
$this->assertStringNotContainsString( 'Running shard', $result['output'] );
130+
}
131+
132+
/**
133+
* Write feature files with a mix of scenarios, including an outline and one using shared resources.
134+
*
135+
* @return string[] Paths of all scenarios, sorted.
136+
*/
137+
private function write_features(): array {
138+
$this->write_feature(
139+
'a.feature',
140+
[
141+
'First' => [ 'Given a WP install', 'When I run `wp option get home`' ],
142+
'Second' => [ 'Given an empty directory' ],
143+
'Server' => [ 'Given a WP install', 'And a PHP built-in web server' ],
144+
]
145+
);
146+
$this->write_feature(
147+
'b.feature',
148+
[
149+
'Third' => [ 'Given an empty directory', 'When I run `wp cli version`' ],
150+
'Fourth' => [ 'Given a WP install with Composer' ],
151+
],
152+
" Scenario Outline: Fifth\n Given an empty directory\n When I run `wp <command>`\n\n Examples:\n | command |\n | cli info |\n | cli version |\n"
153+
);
154+
$this->write_feature(
155+
'c.feature',
156+
[
157+
'Sixth' => [ 'Given an empty directory' ],
158+
'Seventh' => [ 'Given a WP install', 'When I run `wp plugin list`' ],
159+
]
160+
);
161+
162+
$paths = [];
163+
foreach ( glob( $this->temp_dir . '/features/*.feature' ) as $file ) {
164+
$lines = file( $file );
165+
foreach ( $lines as $number => $line ) {
166+
if ( preg_match( '/^\s*Scenario( Outline)?:/', $line ) ) {
167+
$paths[] = 'features/' . basename( $file ) . ':' . ( $number + 1 );
168+
}
169+
}
170+
}
171+
sort( $paths );
172+
173+
return $paths;
174+
}
175+
176+
/**
177+
* @param string $name File name.
178+
* @param array<string, string[]> $scenarios Steps by scenario title.
179+
* @param string $extra Additional Gherkin to append.
180+
*/
181+
private function write_feature( $name, array $scenarios, $extra = '' ): void {
182+
$contents = "Feature: {$name}\n";
183+
foreach ( $scenarios as $title => $steps ) {
184+
$contents .= "\n Scenario: {$title}\n " . implode( "\n ", $steps ) . "\n";
185+
}
186+
if ( '' !== $extra ) {
187+
$contents .= "\n" . $extra;
188+
}
189+
190+
file_put_contents( $this->temp_dir . '/features/' . $name, $contents );
191+
}
192+
193+
/**
194+
* Run the runner with a single worker, as run-behat-tests does for a shard.
195+
*
196+
* @param string $shard Value of WP_CLI_TEST_SHARD.
197+
* @param string[] $user_args Arguments passed to run-behat-tests.
198+
* @return array{output: string, exit_code: int}
199+
*/
200+
private function run_shard( $shard, array $user_args = [] ): array {
201+
$script = dirname( dirname( __DIR__ ) ) . '/utils/behat-parallel.php';
202+
$command = array_merge( [ PHP_BINARY, $script, '1', '--dry-run', '--format=progress', '--' ], $user_args );
203+
204+
$env = array_merge(
205+
getenv(),
206+
[
207+
'WP_CLI_TEST_SHARD' => $shard,
208+
'WP_CLI_TEST_DOCKER' => '0',
209+
'BEHAT_FEATURES_FOLDER' => 'features',
210+
]
211+
);
212+
unset( $env['WP_CLI_TEST_COVERAGE'] );
213+
214+
$process = proc_open(
215+
implode( ' ', array_map( 'escapeshellarg', $command ) ) . ' 2>&1',
216+
[ 1 => [ 'pipe', 'w' ] ],
217+
$pipes,
218+
$this->temp_dir,
219+
$env
220+
);
221+
$this->assertIsResource( $process );
222+
223+
$output = (string) stream_get_contents( $pipes[1] );
224+
fclose( $pipes[1] );
225+
226+
return [
227+
'output' => $output,
228+
'exit_code' => proc_close( $process ),
229+
];
230+
}
231+
232+
/**
233+
* Get the scenarios the last run handed to Behat for its shard.
234+
*
235+
* @return string[]
236+
*/
237+
private function get_shard_scenarios(): array {
238+
$list = $this->get_base_dir() . '/shard.scenarios';
239+
$this->assertFileExists( $list );
240+
241+
return array_values( array_filter( explode( "\n", (string) file_get_contents( $list ) ) ) );
242+
}
243+
244+
/**
245+
* Directory the runner keeps its state in, which depends on the project directory.
246+
*/
247+
private function get_base_dir(): string {
248+
return sys_get_temp_dir() . '/wp-cli-test-parallel-' . substr( md5( (string) realpath( $this->temp_dir ) ), 0, 8 );
249+
}
250+
251+
private function remove_dir( string $dir ): void {
252+
if ( ! is_dir( $dir ) ) {
253+
return;
254+
}
255+
$items = new \RecursiveIteratorIterator(
256+
new \RecursiveDirectoryIterator( $dir, \FilesystemIterator::SKIP_DOTS ),
257+
\RecursiveIteratorIterator::CHILD_FIRST
258+
);
259+
foreach ( $items as $item ) {
260+
$item->isDir() && ! $item->isLink() ? rmdir( (string) $item ) : unlink( (string) $item );
261+
}
262+
rmdir( $dir );
263+
}
264+
}

0 commit comments

Comments
 (0)