88use Behat \Testwork \Hook \Scope \AfterSuiteScope ;
99use Behat \Testwork \Hook \Scope \BeforeSuiteScope ;
1010use RuntimeException ;
11+ use WP_CLI ;
1112use WP_CLI \Process ;
1213use WP_CLI \Utils ;
1314
@@ -639,6 +640,7 @@ public function __construct() {
639640
640641 $ this ->variables ['CORE_CONFIG_SETTINGS ' ] = Utils \assoc_args_to_str ( self ::$ db_settings );
641642
643+ $ this ->test_connection ();
642644 $ this ->drop_db ();
643645 $ this ->set_cache_dir ();
644646 }
@@ -842,6 +844,8 @@ private function set_cache_dir() {
842844 * @param string $sql_cmd Command to run.
843845 * @param array $assoc_args Optional. Associative array of options. Default empty.
844846 * @param bool $add_database Optional. Whether to add dbname to the $sql_cmd. Default false.
847+ *
848+ * return array.
845849 */
846850 private static function run_sql ( $ sql_cmd , $ assoc_args = [], $ add_database = false ) {
847851 $ default_assoc_args = [
@@ -852,11 +856,22 @@ private static function run_sql( $sql_cmd, $assoc_args = [], $add_database = fal
852856 if ( $ add_database ) {
853857 $ sql_cmd .= ' ' . escapeshellarg ( self ::$ db_settings ['dbname ' ] );
854858 }
859+ $ send_to_shell = true ;
860+ if ( isset ( $ assoc_args ['send_to_shell ' ] ) ) {
861+ $ send_to_shell = (bool ) $ assoc_args ['send_to_shell ' ];
862+ unset( $ assoc_args ['send_to_shell ' ] );
863+ }
864+
855865 $ start_time = microtime ( true );
856- Utils \run_mysql_command ( $ sql_cmd , array_merge ( $ assoc_args , $ default_assoc_args ) );
866+ $ result = Utils \run_mysql_command ( $ sql_cmd , array_merge ( $ assoc_args , $ default_assoc_args ), null , $ send_to_shell );
857867 if ( self ::$ log_run_times ) {
858868 self ::log_proc_method_run_time ( 'run_sql ' . $ sql_cmd , $ start_time );
859869 }
870+ return [
871+ 'stdout ' => $ result [0 ],
872+ 'stderr ' => $ result [1 ],
873+ 'exit_code ' => $ result [2 ],
874+ ];
860875 }
861876
862877 public function create_db () {
@@ -868,6 +883,26 @@ public function create_db() {
868883 self ::run_sql ( 'mysql --no-defaults ' , [ 'execute ' => "CREATE DATABASE IF NOT EXISTS $ dbname " ] );
869884 }
870885
886+ /**
887+ * Test if the database connection is working.
888+ */
889+ public function test_connection () {
890+ $ sql_result = self ::run_sql (
891+ 'mysql --no-defaults ' ,
892+ [
893+ 'execute ' => 'SELECT 1 ' ,
894+ 'send_to_shell ' => false ,
895+ ]
896+ );
897+ if ( ! empty ( $ sql_result ['stderr ' ] ) ) {
898+ # WP_CLI output functions are suppressed in behat context.
899+ echo 'There was an error connecting to the database: ' . \PHP_EOL ;
900+ echo ' ' . trim ( $ sql_result ['stderr ' ] ) . \PHP_EOL ;
901+ echo 'run `composer prepare-tests` to connect to the database. ' . \PHP_EOL ;
902+ die ( 1 );
903+ }
904+ }
905+
871906 public function drop_db () {
872907 if ( 'sqlite ' === self ::$ db_type ) {
873908 return ;
0 commit comments