-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathFeatureContext.php
More file actions
2037 lines (1719 loc) · 62 KB
/
FeatureContext.php
File metadata and controls
2037 lines (1719 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace WP_CLI\Tests\Context;
use Behat\Behat\Context\Context;
use Behat\Behat\EventDispatcher\Event\OutlineTested;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\FeatureScope;
use Behat\Behat\Hook\Scope\ScenarioScope;
use Behat\Testwork\Hook\Scope\AfterSuiteScope;
use Behat\Testwork\Hook\Scope\BeforeSuiteScope;
use Behat\Behat\Hook\Scope\AfterFeatureScope;
use Behat\Behat\Hook\Scope\BeforeFeatureScope;
use Behat\Behat\Hook\Scope\BeforeStepScope;
use SebastianBergmann\CodeCoverage\Report\Clover;
use SebastianBergmann\CodeCoverage\Driver\Selector;
use SebastianBergmann\CodeCoverage\Driver\Xdebug;
use SebastianBergmann\CodeCoverage\Filter;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\Environment\Runtime;
use RuntimeException;
use DirectoryIterator;
use WP_CLI\Process;
use WP_CLI\ProcessRun;
use WP_CLI\Utils;
use WP_CLI\Path;
use WP_CLI\WpOrgApi;
/**
* Features context.
*/
class FeatureContext implements Context {
use GivenStepDefinitions;
use ThenStepDefinitions;
use WhenStepDefinitions;
/**
* The result of the last command run with `When I run` or `When I try`. Lives until the end of the scenario.
*
* @var ?ProcessRun
*/
protected $result;
/**
* The number of emails sent by the last command run with `When I run` or `When I try`. Lives until the end of the scenario.
*
* @var int
*/
protected $email_sends;
/**
* The current working directory for scenarios that have a "Given a WP installation" or "Given an empty directory" step. Variable RUN_DIR. Lives until the end of the scenario.
*
* @var ?string
*/
private static $run_dir;
/**
* The Directory that 'composer behat' is run from, assumed to always be the top level project folder
*
* @var string
*/
private static $behat_run_dir;
/**
* Where WordPress core is downloaded to for caching, and which is copied to RUN_DIR during a "Given a WP installation" step. Lives until manually deleted.
*
* @var string
*/
private static $cache_dir;
/**
* The directory that holds the install cache, and which is copied to RUN_DIR during a "Given a WP installation" step. Recreated on each suite run.
*
* @var string
*/
private static $install_cache_dir;
/**
* The directory that holds a copy of the sqlite-database-integration plugin, and which is copied to RUN_DIR during a "Given a WP installation" step. Lives until manually deleted.
*
* @var ?string
*/
private static $sqlite_cache_dir;
/**
* The directory that the WP-CLI cache (WP_CLI_CACHE_DIR, normally "$HOME/.wp-cli/cache") is set to on a "Given an empty cache" step.
* Variable SUITE_CACHE_DIR. Lives until the end of the scenario (or until another "Given an empty cache" step within the scenario).
*
* @var ?string
*/
private static $suite_cache_dir;
/**
* Where the current WP-CLI source repository is copied to for Composer-based tests with a "Given a dependency on current wp-cli" step.
* Variable COMPOSER_LOCAL_REPOSITORY. Lives until the end of the suite.
*
* @var ?string
*/
private static $composer_local_repository;
/**
* The test database settings. All but `dbname` can be set via environment variables. The database is dropped at the start of each scenario and created on a "Given a WP installation" step.
*
* @var array<string, string>
*/
private static $db_settings = [
'dbname' => 'wp_cli_test',
'dbuser' => 'wp_cli_test',
'dbpass' => 'password1',
'dbhost' => '127.0.0.1',
];
/**
* What type of database should WordPress use for the test installations. Default to MySQL
*
* @var string
*/
private static $db_type = 'mysql';
/**
* Name of mysql binary to use (mysql or mariadb). Default to mysql
*
* @var string
*/
private static $mysql_binary = 'mysql';
/**
* Array of background process ids started by the current scenario. Used to terminate them at the end of the scenario.
*
* @var array<resource>
*/
private $running_procs = [];
/**
* Array of temporary file paths created for background processes on Windows. Used to clean them up at the end of the scenario.
*
* @var array<string>
*/
private $temp_files = [];
/**
* Array of variables available as {VARIABLE_NAME}. Some are always set: CORE_CONFIG_SETTINGS, DB_USER, DB_PASSWORD, DB_HOST, SRC_DIR, CACHE_DIR, WP_VERSION-version-latest.
* Some are step-dependent: RUN_DIR, SUITE_CACHE_DIR, COMPOSER_LOCAL_REPOSITORY, PHAR_PATH. One is set on use: INVOKE_WP_CLI_WITH_PHP_ARGS-args.
* Scenarios can define their own variables using "Given save" steps. Variables are reset for each scenario.
*
* @var array<string, string>
*/
public $variables = [];
/**
* The current feature file and scenario line number as '<file>.<line>'. Used in RUN_DIR and SUITE_CACHE_DIR directory names. Set at the start of each scenario.
*
* @var ?string
*/
private static $temp_dir_infix;
/**
* Whether to log run times - WP_CLI_TEST_LOG_RUN_TIMES env var. Set on `@BeforeScenario'.
*
* @var false|string
*/
private static $log_run_times;
/**
* When the suite started, set on `@BeforeScenario'.
*
* @var float
*/
private static $suite_start_time;
/**
* Where to output log - stdout|error_log. Set on `@BeforeSuite`.
*
* @var string
*/
private static $output_to;
/**
* Number of processes/methods to output by longest run times. Set on `@BeforeSuite`.
*
* @var int
*/
private static $num_top_processes;
/**
* Number of scenarios to output by longest run times. Set on `@BeforeSuite`.
*
* @var int
*/
private static $num_top_scenarios;
/**
* Scenario run times (top `self::$num_top_scenarios` only).
*
* @var array<string, float>
*/
private static $scenario_run_times = [];
/**
* Scenario count, incremented on `@AfterScenario`.
*
* @var int
*/
private static $scenario_count = 0;
/**
* Array of run time info for proc methods, keyed by method name and arg, each a 2-element array containing run time and run count.
*
* @var array<string, array{int, int}>
*/
private static $proc_method_run_times = [];
/**
* @var array<string, string>
*/
private $mocked_requests = [];
/**
* The current feature.
*
* @var \Behat\Gherkin\Node\FeatureNode|null
*/
private static $feature;
/**
* The current scenario.
*
* @var \Behat\Gherkin\Node\ScenarioInterface|null
*/
private $scenario;
/**
* Line of the current step.
*
* @var int
*/
private $step_line = 0;
/**
* @BeforeFeature
*/
public static function store_feature( BeforeFeatureScope $scope ): void {
self::$feature = $scope->getFeature();
}
/**
* @BeforeScenario
*/
public function store_scenario( BeforeScenarioScope $scope ): void {
$this->scenario = $scope->getScenario();
}
/**
* @BeforeStep
*/
public function store_step( BeforeStepScope $scope ): void {
$this->step_line = $scope->getStep()->getLine();
}
/**
* @AfterScenario
*/
public function forget_scenario( AfterScenarioScope $scope ): void {
$this->step_line = 0;
$this->scenario = null;
}
/**
* @AfterFeature
*/
public static function forget_feature( AfterFeatureScope $scope ): void {
self::$feature = null;
}
/**
* Whether tests are currently running with code coverage collection.
*
* @return bool
*/
private static function running_with_code_coverage() {
$with_code_coverage = (string) getenv( 'WP_CLI_TEST_COVERAGE' );
return \in_array( $with_code_coverage, [ 'true', '1' ], true );
}
public static function merge_coverage_reports(): void {
if ( ! self::running_with_code_coverage() ) {
return;
}
$filter = new Filter();
$coverage = new CodeCoverage(
// Selector class was only added in v9.1 of the php-code-coverage library.
class_exists( Selector::class ) ? ( new Selector() )->forLineCoverage( $filter ) : ( new Xdebug() ),
$filter
);
foreach ( new DirectoryIterator( self::$behat_run_dir . '/build/logs' ) as $file ) {
if ( ! $file->isFile() || 'cov' !== $file->getExtension() ) {
continue;
}
$coverage->merge( include $file->getPathname() );
unlink( $file->getPathname() );
}
( new Clover() )->process( $coverage, self::$behat_run_dir . '/build/logs/behat-coverage.xml' );
}
/**
* Get the path to the Composer vendor folder.
*
* @return string Absolute path to the Composer vendor folder.
*/
public static function get_vendor_dir(): ?string {
static $vendor_folder = null;
if ( null !== $vendor_folder ) {
return $vendor_folder;
}
// We try to detect the vendor folder in the most probable locations.
$vendor_locations = [
// wp-cli/wp-cli-tests is a dependency of the current working dir.
getcwd() . DIRECTORY_SEPARATOR . 'vendor',
// wp-cli/wp-cli-tests is the root project.
dirname( __DIR__, 2 ) . DIRECTORY_SEPARATOR . 'vendor',
// wp-cli/wp-cli-tests is a dependency.
dirname( __DIR__, 4 ),
];
$vendor_folder = '';
foreach ( $vendor_locations as $location ) {
if (
is_dir( $location )
&& is_readable( $location )
&& is_file( "{$location}/autoload.php" )
) {
$vendor_folder = $location;
break;
}
}
return $vendor_folder;
}
/**
* Get the path to the WP-CLI framework folder.
*
* @return string Absolute path to the WP-CLI framework folder.
*/
public static function get_framework_dir(): ?string {
static $framework_folder = null;
if ( null !== $framework_folder ) {
return $framework_folder;
}
$vendor_folder = self::get_vendor_dir();
// Now we need to detect the location of wp-cli/wp-cli package.
$framework_locations = [
// wp-cli/wp-cli is the root project.
dirname( $vendor_folder ),
// wp-cli/wp-cli is a dependency.
$vendor_folder . DIRECTORY_SEPARATOR . 'wp-cli' . DIRECTORY_SEPARATOR . 'wp-cli',
];
$framework_folder = '';
foreach ( $framework_locations as $location ) {
if (
is_dir( $location )
&& is_readable( $location )
&& is_file( "{$location}/php/utils.php" )
) {
$framework_folder = $location;
break;
}
}
return $framework_folder;
}
/**
* Get the path to the WP-CLI binary.
*
* @return string Absolute path to the WP-CLI binary.
*/
public static function get_bin_path(): ?string {
static $bin_path = null;
if ( null !== $bin_path ) {
return $bin_path;
}
$bin_path = getenv( 'WP_CLI_BIN_DIR' );
if ( ! empty( $bin_path ) ) {
return $bin_path;
}
$bin_paths = [
self::get_vendor_dir() . DIRECTORY_SEPARATOR . 'bin',
self::get_framework_dir() . DIRECTORY_SEPARATOR . 'bin',
];
$bin = Utils\is_windows() ? 'wp.bat' : 'wp';
foreach ( $bin_paths as $path ) {
$full_bin_path = $path . DIRECTORY_SEPARATOR . $bin;
if ( is_file( $full_bin_path ) && ( Utils\is_windows() || is_executable( $full_bin_path ) ) ) {
return $path;
}
}
return null;
}
/**
* Get the environment variables required for launched `wp` processes.
*
* @return array<string, string|int>
*/
private static function get_process_env_variables(): array {
static $env = null;
if ( null !== $env ) {
return $env;
}
// Ensure we're using the expected `wp` binary.
$bin_path = self::get_bin_path();
if ( ! $bin_path ) {
throw new RuntimeException( 'Could not find WP-CLI binary path.' );
}
self::debug( "WP-CLI binary path: {$bin_path}" );
$bin = Utils\is_windows() ? 'wp.bat' : 'wp';
$full_bin_path = $bin_path . DIRECTORY_SEPARATOR . $bin;
if ( ! is_executable( $full_bin_path ) ) {
self::debug( "WARNING: File named '{$bin}' found in the provided/detected binary path is not executable." );
}
$path_separator = Utils\is_windows() ? ';' : ':';
$php_binary_path = dirname( PHP_BINARY );
$env = [
'PATH' => $php_binary_path . $path_separator . $bin_path . $path_separator . getenv( 'PATH' ),
'BEHAT_RUN' => 1,
'HOME' => sys_get_temp_dir() . '/wp-cli-home',
'COMPOSER_HOME' => sys_get_temp_dir() . '/wp-cli-composer-home',
'TEST_RUN_DIR' => self::$behat_run_dir,
];
$env = array_merge( $_ENV, $env );
if ( self::running_with_code_coverage() ) {
$has_coverage_driver = ( new Runtime() )->hasXdebug() || ( new Runtime() )->hasPCOV();
if ( ! $has_coverage_driver ) {
throw new RuntimeException( 'No coverage driver available. Re-run script with `--xdebug` flag, i.e. `composer behat -- --xdebug`.' );
}
$coverage_require_file = self::$behat_run_dir . '/vendor/wp-cli/wp-cli-tests/utils/generate-coverage.php';
if ( ! file_exists( $coverage_require_file ) ) {
// This file is not vendored inside the wp-cli-tests project
$coverage_require_file = self::$behat_run_dir . '/utils/generate-coverage.php';
}
$current = getenv( 'WP_CLI_REQUIRE' );
$updated = $current ? "{$current},{$coverage_require_file}" : $coverage_require_file;
$env['WP_CLI_REQUIRE'] = $updated;
}
$config_path = getenv( 'WP_CLI_CONFIG_PATH' );
if ( false !== $config_path ) {
$env['WP_CLI_CONFIG_PATH'] = $config_path;
}
$allow_root = getenv( 'WP_CLI_ALLOW_ROOT' );
if ( false !== $allow_root ) {
$env['WP_CLI_ALLOW_ROOT'] = $allow_root;
}
$term = getenv( 'TERM' );
if ( false !== $term ) {
$env['TERM'] = $term;
}
$php_args = getenv( 'WP_CLI_PHP_ARGS' );
if ( false !== $php_args ) {
$env['WP_CLI_PHP_ARGS'] = $php_args;
}
$php_used = getenv( 'WP_CLI_PHP_USED' );
if ( false !== $php_used ) {
$env['WP_CLI_PHP_USED'] = $php_used;
}
$php = getenv( 'WP_CLI_PHP' );
if ( false !== $php ) {
$env['WP_CLI_PHP'] = $php;
}
$travis_build_dir = getenv( 'TRAVIS_BUILD_DIR' );
if ( false !== $travis_build_dir ) {
$env['TRAVIS_BUILD_DIR'] = $travis_build_dir;
}
// Dump environment for debugging purposes, but before adding the GitHub token.
self::debug( 'Environment:' );
foreach ( $env as $key => $value ) {
self::debug( " [{$key}] => {$value}" );
}
$github_token = getenv( 'GITHUB_TOKEN' );
if ( false !== $github_token ) {
$env['GITHUB_TOKEN'] = $github_token;
}
return $env;
}
/**
* Get the internal variables to use within tests.
*
* @return array<string, string> Associative array of internal variables that will be mapped
* into tests.
*/
private static function get_behat_internal_variables(): array {
static $variables = null;
if ( null !== $variables ) {
return $variables;
}
$paths = [
dirname( __DIR__, 4 ) . '/wp-cli/wp-cli/VERSION',
dirname( __DIR__, 5 ) . '/VERSION',
dirname( __DIR__, 2 ) . '/vendor/wp-cli/wp-cli/VERSION',
];
$framework_root = dirname( __DIR__, 2 );
foreach ( $paths as $path ) {
if ( file_exists( $path ) ) {
$framework_root = (string) realpath( dirname( $path ) );
break;
}
}
$variables = [
'FRAMEWORK_ROOT' => realpath( $framework_root ),
'SRC_DIR' => realpath( dirname( __DIR__, 2 ) ),
'PROJECT_DIR' => realpath( dirname( __DIR__, 5 ) ),
];
return $variables;
}
/**
* Download and extract a single copy of the sqlite-database-integration plugin
* for use in subsequent WordPress copies
*
* @param string $dir
*/
private static function download_sqlite_plugin( $dir ): void {
$download_url = 'https://downloads.wordpress.org/plugin/sqlite-database-integration.zip';
$download_location = $dir . '/sqlite-database-integration.zip';
if ( ! is_dir( $dir ) ) {
mkdir( $dir );
}
$response = Utils\http_request( 'GET', $download_url, null, [], [ 'filename' => $download_location ] );
if ( 200 !== $response->status_code ) {
throw new RuntimeException( "Could not download SQLite plugin (HTTP code {$response->status_code})" );
}
$zip = new \ZipArchive();
$new_zip_file = $download_location;
if ( $zip->open( $new_zip_file ) === true ) {
if ( $zip->extractTo( $dir ) ) {
$zip->close();
unlink( $new_zip_file );
} else {
$error_message = $zip->getStatusString();
throw new RuntimeException( sprintf( 'Failed to extract files from the zip: %s', $error_message ) );
}
} else {
$error_message = $zip->getStatusString();
throw new RuntimeException( sprintf( 'Failed to open the zip file: %s', $error_message ) );
}
}
/**
* Given a WordPress installation with the sqlite-database-integration plugin,
* configure it to use SQLite as the database by placing the db.php dropin file
*
* @param string $dir
*/
private static function configure_sqlite( $dir ): void {
$db_copy = $dir . '/wp-content/mu-plugins/sqlite-database-integration/db.copy';
$db_dropin = $dir . '/wp-content/db.php';
$db_copy_contents = file_get_contents( $db_copy );
if ( false === $db_copy_contents ) {
throw new RuntimeException( "Could not read db.copy file at: {$db_copy}" );
}
/* similar to https://github.com/WordPress/sqlite-database-integration/blob/3306576c9b606bc23bbb26c15383fef08e03ab11/activate.php#L95 */
$file_contents = str_replace(
array(
'\'{SQLITE_IMPLEMENTATION_FOLDER_PATH}\'',
'{SQLITE_PLUGIN}',
'/plugins/',
),
array(
'__DIR__ . \'mu-plugins/sqlite-database-integration\'',
'sqlite-database-integration/load.php',
'/mu-plugins/',
),
$db_copy_contents
);
file_put_contents( $db_dropin, $file_contents );
}
/**
* We cache the results of `wp core download` to improve test performance.
* Ideally, we'd cache at the HTTP layer for more reliable tests.
*
* @param string $version
*/
private static function cache_wp_files( $version = '' ): void {
$wp_version = $version ?: getenv( 'WP_VERSION' );
$wp_version_suffix = $wp_version ? "-$wp_version" : '';
self::$cache_dir = sys_get_temp_dir() . '/wp-cli-test-core-download-cache' . $wp_version_suffix;
self::$sqlite_cache_dir = sys_get_temp_dir() . '/wp-cli-test-sqlite-integration-cache';
if ( 'sqlite' === getenv( 'WP_CLI_TEST_DBTYPE' ) ) {
if ( ! is_readable( self::$sqlite_cache_dir . '/sqlite-database-integration/db.copy' ) ) {
self::download_sqlite_plugin( self::$sqlite_cache_dir );
}
}
if ( is_readable( self::$cache_dir . '/wp-config-sample.php' ) ) {
return;
}
$cmd = Utils\esc_cmd( 'wp core download --force --path=%s', self::$cache_dir );
if ( $wp_version ) {
$cmd .= Utils\esc_cmd( ' --version=%s', $wp_version );
}
Process::create( $cmd, null, self::get_process_env_variables() )->run_check();
}
/**
* @BeforeSuite
*/
public static function prepare( BeforeSuiteScope $scope ): void {
self::bootstrap_feature_context();
// Test performance statistics - useful for detecting slow tests.
self::$log_run_times = getenv( 'WP_CLI_TEST_LOG_RUN_TIMES' );
if ( false !== self::$log_run_times ) {
self::log_run_times_before_suite( $scope );
}
self::$behat_run_dir = getcwd();
// TODO: Improve Windows support upstream in Utils\get_mysql_binary_path().
if ( Utils\is_windows() ) {
self::$mysql_binary = 'mysql.exe';
} else {
self::$mysql_binary = Utils\get_mysql_binary_path();
}
$result = Process::create( 'wp cli info', null, self::get_process_env_variables() )->run_check();
echo "{$result->stdout}\n";
// Remove install cache if any (not setting the static var).
$wp_version = getenv( 'WP_VERSION' );
$wp_version_suffix = ( false !== $wp_version ) ? "-$wp_version" : '';
$install_cache_dir = sys_get_temp_dir() . '/wp-cli-test-core-install-cache' . $wp_version_suffix;
if ( file_exists( $install_cache_dir ) ) {
self::remove_dir( $install_cache_dir );
}
if ( getenv( 'WP_CLI_TEST_DEBUG_BEHAT_ENV' ) ) {
exit;
}
}
/**
* @AfterSuite
*/
public static function afterSuite( AfterSuiteScope $scope ): void {
if ( self::$composer_local_repository ) {
self::remove_dir( self::$composer_local_repository );
self::$composer_local_repository = null;
}
if ( self::$log_run_times ) {
self::log_run_times_after_suite( $scope );
}
self::merge_coverage_reports();
}
/**
* @BeforeScenario
*/
public function beforeScenario( BeforeScenarioScope $scope ): void {
if ( self::$log_run_times ) {
self::log_run_times_before_scenario( $scope );
}
$this->variables = array_merge(
$this->variables,
self::get_behat_internal_variables()
);
$sql_dump_command = Utils\get_sql_dump_command();
$this->variables['MYSQL_BINARY'] = self::$mysql_binary;
$this->variables['SQL_DUMP_COMMAND'] = $sql_dump_command;
// Used in the names of the RUN_DIR and SUITE_CACHE_DIR directories.
self::$temp_dir_infix = null;
$file = self::get_event_file( $scope, $line );
if ( isset( $file ) ) {
self::$temp_dir_infix = basename( $file ) . '.' . $line;
}
}
/**
* @AfterScenario
*/
public function afterScenario( AfterScenarioScope $scope ): void {
if ( self::$run_dir ) {
// Remove altered WP install, unless there's an error (and we are not on CI).
$is_ci = getenv( 'CI' );
$is_debug = getenv( 'WP_CLI_TEST_DEBUG_BEHAT_ENV' );
if ( $scope->getTestResult()->getResultCode() <= 10 || ( $is_ci && ! $is_debug ) ) {
self::remove_dir( self::$run_dir );
}
self::$run_dir = null;
}
// Remove WP-CLI package directory if any. Set to `wp package path` by package-command and scaffold-package-command features, and by cli-info.feature.
if ( isset( $this->variables['PACKAGE_PATH'] ) ) {
self::remove_dir( $this->variables['PACKAGE_PATH'] );
}
// Remove SUITE_CACHE_DIR if any.
if ( self::$suite_cache_dir ) {
self::remove_dir( self::$suite_cache_dir );
self::$suite_cache_dir = null;
}
// Remove global config file if any.
$env = self::get_process_env_variables();
if ( isset( $env['HOME'] ) && file_exists( "{$env['HOME']}/.wp-cli/config.yml" ) ) {
unlink( "{$env['HOME']}/.wp-cli/config.yml" );
}
// Remove any background processes.
foreach ( $this->running_procs as $proc ) {
$status = proc_get_status( $proc );
self::terminate_proc( $status['pid'] );
}
// Clean up temporary files created for background processes on Windows.
$this->cleanup_temp_files( ...$this->temp_files );
$this->temp_files = [];
if ( self::$log_run_times ) {
self::log_run_times_after_scenario( $scope );
}
}
/**
* Terminate a process and any of its children.
*
* @param int $master_pid
*/
private static function terminate_proc( $master_pid ): void {
$master_pid = (int) $master_pid;
if ( Utils\is_windows() ) {
shell_exec( "taskkill /F /T /PID $master_pid > NUL 2>&1" );
return;
}
$output = shell_exec( "ps -o ppid,pid,command | grep $master_pid" );
foreach ( explode( PHP_EOL, $output ? $output : '' ) as $line ) {
if ( preg_match( '/^\s*(\d+)\s+(\d+)/', $line, $matches ) ) {
$parent = $matches[1];
$child = $matches[2];
if ( (int) $parent === $master_pid ) {
self::terminate_proc( (int) $child );
}
}
}
if ( ! function_exists( 'posix_kill' ) ) {
return;
}
if ( ! posix_kill( $master_pid, 9 ) ) {
$errno = posix_get_last_error();
// Ignore "No such process" error as that's what we want.
if ( 3 /*ESRCH*/ !== $errno ) {
throw new RuntimeException( posix_strerror( $errno ) );
}
}
}
/**
* Create a temporary WP_CLI_CACHE_DIR. Exposed as SUITE_CACHE_DIR in "Given an empty cache" step.
*/
public static function create_cache_dir(): string {
if ( self::$suite_cache_dir ) {
self::remove_dir( self::$suite_cache_dir );
}
self::$suite_cache_dir = sys_get_temp_dir() . '/' . uniqid( 'wp-cli-test-suite-cache-' . self::$temp_dir_infix . '-', true );
mkdir( self::$suite_cache_dir );
return self::$suite_cache_dir;
}
/**
* Initializes context.
* Every scenario gets its own context object.
*/
public function __construct() {
if ( getenv( 'WP_CLI_TEST_DBROOTUSER' ) ) {
$this->variables['DB_ROOT_USER'] = getenv( 'WP_CLI_TEST_DBROOTUSER' );
}
if ( false !== getenv( 'WP_CLI_TEST_DBROOTPASS' ) ) {
$this->variables['DB_ROOT_PASSWORD'] = getenv( 'WP_CLI_TEST_DBROOTPASS' );
}
if ( getenv( 'WP_CLI_TEST_DBNAME' ) ) {
$this->variables['DB_NAME'] = getenv( 'WP_CLI_TEST_DBNAME' );
} else {
$this->variables['DB_NAME'] = 'wp_cli_test';
}
if ( getenv( 'WP_CLI_TEST_DBUSER' ) ) {
$this->variables['DB_USER'] = getenv( 'WP_CLI_TEST_DBUSER' );
} else {
$this->variables['DB_USER'] = 'wp_cli_test';
}
if ( false !== getenv( 'WP_CLI_TEST_DBPASS' ) ) {
$this->variables['DB_PASSWORD'] = getenv( 'WP_CLI_TEST_DBPASS' );
} else {
$this->variables['DB_PASSWORD'] = 'password1';
}
if ( getenv( 'WP_CLI_TEST_DBHOST' ) ) {
$this->variables['DB_HOST'] = getenv( 'WP_CLI_TEST_DBHOST' );
} else {
$this->variables['DB_HOST'] = 'localhost';
}
if ( getenv( 'WP_CLI_TEST_DBTYPE' ) ) {
$this->variables['DB_TYPE'] = getenv( 'WP_CLI_TEST_DBTYPE' );
} else {
// Auto-detect database type if not explicitly set
$this->variables['DB_TYPE'] = Utils\get_db_type();
}
if ( getenv( 'MYSQL_TCP_PORT' ) ) {
$this->variables['MYSQL_PORT'] = getenv( 'MYSQL_TCP_PORT' );
}
if ( getenv( 'MYSQL_HOST' ) ) {
$this->variables['MYSQL_HOST'] = getenv( 'MYSQL_HOST' );
}
if ( getenv( 'WP_CLI_TEST_DBSOCKET' ) ) {
$this->variables['DB_SOCKET'] = getenv( 'WP_CLI_TEST_DBSOCKET' );
}
self::$db_settings['dbname'] = $this->variables['DB_NAME'];
self::$db_settings['dbuser'] = $this->variables['DB_USER'];
self::$db_settings['dbpass'] = $this->variables['DB_PASSWORD'];
self::$db_settings['dbhost'] = $this->variables['DB_HOST'];
self::$db_type = $this->variables['DB_TYPE'];
$this->variables['CORE_CONFIG_SETTINGS'] = Utils\assoc_args_to_str( self::$db_settings );
$this->test_connection();
$this->drop_db();
$this->set_cache_dir();
}
/**
* @param string $message
*/
protected static function debug( $message ): void { // phpcs:ignore Universal.Files.SeparateFunctionsFromOO.Mixed
if ( ! getenv( 'WP_CLI_TEST_DEBUG_BEHAT_ENV' ) ) {
return;
}
echo "{$message}\n";
}
/**
* Load required support files as needed before heading into the Behat context.
*/
protected static function bootstrap_feature_context(): void {
$vendor_folder = self::get_vendor_dir();
self::debug( "Vendor folder location: {$vendor_folder}" );
// Didn't manage to detect a valid vendor folder.
if ( empty( $vendor_folder ) ) {
return;
}
// We assume the vendor folder is located in the project root folder.
$project_folder = dirname( $vendor_folder );
$framework_folder = self::get_framework_dir();
self::debug( "Framework folder location: {$framework_folder}" );
// Load helper functionality that is needed for the tests.
require_once "{$framework_folder}/php/utils.php";
require_once "{$framework_folder}/php/WP_CLI/Process.php";
require_once "{$framework_folder}/php/WP_CLI/ProcessRun.php";
// Manually load Composer file includes by generating a config with require:
// statements for each file.
$project_composer = "{$project_folder}/composer.json";
if ( ! file_exists( $project_composer ) ) {
return;
}
$composer_contents = file_get_contents( $project_composer );
if ( false === $composer_contents ) {
return;
}
$composer = json_decode( $composer_contents );
if ( empty( $composer->autoload->files ) ) {
return;
}
$contents = "require:\n";
foreach ( $composer->autoload->files as $file ) {
$contents .= " - {$project_folder}/{$file}\n";
}
$temp_folder = sys_get_temp_dir() . '/wp-cli-package-test';
if (
! is_dir( $temp_folder )
&& ! mkdir( $temp_folder )
&& ! is_dir( $temp_folder )
) {
return;
}
$project_config = "{$temp_folder}/config.yml";
file_put_contents( $project_config, $contents );
putenv( 'WP_CLI_CONFIG_PATH=' . $project_config );
self::debug( "Project config file location: {$project_config}" );
self::debug( "Project config:\n{$contents}" );
}
/**
* Replace standard {VARIABLE_NAME} variables and the special {INVOKE_WP_CLI_WITH_PHP_ARGS-args} and {WP_VERSION-version-latest} variables.
* Note that standard variable names can only contain uppercase letters, digits and underscores and cannot begin with a digit.
*
* @param string $str
* @return string
*/
public function replace_variables( $str ) {
$str = preg_replace_callback( '/\{([A-Z_][A-Z_0-9]*)\}/', [ $this, 'replace_var' ], $str );
if ( false !== strpos( $str, '{INVOKE_WP_CLI_WITH_PHP_ARGS-' ) ) {
$str = $this->replace_invoke_wp_cli_with_php_args( $str );
}
if ( false !== strpos( $str, '{WP_VERSION-' ) ) {
$str = $this->replace_wp_versions( $str );
}
return $str;
}