Skip to content

Commit e4afd39

Browse files
authored
Merge pull request #410 from wp-cli/feature/declare-required-tools
Declare and check the commands that scenarios need
2 parents f949754 + 855b91b commit e4afd39

10 files changed

Lines changed: 370 additions & 11 deletions

File tree

‎.readme-partials/USING.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,18 @@ they test.
383383
skipped when there is none, which is the case when the database server runs in a
384384
container and is only reachable over TCP. Set `WP_CLI_TEST_DBSOCKET` to point at the
385385
socket if it lives somewhere unusual.
386+
* `@require-bin-<name>` — the scenario runs a command that is not always installed, such as
387+
`@require-bin-svn` or `@require-bin-ex` for one using `ex` as its editor. It is skipped
388+
where the command is not available. `@require-composer` does the same for Composer.
389+
* `@require-extension-<name>` — the scenario needs a PHP extension, such as
390+
`@require-extension-imagick`. It is skipped where the extension is not loaded.
391+
* `@require-download` — the scenario downloads files from WordPress.org. It is skipped where
392+
WordPress.org cannot be reached.
393+
394+
Requirement tags the test framework does not know are reported with a warning, as they would
395+
not filter anything. When a command fails because a command it runs does not exist, the
396+
failure names the tag to add, and `composer lint-gherkin` lists the scenarios that run
397+
commands which are not always installed without declaring them.
386398
387399
Before the scenarios run, the scenarios that are left out are listed together with the reason,
388400
separating the ones the environment cannot run, such as those needing a PHP extension that is

‎bin/run-gherkin-lint-tests‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,6 @@ then
66
exit 0;
77
fi
88

9-
# The linter is a Node package, which a PHP project cannot assume is present.
10-
# Skip rather than fail, the same way the Behat runner skips a package without a
11-
# behat.yml. The check still runs in CI, where Node is always available.
12-
if ! command -v npx > /dev/null 2>&1
13-
then
14-
echo 'Did not detect the "npx" command, skipping the Gherkin linting.'
15-
echo "It is part of Node.js 20 or later, see https://nodejs.org/ for installation instructions."
16-
exit 0;
17-
fi
18-
199
# To retrieve the WP-CLI tests package root folder, we start with this scripts
2010
# location.
2111
SOURCE="$0"
@@ -61,6 +51,21 @@ then
6151
set -- features
6252
fi
6353

54+
# Flag scenarios that run tools which are not always installed without declaring them.
55+
# This only reports, so that existing feature files can be tagged over time.
56+
php "${WP_CLI_TESTS_ROOT}/utils/check-required-tools.php" "$@"
57+
58+
# The linter is a Node package, which a PHP project cannot assume is present.
59+
# Skip rather than fail, the same way the Behat runner skips a package without a
60+
# behat.yml. The check still runs in CI, where Node is always available.
61+
if ! command -v npx > /dev/null 2>&1
62+
then
63+
echo 'Did not detect the "npx" command, skipping the Gherkin linting.'
64+
echo "It is part of Node.js 20 or later, see https://nodejs.org/ for installation instructions."
65+
exit 0;
66+
fi
67+
68+
6469
run_linter() {
6570
npx --yes "gherkin-lint-plus@${GHERKIN_LINT_VERSION}" --config "${CONFIG_FILE}" "$@"
6671
}

‎phpcs.xml.dist‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,12 @@
8080
<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
8181
<exclude-pattern>*/utils/behat-tags\.php$</exclude-pattern>
8282
<exclude-pattern>*/utils/behat-parallel\.php$</exclude-pattern>
83+
<exclude-pattern>*/utils/check-required-tools\.php$</exclude-pattern>
8384
</rule>
8485
<rule ref="WordPress.WP.GlobalVariablesOverride">
8586
<exclude-pattern>*/utils/behat-tags\.php$</exclude-pattern>
8687
<exclude-pattern>*/utils/behat-parallel\.php$</exclude-pattern>
88+
<exclude-pattern>*/utils/check-required-tools\.php$</exclude-pattern>
8789
</rule>
8890

8991
<!-- This is a procedural stand-alone file that is adding polyfills when

‎src/Context/Support.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,30 @@
1212

1313
trait Support {
1414

15+
/**
16+
* Explain how to declare a command that a command run by the scenario needed but could not find.
17+
*
18+
* @param string|null $stderr Error output to inspect. Defaults to the one of the last command run.
19+
* @return string Empty if no command was missing.
20+
*/
21+
protected function missing_command_hint( $stderr = null ): string {
22+
if ( null === $stderr ) {
23+
if ( ! isset( $this->result ) ) {
24+
return '';
25+
}
26+
$stderr = (string) $this->result->stderr;
27+
}
28+
29+
if (
30+
! preg_match( '/\b(?:sh|bash|dash|zsh)(?:: line \d+|: \d+)?: ([A-Za-z0-9_.+-]+): (?:command )?not found/', $stderr, $matches )
31+
&& ! preg_match( "/'([A-Za-z0-9_.+-]+)' is not recognized as an internal or external command/", $stderr, $matches )
32+
) {
33+
return '';
34+
}
35+
36+
return "\n\nThe command `{$matches[1]}` was not found. If the scenario needs it, tag it with @require-bin-{$matches[1]}, so that environments without it report the scenario as not run instead of failing it.";
37+
}
38+
1539
/**
1640
* @param string $regex
1741
* @param string $actual
@@ -141,6 +165,7 @@ protected function check_string( $output, $expected, $action, $message = false,
141165
}
142166

143167
$message .= "\n\n" . $action_message . "\n" . $expected;
168+
$message .= $this->missing_command_hint();
144169

145170
$diff = $this->generate_diff( $expected, rtrim( $output, "\n" ) );
146171
if ( ! empty( $diff ) ) {

‎src/Context/ThenStepDefinitions.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function then_the_return_code_should_be( $not, $return_code ): void {
3535
( ! $not && (int) $return_code !== $this->result->return_code )
3636
|| ( $not && (int) $return_code === $this->result->return_code )
3737
) {
38-
throw new RuntimeException( $this->result );
38+
throw new RuntimeException( $this->result . $this->missing_command_hint() );
3939
}
4040
}
4141

‎src/Context/WhenStepDefinitions.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public function wpcli_tests_invoke_proc( $proc, $mode ) {
3232
$message .= "\n\nThe command unexpectedly exited with status {$status}. If you expect a non-zero exit status, use `When I try [...]`. Else, this may be a bug in your code or test.";
3333
}
3434

35+
$message .= $this->missing_command_hint( $e->getMessage() );
36+
3537
throw new \RuntimeException( $message, $e->getCode(), $e );
3638
}
3739

‎tests/tests/TestBehatTags.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,4 +683,29 @@ public function test_strict_requirements_allow_other_configurations(): void {
683683
$this->assertSame( 0, $result['exit_code'] );
684684
$this->assertStringContainsString( '~@broken', $result['stdout'] );
685685
}
686+
687+
public function test_missing_commands_are_filtered_out_and_reported(): void {
688+
file_put_contents(
689+
$this->temp_dir . DIRECTORY_SEPARATOR . 'features' . DIRECTORY_SEPARATOR . 'commands.feature',
690+
"Feature: Commands\n\n @require-bin-wpclinonexistentcommand\n Scenario: Needs a missing command\n Given a step\n\n @require-bin-php\n Scenario: Needs PHP\n Given a step\n"
691+
);
692+
693+
$result = $this->run_behat_tags_script_with_streams();
694+
695+
$this->assertStringContainsString( '~@require-bin-wpclinonexistentcommand', $result['stdout'] );
696+
$this->assertStringNotContainsString( '@require-bin-php', $result['stdout'] );
697+
$this->assertStringContainsString( '@require-bin-wpclinonexistentcommand, as the command "wpclinonexistentcommand" is not available: ', $result['stderr'] );
698+
}
699+
700+
public function test_unknown_requirement_tags_are_warned_about(): void {
701+
file_put_contents(
702+
$this->temp_dir . DIRECTORY_SEPARATOR . 'features' . DIRECTORY_SEPARATOR . 'unknown.feature',
703+
"Feature: Unknown\n\n @require-wpclinonexistent\n Scenario: Has an unknown requirement\n Given a step\n"
704+
);
705+
706+
$result = $this->run_behat_tags_script_with_streams();
707+
708+
$this->assertStringContainsString( 'Warning: @require-wpclinonexistent is not a known requirement and does not filter anything: ', $result['stderr'] );
709+
$this->assertStringContainsString( 'unknown.feature:4', $result['stderr'] );
710+
}
686711
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace WP_CLI\Tests\Tests;
4+
5+
use PHPUnit\Framework\Attributes\DataProvider;
6+
use WP_CLI\Tests\Context\Support;
7+
use WP_CLI\Tests\TestCase;
8+
9+
class TestMissingCommandHint extends TestCase {
10+
11+
/**
12+
* @return string
13+
*/
14+
private function hint( string $stderr ) {
15+
$context = new class() {
16+
use Support;
17+
18+
/**
19+
* @var \WP_CLI\ProcessRun|null
20+
*/
21+
public $result = null;
22+
23+
public function hint( string $stderr ): string {
24+
return $this->missing_command_hint( $stderr );
25+
}
26+
};
27+
28+
return $context->hint( $stderr );
29+
}
30+
31+
/**
32+
* @dataProvider data_missing_commands
33+
*/
34+
#[DataProvider( 'data_missing_commands' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound
35+
public function test_missing_commands_are_named( string $stderr, string $command ): void {
36+
$this->assertStringContainsString( "The command `{$command}` was not found. If the scenario needs it, tag it with @require-bin-{$command}", $this->hint( $stderr ) );
37+
}
38+
39+
/**
40+
* @return array<array{string, string}>
41+
*/
42+
public static function data_missing_commands(): array {
43+
return [
44+
[ "sh: line 1: ex: command not found\n", 'ex' ],
45+
[ "sh: 1: ex: not found\n", 'ex' ],
46+
[ "bash: svn: command not found\n", 'svn' ],
47+
[ "'zipinfo' is not recognized as an internal or external command,\n", 'zipinfo' ],
48+
];
49+
}
50+
51+
public function test_other_errors_get_no_hint(): void {
52+
$this->assertSame( '', $this->hint( "Error: not found\n" ) );
53+
$this->assertSame( '', $this->hint( "Error: Plugin: not found\n" ) );
54+
$this->assertSame( '', $this->hint( '' ) );
55+
}
56+
}

‎utils/behat-tags.php‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,86 @@ function os_tags( $features_folder = 'features' ) {
393393
return $skip_tags;
394394
}
395395

396+
/**
397+
* Whether a command is available in the environment.
398+
*
399+
* @param string $command
400+
* @return bool
401+
*/
402+
function command_available( $command ) {
403+
$check = 'Windows' === PHP_OS_FAMILY ? 'where ' . escapeshellarg( $command ) . ' 2> NUL' : 'command -v ' . escapeshellarg( $command ) . ' 2> /dev/null';
404+
exec( $check, $output, $exit_code );
405+
return 0 === $exit_code;
406+
}
407+
408+
/**
409+
* Tags for requirements on the environment beyond PHP extensions: commands, network access and opcache settings.
410+
*
411+
* @param string $features_folder The folder where the feature files are located.
412+
* @return array
413+
*/
414+
function environment_tags( $features_folder = 'features' ) {
415+
$skip_tags = array();
416+
417+
$feature_files = glob( $features_folder . DIRECTORY_SEPARATOR . '*.feature' );
418+
$contents = '';
419+
foreach ( $feature_files ? $feature_files : array() as $feature_file ) {
420+
$contents .= (string) file_get_contents( $feature_file ) . "\n";
421+
}
422+
423+
// Commands a scenario needs, such as "@require-bin-svn".
424+
if ( preg_match_all( '/@require-bin-([A-Za-z0-9_.+-]+)/', $contents, $matches ) ) {
425+
foreach ( array_unique( $matches[1] ) as $command ) {
426+
if ( ! command_available( $command ) ) {
427+
$skip_tags[] = "@require-bin-{$command}";
428+
}
429+
}
430+
}
431+
432+
if ( false !== strpos( $contents, '@require-composer' ) && ! command_available( 'composer' ) ) {
433+
$skip_tags[] = '@require-composer';
434+
}
435+
436+
if ( false !== strpos( $contents, '@require-download' ) ) {
437+
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed connection is the answer being looked for.
438+
$connection = @fsockopen( 'downloads.wordpress.org', 443, $errno, $errstr, 5 );
439+
if ( false === $connection ) {
440+
$skip_tags[] = '@require-download';
441+
} else {
442+
fclose( $connection );
443+
}
444+
}
445+
446+
// WP-CLI reads the doc comments of commands, which opcache can be configured to drop.
447+
if ( false !== strpos( $contents, '@require-opcache-save-comments' ) && extension_loaded( 'Zend OPcache' ) && ! ini_get( 'opcache.save_comments' ) ) {
448+
$skip_tags[] = '@require-opcache-save-comments';
449+
}
450+
451+
return $skip_tags;
452+
}
453+
454+
/**
455+
* Warn about requirement tags that the test framework does not know, and which therefore never filter anything.
456+
*
457+
* @param string $features_folder The folder where the feature files are located.
458+
*/
459+
function warn_about_unknown_requirement_tags( $features_folder = 'features' ) {
460+
$known = '/^@(require-(wp|php|mysql|mariadb)-[0-9.]+|less-than-(wp|php|mysql|mariadb)-[0-9.]+|require-(mysql|mariadb|sqlite|mysql-or-mariadb|object-cache|wp-stable|mysql-socket|composer|download|opcache-save-comments|windows|macos|linux)|require-(extension|bin)-[A-Za-z0-9_.+-]+)$/';
461+
462+
$unknown = array();
463+
foreach ( scenarios_with_tags( $features_folder ) as $scenario ) {
464+
foreach ( $scenario['tags'] as $tag ) {
465+
if ( preg_match( '/^@(require|less-than)-/', $tag ) && ! preg_match( $known, $tag ) ) {
466+
$unknown[ $tag ][] = $scenario['path'];
467+
}
468+
}
469+
}
470+
471+
foreach ( $unknown as $tag => $paths ) {
472+
fwrite( STDERR, sprintf( "Warning: %s is not a known requirement and does not filter anything: %s\n", $tag, implode( ', ', array_unique( $paths ) ) ) );
473+
}
474+
}
475+
396476
/**
397477
* Get the scenarios of the feature files with the tags that apply to them.
398478
*
@@ -457,6 +537,22 @@ function describe_skip_tag( $tag, $context ) {
457537
return array( true, "the PHP extension \"{$matches[1]}\" is not loaded" );
458538
}
459539

540+
if ( preg_match( '/^@require-bin-(.+)$/', $tag, $matches ) ) {
541+
return array( true, "the command \"{$matches[1]}\" is not available" );
542+
}
543+
544+
if ( '@require-composer' === $tag ) {
545+
return array( true, 'the command "composer" is not available' );
546+
}
547+
548+
if ( '@require-download' === $tag ) {
549+
return array( true, 'downloads.wordpress.org cannot be reached' );
550+
}
551+
552+
if ( '@require-opcache-save-comments' === $tag ) {
553+
return array( true, 'opcache drops doc comments' );
554+
}
555+
460556
if ( '@require-mysql-socket' === $tag ) {
461557
return array( true, 'the database server cannot be reached through a socket' );
462558
}
@@ -583,6 +679,9 @@ function ( $path ) {
583679

584680
$skip_tags = array_merge( $skip_tags, extension_tags( $features_folder ) );
585681
$skip_tags = array_merge( $skip_tags, os_tags( $features_folder ) );
682+
$skip_tags = array_merge( $skip_tags, environment_tags( $features_folder ) );
683+
684+
warn_about_unknown_requirement_tags( $features_folder );
586685

587686
$missing = report_filtered_scenarios(
588687
$skip_tags,

0 commit comments

Comments
 (0)