@@ -187,6 +187,179 @@ static function ( $a, $b ) {
187187 return $ shards ;
188188}
189189
190+ /**
191+ * Get the Docker image of the database server the tests run against on the host, so that the
192+ * containers test against the same type and version of database server.
193+ *
194+ * @return string|null Image name, or null if the server could not be identified.
195+ */
196+ function wp_cli_tests_docker_db_image () {
197+ $ image = getenv ( 'WP_CLI_TEST_DOCKER_DB ' );
198+ if ( is_string ( $ image ) && '' !== $ image ) {
199+ return $ image ;
200+ }
201+
202+ $ host = getenv ( 'WP_CLI_TEST_DBHOST ' ) ?: 'localhost ' ;
203+ $ parts = explode ( ': ' , $ host );
204+ $ args = '-h ' . escapeshellarg ( $ parts [0 ] );
205+ if ( isset ( $ parts [1 ] ) ) {
206+ $ args .= is_numeric ( $ parts [1 ] ) ? ' --port= ' . escapeshellarg ( $ parts [1 ] ) . ' --protocol=tcp ' : ' --socket= ' . escapeshellarg ( $ parts [1 ] );
207+ }
208+ $ pass = getenv ( 'WP_CLI_TEST_DBROOTPASS ' );
209+ $ args .= ' -u ' . escapeshellarg ( getenv ( 'WP_CLI_TEST_DBROOTUSER ' ) ?: 'root ' ) . ( false !== $ pass && '' !== $ pass ? ' -p ' . escapeshellarg ( $ pass ) : '' );
210+
211+ foreach ( [ 'mysql ' , 'mariadb ' ] as $ client ) {
212+ $ version = (string ) exec ( "{$ client } {$ args } --skip-column-names -e 'SELECT VERSION()' 2>/dev/null " );
213+ if ( preg_match ( '/^(\d+\.\d+)/ ' , $ version , $ matches ) ) {
214+ return ( false !== stripos ( $ version , 'mariadb ' ) ? 'mariadb: ' : 'mysql: ' ) . $ matches [1 ];
215+ }
216+ }
217+
218+ return null ;
219+ }
220+
221+ /**
222+ * Get the extra options a database server image needs to accept the test user's password.
223+ *
224+ * @param string $image
225+ * @return string
226+ */
227+ function wp_cli_tests_docker_db_options ( $ image ) {
228+ // Throwaway databases do not need to wait for their writes to reach the disk.
229+ $ options = '--innodb-flush-log-at-trx-commit=0 --sync-binlog=0 ' ;
230+
231+ if ( preg_match ( '/^mysql:(\d+)\.(\d+)/ ' , $ image , $ matches ) && (int ) $ matches [1 ] >= 8 ) {
232+ $ options .= version_compare ( "{$ matches [1 ]}. {$ matches [2 ]}" , '8.4 ' , '>= ' )
233+ ? ' --mysql-native-password=ON --authentication-policy=mysql_native_password '
234+ : ' --default-authentication-plugin=mysql_native_password ' ;
235+ }
236+
237+ return $ options ;
238+ }
239+
240+ /**
241+ * Build the image the workers run in.
242+ *
243+ * @return string|null Image name, or null if it could not be built.
244+ */
245+ function wp_cli_tests_docker_php_image () {
246+ $ version = PHP_MAJOR_VERSION . '. ' . PHP_MINOR_VERSION ;
247+ $ image = "wp-cli-tests-php: {$ version }" ;
248+
249+ exec ( 'docker build -q -t ' . escapeshellarg ( $ image ) . ' --build-arg ' . escapeshellarg ( "PHP_VERSION= {$ version }" ) . ' ' . escapeshellarg ( __DIR__ . '/docker ' ) . ' 2>&1 ' , $ output , $ exit_code );
250+
251+ if ( 0 !== $ exit_code ) {
252+ fwrite ( STDERR , "Warning: Could not build the Docker image for PHP {$ version }: \n" . implode ( "\n" , array_slice ( $ output , -5 ) ) . "\n" );
253+ return null ;
254+ }
255+
256+ return $ image ;
257+ }
258+
259+ /**
260+ * Get the directories a container needs to see at their usual paths.
261+ *
262+ * @param string $base_dir
263+ * @return array<int|string, string> Paths to mount at the same path, and read-only sources keyed by source path.
264+ */
265+ function wp_cli_tests_docker_mounts ( $ base_dir ) {
266+ $ cwd = (string ) getcwd ();
267+ $ mounts = [ $ cwd , $ base_dir ];
268+
269+ // Dependencies can be symlinked from outside the project, as in wp-cli/wp-cli-dev,
270+ // in which case the closest directory holding both has to be visible.
271+ foreach ( [ $ cwd . '/vendor/autoload.php ' ] as $ path ) {
272+ $ real = realpath ( $ path );
273+ if ( false === $ real || 0 === strpos ( $ real . '/ ' , $ cwd . '/ ' ) ) {
274+ continue ;
275+ }
276+ $ common = $ cwd ;
277+ while ( 0 !== strpos ( $ real . '/ ' , rtrim ( $ common , '/ ' ) . '/ ' ) && dirname ( $ common ) !== $ common ) {
278+ $ common = dirname ( $ common );
279+ }
280+ $ mounts [] = '/ ' === $ common ? dirname ( $ real ) : $ common ;
281+ }
282+
283+ $ mounts = array_values ( array_unique ( $ mounts ) );
284+
285+ // Download WordPress once for all containers, which only ever copy from it.
286+ $ version = getenv ( 'WP_VERSION ' );
287+ if ( $ version && ! getenv ( 'WP_CLI_TEST_CORE_ZIP ' ) ) {
288+ $ cache = sys_get_temp_dir () . '/wp-cli-test-core-download-cache- ' . $ version ;
289+ if ( ! is_readable ( $ cache . '/wp-includes/version.php ' ) ) {
290+ exec ( 'vendor/bin/wp core download --force --path= ' . escapeshellarg ( $ cache ) . ' --version= ' . escapeshellarg ( $ version ) . ' > /dev/null 2>&1 ' );
291+ }
292+ if ( is_readable ( $ cache . '/wp-includes/version.php ' ) ) {
293+ $ mounts [ $ cache ] = '/tmp/wp-cli-test-core-download-cache- ' . $ version ;
294+ }
295+ }
296+
297+ return $ mounts ;
298+ }
299+
300+ /**
301+ * Start the containers of a worker and get the command that runs its scenarios.
302+ *
303+ * @param string $name Name prefix of the worker's containers.
304+ * @param string $php_image
305+ * @param string|null $db_image Null when running on SQLite.
306+ * @param array<int|string, string> $mounts
307+ * @param array<string> $user_args
308+ * @param string $scenario_list File listing the worker's scenarios.
309+ * @return string
310+ */
311+ function wp_cli_tests_docker_worker_command ( $ name , $ php_image , $ db_image , array $ mounts , array $ user_args , $ scenario_list ) {
312+ $ network = '' ;
313+
314+ if ( null !== $ db_image ) {
315+ exec (
316+ 'docker run -d --rm --name ' . escapeshellarg ( "{$ name }-db " )
317+ . ' --tmpfs /var/lib/mysql '
318+ . ' -e MYSQL_ROOT_PASSWORD=root -e MYSQL_USER=wp_cli_test -e MYSQL_PASSWORD=password1 '
319+ . ' ' . escapeshellarg ( $ db_image ) . ' ' . wp_cli_tests_docker_db_options ( $ db_image ) . ' 2>&1 '
320+ );
321+ // Share the database container's network, so the server is at 127.0.0.1 and nothing else is.
322+ $ network = ' --network ' . escapeshellarg ( "container: {$ name }-db " );
323+ }
324+
325+ $ env = [
326+ 'HOME ' => '/tmp/home ' ,
327+ 'WP_CLI_TEST_DBHOST ' => '127.0.0.1:3306 ' ,
328+ 'WP_CLI_TEST_DBROOTUSER ' => 'root ' ,
329+ 'WP_CLI_TEST_DBROOTPASS ' => 'root ' ,
330+ ];
331+
332+ foreach ( getenv () as $ key => $ value ) {
333+ if ( preg_match ( '/^(WP_VERSION|NO_COLOR|CI|GITHUB_TOKEN|WP_CLI_TEST_(DBTYPE|OBJECT_CACHE|CORE_ZIP|QUIET|LOG_RUN_TIMES|PHP_TUNING|WP_VERSION_CACHE_TTL))$/ ' , $ key ) ) {
334+ $ env [ $ key ] = $ value ;
335+ }
336+ }
337+
338+ $ command = 'docker run --rm --name ' . escapeshellarg ( $ name ) . $ network
339+ . ' --tmpfs /tmp:exec,mode=1777 '
340+ . ' -u ' . escapeshellarg ( getmyuid () . ': ' . getmygid () )
341+ . ' -w ' . escapeshellarg ( (string ) getcwd () );
342+
343+ foreach ( $ mounts as $ source => $ target ) {
344+ if ( is_int ( $ source ) ) {
345+ $ command .= ' -v ' . escapeshellarg ( "{$ target }: {$ target }" );
346+ } else {
347+ $ command .= ' -v ' . escapeshellarg ( "{$ source }: {$ target }:ro " );
348+ }
349+ }
350+
351+ foreach ( $ env as $ key => $ value ) {
352+ $ command .= ' -e ' . escapeshellarg ( "{$ key }= {$ value }" );
353+ }
354+
355+ $ inner = 'mkdir -p "$HOME" '
356+ // Wait for the database server, which takes a few seconds to start, before preparing it.
357+ . ( null !== $ db_image ? ' && for i in $(seq 1 60); do mysql -h127.0.0.1 -P3306 --protocol=tcp -uroot -proot -e "SELECT 1" > /dev/null 2>&1 && break; sleep 1; done && vendor/bin/install-package-tests > /dev/null ' : '' )
358+ . ' && vendor/bin/run-behat-tests ' . implode ( ' ' , array_map ( 'escapeshellarg ' , array_merge ( $ user_args , [ $ scenario_list ] ) ) );
359+
360+ return $ command . ' ' . escapeshellarg ( $ php_image ) . ' sh -c ' . escapeshellarg ( $ inner );
361+ }
362+
190363$ args = array_slice ( $ argv , 1 );
191364
192365$ workers = (int ) array_shift ( $ args );
@@ -196,9 +369,18 @@ static function ( $a, $b ) {
196369$ user_args = false === $ separator ? [] : array_slice ( $ args , $ separator + 1 );
197370$ all_args = array_merge ( $ behat_args , $ user_args );
198371
372+ // Run every worker in its own throwaway containers, see run-behat-tests.
373+ $ docker = (bool ) getenv ( 'WP_CLI_TEST_DOCKER ' ) && DIRECTORY_SEPARATOR !== '\\' ;
374+ $ rerun_paths = null ;
375+
199376// A rerun after a parallel run covers exactly the scenarios that failed in it.
200377$ rerun = array_search ( '--rerun ' , $ user_args , true );
201- if ( false !== $ rerun && file_exists ( wp_cli_tests_failures_file () ) ) {
378+ if ( false !== $ rerun && file_exists ( wp_cli_tests_failures_file () ) && $ docker ) {
379+ unset( $ user_args [ $ rerun ] );
380+ $ user_args = array_values ( $ user_args );
381+ $ rerun_paths = array_filter ( explode ( "\n" , (string ) file_get_contents ( wp_cli_tests_failures_file () ) ) );
382+ unlink ( wp_cli_tests_failures_file () );
383+ } elseif ( false !== $ rerun && file_exists ( wp_cli_tests_failures_file () ) ) {
202384 unset( $ user_args [ $ rerun ] );
203385 $ failures = wp_cli_tests_failures_file ();
204386 $ copy = $ failures . '. ' . getmypid () . '.scenarios ' ;
@@ -217,10 +399,25 @@ static function ( $a, $b ) {
217399 }
218400}
219401
220- if ( $ workers < 2 || DIRECTORY_SEPARATOR === '\\' || $ selects_scenarios ) {
402+ if ( ( $ workers < 2 && ! $ docker ) || DIRECTORY_SEPARATOR === '\\' || ( $ selects_scenarios && null === $ rerun_paths ) ) {
221403 wp_cli_tests_run_behat_and_exit ( $ all_args );
222404}
223405
406+ $ php_image = null ;
407+ $ db_image = null ;
408+ if ( $ docker ) {
409+ $ php_image = wp_cli_tests_docker_php_image ();
410+ $ db_image = 'sqlite ' === getenv ( 'WP_CLI_TEST_DBTYPE ' ) ? null : wp_cli_tests_docker_db_image ();
411+
412+ if ( null === $ php_image || ( null === $ db_image && 'sqlite ' !== getenv ( 'WP_CLI_TEST_DBTYPE ' ) ) ) {
413+ fwrite ( STDERR , "Warning: Running the scenarios without Docker. \n" );
414+ $ docker = false ;
415+ if ( $ workers < 2 || null !== $ rerun_paths ) {
416+ wp_cli_tests_run_behat_and_exit ( $ all_args );
417+ }
418+ }
419+ }
420+
224421require getcwd () . '/vendor/autoload.php ' ;
225422
226423$ tags = '' ;
@@ -230,14 +427,43 @@ static function ( $a, $b ) {
230427 }
231428}
232429
430+ // Containers check for PHP extensions themselves, as theirs can differ from the host's.
431+ if ( $ docker ) {
432+ $ tags = (string ) preg_replace ( '/(^|&&)~@require-extension-[A-Za-z0-9_]+/ ' , '' , $ tags );
433+ $ tags = trim ( $ tags , '& ' );
434+ }
435+
233436$ features_folder = getenv ( 'BEHAT_FEATURES_FOLDER ' ) ?: 'features ' ;
234- $ scenarios = wp_cli_tests_collect_scenarios ( $ features_folder , $ tags );
235- $ workers = min ( $ workers , max ( 1 , count ( $ scenarios ) ) );
236437
237- if ( $ workers < 2 ) {
438+ if ( null !== $ rerun_paths ) {
439+ $ scenarios = array_map (
440+ static function ( $ path ) {
441+ return [
442+ 'path ' => $ path ,
443+ 'cost ' => 1 ,
444+ 'shared ' => false ,
445+ ];
446+ },
447+ $ rerun_paths
448+ );
449+ $ workers = 1 ;
450+ } else {
451+ $ scenarios = wp_cli_tests_collect_scenarios ( $ features_folder , $ tags );
452+ }
453+
454+ $ workers = min ( max ( 1 , $ workers ), max ( 1 , count ( $ scenarios ) ) );
455+
456+ if ( $ workers < 2 && ! $ docker ) {
238457 wp_cli_tests_run_behat_and_exit ( $ all_args );
239458}
240459
460+ // Containers do not share ports or temporary directories, so any of them can run any scenario.
461+ if ( $ docker ) {
462+ foreach ( $ scenarios as $ key => $ scenario ) {
463+ $ scenarios [ $ key ]['shared ' ] = false ;
464+ }
465+ }
466+
241467$ shards = wp_cli_tests_distribute ( $ scenarios , $ workers );
242468// Kept between runs, so that the workers' caches stay warm and failed scenarios can be inspected.
243469$ base_dir = sys_get_temp_dir () . '/wp-cli-test-parallel- ' . substr ( md5 ( (string ) getcwd () ), 0 , 8 );
@@ -247,7 +473,19 @@ static function ( $a, $b ) {
247473 mkdir ( $ base_dir , 0777 , true );
248474}
249475
250- printf ( "Running %d scenarios in %d parallel workers. \n" , count ( $ scenarios ), $ workers );
476+ printf ( "Running %d scenarios in %d parallel workers%s. \n" , count ( $ scenarios ), $ workers , $ docker ? ' in Docker containers ' : '' );
477+
478+ $ containers = [];
479+ if ( $ docker ) {
480+ $ mounts = wp_cli_tests_docker_mounts ( $ base_dir );
481+ register_shutdown_function (
482+ static function () use ( &$ containers ) {
483+ foreach ( $ containers as $ container ) {
484+ exec ( 'docker rm -f ' . escapeshellarg ( $ container ) . ' > /dev/null 2>&1 ' );
485+ }
486+ }
487+ );
488+ }
251489
252490$ procs = [];
253491foreach ( $ shards as $ index => $ paths ) {
@@ -267,6 +505,14 @@ static function ( $a, $b ) {
267505 $ output = "{$ base_dir }/worker- {$ index }.log " ;
268506 $ command = escapeshellarg ( PHP_BINARY ) . ' vendor/bin/behat ' . implode ( ' ' , array_map ( 'escapeshellarg ' , array_merge ( $ all_args , [ $ list ] ) ) );
269507
508+ if ( $ docker ) {
509+ $ name = 'wp-cli-tests- ' . substr ( md5 ( $ base_dir ), 0 , 8 ) . "- {$ index }" ;
510+ $ containers [] = $ name ;
511+ $ containers [] = "{$ name }-db " ;
512+ $ env = getenv ();
513+ $ command = wp_cli_tests_docker_worker_command ( $ name , (string ) $ php_image , $ db_image , $ mounts , array_values ( $ user_args ), $ list );
514+ }
515+
270516 $ procs [ $ index ] = [
271517 'proc ' => proc_open (
272518 $ command ,
0 commit comments