From 0aed73375f378630ccd5edddfd4d2b459da4f33c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 17:59:03 +0000 Subject: [PATCH 01/18] Turn AGENTS.md rules into checks Three rules that AGENTS.md spelled out in prose are now enforced by code, so the synced AGENTS.md can drop them: - A PHPStan rule (`wpcli.testCaseParent`) reports test classes that extend PHPUnit\Framework\TestCase directly instead of WP_CLI\Tests\TestCase. - The runner scripts default to the compact, uncolored reports when they run under an AI coding agent (AI_AGENT, CLAUDECODE, CODEX_SANDBOX, CURSOR_AGENT or GEMINI_CLI is set). Setting NO_COLOR or WP_CLI_TEST_QUIET to an empty string keeps the full report. - A Behat step that fails because a `wp` command is not registered now says that only the commands of packages in composer.json can be run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 8 ++ bin/run-gherkin-lint-tests | 8 ++ bin/run-linter-tests | 8 ++ bin/run-php-unit-tests | 8 ++ bin/run-phpcs-tests | 8 ++ bin/run-phpstan-tests | 8 ++ extension.neon | 1 + src/Context/Support.php | 4 + src/PHPStan/TestCaseParentRule.php | 53 ++++++++ tests/data/test_case_parent.php | 34 +++++ .../tests/PHPStan/TestTestCaseParentRule.php | 35 +++++ tests/tests/TestAgentReportDefaults.php | 127 ++++++++++++++++++ tests/tests/TestMissingCommandHint.php | 7 + 13 files changed, 309 insertions(+) create mode 100644 src/PHPStan/TestCaseParentRule.php create mode 100644 tests/data/test_case_parent.php create mode 100644 tests/tests/PHPStan/TestTestCaseParentRule.php create mode 100644 tests/tests/TestAgentReportDefaults.php diff --git a/bin/run-behat-tests b/bin/run-behat-tests index c9198b712..5b062d82f 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -1,5 +1,13 @@ #!/bin/bash +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + # Run the Behat tests only if a Behat config file is found. if [ ! -f "behat.yml" ] && [ ! -f "behat.php" ] && [ ! -f "behat.dist.php" ]; then echo 'Did not detect "behat.yml" file, skipping Behat tests.' diff --git a/bin/run-gherkin-lint-tests b/bin/run-gherkin-lint-tests index 3a648e0ca..5ef11132a 100755 --- a/bin/run-gherkin-lint-tests +++ b/bin/run-gherkin-lint-tests @@ -1,5 +1,13 @@ #!/bin/sh +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + # Run the Gherkin linter only if there are feature files to lint. if [ ! -d "features" ] then diff --git a/bin/run-linter-tests b/bin/run-linter-tests index e43cacfc3..6577abecb 100755 --- a/bin/run-linter-tests +++ b/bin/run-linter-tests @@ -1,5 +1,13 @@ #!/bin/sh +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + # Honor the NO_COLOR convention (https://no-color.org/). This has to turn the # color off explicitly rather than omit the flag, because the tool's own # detection only asks whether STDOUT is a terminal and knows nothing about diff --git a/bin/run-php-unit-tests b/bin/run-php-unit-tests index 3d89befab..492b880a9 100755 --- a/bin/run-php-unit-tests +++ b/bin/run-php-unit-tests @@ -1,5 +1,13 @@ #!/bin/sh +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + # Run the unit tests, if they exist if [ -f "phpunit.xml" ] || [ -f "phpunit.xml.dist" ] || [ -f ".phpunit.xml" ] || [ -f ".phpunit.xml.dist" ] then diff --git a/bin/run-phpcs-tests b/bin/run-phpcs-tests index 3c2a9f043..f9f2a269a 100755 --- a/bin/run-phpcs-tests +++ b/bin/run-phpcs-tests @@ -1,5 +1,13 @@ #!/bin/sh +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + EXIT_CODE=0 # 1. Run standard PHP code style check if a configuration file exists. diff --git a/bin/run-phpstan-tests b/bin/run-phpstan-tests index a6cdeeac9..b994f3eb1 100755 --- a/bin/run-phpstan-tests +++ b/bin/run-phpstan-tests @@ -1,5 +1,13 @@ #!/bin/sh +# AI coding agents pay for every byte of a report they read back, so they get +# the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET +# to an empty string keeps the full report. +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then + [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 + [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 +fi + EXIT_CODE=0 # 1. Run the static analysis only if a configuration file exists. diff --git a/extension.neon b/extension.neon index ae4275061..73a34178f 100644 --- a/extension.neon +++ b/extension.neon @@ -25,6 +25,7 @@ services: - phpstan.parser.richParserNodeVisitor rules: - WP_CLI\Tests\PHPStan\WPCliAddHookCallbackRule + - WP_CLI\Tests\PHPStan\TestCaseParentRule parameters: dynamicConstantNames: diff --git a/src/Context/Support.php b/src/Context/Support.php index 824a496fb..c367c47e1 100644 --- a/src/Context/Support.php +++ b/src/Context/Support.php @@ -26,6 +26,10 @@ protected function missing_command_hint( $stderr = null ): string { $stderr = (string) $this->result->stderr; } + if ( preg_match( "/'([^']+)' is not a registered wp command\./", $stderr, $matches ) ) { + return "\n\nThe WP-CLI command `{$matches[1]}` is not installed. Only the commands of the packages in composer.json (`require` or `require-dev`) can be run in the tests, so add the package that provides it there."; + } + if ( ! preg_match( '/\b(?:sh|bash|dash|zsh)(?:: line \d+|: \d+)?: ([A-Za-z0-9_.+-]+): (?:command )?not found/', $stderr, $matches ) && ! preg_match( "/'([A-Za-z0-9_.+-]+)' is not recognized as an internal or external command/", $stderr, $matches ) diff --git a/src/PHPStan/TestCaseParentRule.php b/src/PHPStan/TestCaseParentRule.php new file mode 100644 index 000000000..ffb4eafa5 --- /dev/null +++ b/src/PHPStan/TestCaseParentRule.php @@ -0,0 +1,53 @@ + + */ +final class TestCaseParentRule implements Rule { + + public function getNodeType(): string { + return Class_::class; + } + + public function processNode( Node $node, Scope $scope ): array { + if ( null === $node->extends ) { + return []; + } + + $parent = $scope->resolveName( $node->extends ); + + if ( 'phpunit\\framework\\testcase' !== strtolower( $parent ) ) { + return []; + } + + return [ + RuleErrorBuilder::message( + sprintf( + 'Test class %s extends %s directly. Extend WP_CLI\\Tests\\TestCase instead, so the test runs on every supported PHPUnit version.', + null !== $node->name ? $node->name->toString() : 'class@anonymous', + $parent + ) + ) + ->identifier( 'wpcli.testCaseParent' ) + ->build(), + ]; + } +} diff --git a/tests/data/test_case_parent.php b/tests/data/test_case_parent.php new file mode 100644 index 000000000..028a5ab5c --- /dev/null +++ b/tests/data/test_case_parent.php @@ -0,0 +1,34 @@ + + */ +class TestTestCaseParentRule extends RuleTestCase { + + protected function getRule(): Rule { + return new TestCaseParentRule(); + } + + public function testRule(): void { + $this->analyse( + [ __DIR__ . '/../../data/test_case_parent.php' ], + [ + [ + 'Test class ExtendsPHPUnitTestCase extends PHPUnit\Framework\TestCase directly. Extend WP_CLI\Tests\TestCase instead, so the test runs on every supported PHPUnit version.', + 25, + ], + [ + 'Test class ExtendsPHPUnitTestCaseFullyQualified extends PHPUnit\Framework\TestCase directly. Extend WP_CLI\Tests\TestCase instead, so the test runs on every supported PHPUnit version.', + 29, + ], + ] + ); + } +} diff --git a/tests/tests/TestAgentReportDefaults.php b/tests/tests/TestAgentReportDefaults.php new file mode 100644 index 000000000..092fb3c63 --- /dev/null +++ b/tests/tests/TestAgentReportDefaults.php @@ -0,0 +1,127 @@ +markTestSkipped( 'The runner scripts are POSIX shell scripts.' ); + } + + $this->temp_dir = sys_get_temp_dir() . '/wp-cli-agent-defaults-' . uniqid(); + mkdir( $this->temp_dir . '/vendor/bin', 0777, true ); + touch( $this->temp_dir . '/phpcs.xml.dist' ); + + // Stands in for PHPCS and prints the arguments the runner passed to it. + file_put_contents( $this->temp_dir . '/vendor/bin/phpcs', "#!/bin/sh\necho \"ARGS:\$*\"\n" ); + chmod( $this->temp_dir . '/vendor/bin/phpcs', 0755 ); + } + + protected function tear_down(): void { + if ( '' !== $this->temp_dir ) { + unlink( $this->temp_dir . '/vendor/bin/phpcs' ); + unlink( $this->temp_dir . '/phpcs.xml.dist' ); + rmdir( $this->temp_dir . '/vendor/bin' ); + rmdir( $this->temp_dir . '/vendor' ); + rmdir( $this->temp_dir ); + } + + parent::tear_down(); + } + + /** + * @param array $env + */ + private function phpcs_args( array $env ): string { + // The variables go through env(1), because proc_open() drops the ones + // that are set to an empty string. + $command = [ 'env' ]; + foreach ( $env as $name => $value ) { + $command[] = "{$name}={$value}"; + } + $command[] = dirname( __DIR__, 2 ) . '/bin/run-phpcs-tests'; + + $process = proc_open( + $command, + [ 1 => [ 'pipe', 'w' ] ], + $pipes, + $this->temp_dir, + [ 'PATH' => (string) getenv( 'PATH' ) ] + ); + $this->assertIsResource( $process ); + + $output = (string) stream_get_contents( $pipes[1] ); + fclose( $pipes[1] ); + proc_close( $process ); + + $this->assertSame( 1, preg_match( '/^ARGS:(.*)$/m', $output, $matches ), $output ); + + return trim( $matches[1] ); + } + + /** + * @return array, string}> + */ + public static function data_environments(): array { + return [ + 'no agent' => [ [], '' ], + 'Claude Code' => [ [ 'CLAUDECODE' => '1' ], '-q --report=emacs' ], + 'generic AI_AGENT marker' => [ [ 'AI_AGENT' => 'some-agent' ], '-q --report=emacs' ], + 'agent opted out' => [ + [ + 'CLAUDECODE' => '1', + 'WP_CLI_TEST_QUIET' => '', + ], + '', + ], + 'quiet asked for by a user' => [ [ 'WP_CLI_TEST_QUIET' => '1' ], '-q --report=emacs' ], + ]; + } + + /** + * @dataProvider data_environments + * + * @param array $env + */ + #[DataProvider( 'data_environments' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound + public function test_phpcs_report_follows_the_environment( array $env, string $expected ): void { + $this->assertSame( $expected, $this->phpcs_args( $env ) ); + } + + /** + * Every runner has to detect agents the same way, or one of them drifts. + */ + public function test_all_runners_share_the_same_detection(): void { + $blocks = []; + foreach ( self::SCRIPTS as $script ) { + $source = (string) file_get_contents( dirname( __DIR__, 2 ) . '/bin/' . $script ); + $this->assertSame( 1, preg_match( '/^# AI coding agents.*?^fi$/ms', $source, $matches ), "{$script} has no agent detection." ); + $blocks[ $script ] = $matches[0]; + } + + $this->assertCount( 1, array_unique( $blocks ), 'The agent detection differs between the runner scripts.' ); + } +} diff --git a/tests/tests/TestMissingCommandHint.php b/tests/tests/TestMissingCommandHint.php index c6aa87210..8864ad508 100644 --- a/tests/tests/TestMissingCommandHint.php +++ b/tests/tests/TestMissingCommandHint.php @@ -48,6 +48,13 @@ public static function data_missing_commands(): array { ]; } + public function test_unregistered_wp_commands_point_to_composer_json(): void { + $this->assertStringContainsString( + 'The WP-CLI command `scaffold` is not installed. Only the commands of the packages in composer.json', + $this->hint( "Error: 'scaffold' is not a registered wp command. See 'wp help' for available commands.\n" ) + ); + } + public function test_other_errors_get_no_hint(): void { $this->assertSame( '', $this->hint( "Error: not found\n" ) ); $this->assertSame( '', $this->hint( "Error: Plugin: not found\n" ) ); From 7209d1d6b97cc3e6113218a89b781b0efeb51b92 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:01:21 +0000 Subject: [PATCH 02/18] Pass the runner command to proc_open() as a string for PHP < 7.4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- tests/tests/TestAgentReportDefaults.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/tests/TestAgentReportDefaults.php b/tests/tests/TestAgentReportDefaults.php index 092fb3c63..76a960fed 100644 --- a/tests/tests/TestAgentReportDefaults.php +++ b/tests/tests/TestAgentReportDefaults.php @@ -58,11 +58,12 @@ protected function tear_down(): void { private function phpcs_args( array $env ): string { // The variables go through env(1), because proc_open() drops the ones // that are set to an empty string. - $command = [ 'env' ]; + // A string rather than an array, which proc_open() only takes as of PHP 7.4. + $command = 'env'; foreach ( $env as $name => $value ) { - $command[] = "{$name}={$value}"; + $command .= ' ' . escapeshellarg( "{$name}={$value}" ); } - $command[] = dirname( __DIR__, 2 ) . '/bin/run-phpcs-tests'; + $command .= ' ' . escapeshellarg( dirname( __DIR__, 2 ) . '/bin/run-phpcs-tests' ); $process = proc_open( $command, From bd4a557d980cd04e167801f4a6f6f8c365b0f721 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:14:19 +0000 Subject: [PATCH 03/18] Detect Antigravity through ANTIGRAVITY_AGENT as well Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 2 +- bin/run-gherkin-lint-tests | 2 +- bin/run-linter-tests | 2 +- bin/run-php-unit-tests | 2 +- bin/run-phpcs-tests | 2 +- bin/run-phpstan-tests | 2 +- tests/tests/TestAgentReportDefaults.php | 1 + 7 files changed, 7 insertions(+), 6 deletions(-) diff --git a/bin/run-behat-tests b/bin/run-behat-tests index 5b062d82f..0cf4e9855 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/bin/run-gherkin-lint-tests b/bin/run-gherkin-lint-tests index 5ef11132a..f2d2118a1 100755 --- a/bin/run-gherkin-lint-tests +++ b/bin/run-gherkin-lint-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/bin/run-linter-tests b/bin/run-linter-tests index 6577abecb..d642f4793 100755 --- a/bin/run-linter-tests +++ b/bin/run-linter-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/bin/run-php-unit-tests b/bin/run-php-unit-tests index 492b880a9..5f9fa92c9 100755 --- a/bin/run-php-unit-tests +++ b/bin/run-php-unit-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/bin/run-phpcs-tests b/bin/run-phpcs-tests index f9f2a269a..97408d95f 100755 --- a/bin/run-phpcs-tests +++ b/bin/run-phpcs-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/bin/run-phpstan-tests b/bin/run-phpstan-tests index b994f3eb1..28495ddca 100755 --- a/bin/run-phpstan-tests +++ b/bin/run-phpstan-tests @@ -3,7 +3,7 @@ # AI coding agents pay for every byte of a report they read back, so they get # the compact, uncolored one by default. Setting NO_COLOR or WP_CLI_TEST_QUIET # to an empty string keeps the full report. -if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}" ]; then +if [ -n "${AI_AGENT}${CLAUDECODE}${CODEX_SANDBOX}${CURSOR_AGENT}${GEMINI_CLI}${ANTIGRAVITY_AGENT}" ]; then [ -n "${NO_COLOR+set}" ] || export NO_COLOR=1 [ -n "${WP_CLI_TEST_QUIET+set}" ] || export WP_CLI_TEST_QUIET=1 fi diff --git a/tests/tests/TestAgentReportDefaults.php b/tests/tests/TestAgentReportDefaults.php index 76a960fed..775d76344 100644 --- a/tests/tests/TestAgentReportDefaults.php +++ b/tests/tests/TestAgentReportDefaults.php @@ -91,6 +91,7 @@ public static function data_environments(): array { 'no agent' => [ [], '' ], 'Claude Code' => [ [ 'CLAUDECODE' => '1' ], '-q --report=emacs' ], 'generic AI_AGENT marker' => [ [ 'AI_AGENT' => 'some-agent' ], '-q --report=emacs' ], + 'Antigravity' => [ [ 'ANTIGRAVITY_AGENT' => '1' ], '-q --report=emacs' ], 'agent opted out' => [ [ 'CLAUDECODE' => '1', From aba6fd50a3eb1ef556c7a031800b27dc64266e8e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:23:43 +0000 Subject: [PATCH 04/18] Report undefined Behat steps with the closest existing ones The step list in AGENTS.md was how agents learned which Behat steps exist. Without it, a guessed step such as `Then STDOUT should equal:` is reported only once a scenario reaches it, and Behat then suggests snippets for new step definitions in FeatureContext, which lives in vendor/. run-behat-tests now checks the feature files it is given against the output of `behat --definitions=l` before any scenario is set up. Each step that no definition matches is reported with its line and the three closest existing steps, and the run stops. The check covers project-specific contexts too, since it reads the definitions from Behat itself. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 13 ++ src/StepChecker.php | 218 ++++++++++++++++++++++++++++++++ tests/tests/TestStepChecker.php | 105 +++++++++++++++ utils/check-feature-steps.php | 92 ++++++++++++++ 4 files changed, 428 insertions(+) create mode 100644 src/StepChecker.php create mode 100644 tests/tests/TestStepChecker.php create mode 100644 utils/check-feature-steps.php diff --git a/bin/run-behat-tests b/bin/run-behat-tests index 0cf4e9855..524835eec 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -325,6 +325,19 @@ fi # Generate the tags to apply environment-specific filters. BEHAT_TAGS=$(php "$WP_CLI_TESTS_ROOT"/utils/behat-tags.php) +# Report steps that no definition matches before any scenario is set up, each +# with the closest existing steps. Behat would only report them once a scenario +# reached them, and suggest snippets for new step definitions instead. +CHECK_STEPS=1 +for arg in "$@"; do + case "$arg" in + -d*|--definitions|--definitions=*|--rerun|--init|-h|--help|--story-syntax) CHECK_STEPS="";; + esac +done +if [ -n "${CHECK_STEPS}" ] && ! php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$@"; then + exit 1 +fi + BEHAT_EXTRA_ARGS=() if [[ "${WP_CLI_TEST_COVERAGE}" == "true" ]] && vendor/bin/behat --help 2>/dev/null | grep -q 'xdebug'; then BEHAT_EXTRA_ARGS+=('--xdebug') diff --git a/src/StepChecker.php b/src/StepChecker.php new file mode 100644 index 000000000..7a9484641 --- /dev/null +++ b/src/StepChecker.php @@ -0,0 +1,218 @@ + + */ + public static function parse_definitions( $listing ) { + $definitions = []; + + foreach ( preg_split( '/\R/', $listing ) ?: [] as $line ) { + if ( ! preg_match( '/^\s*\S+\s*\|\s*(Given|When|Then)\s+(.+?)\s*$/', $line, $matches ) ) { + continue; + } + + $pattern = $matches[2]; + $regex = preg_match( '/^\/.*\/[a-zA-Z]*$/', $pattern ) ? $pattern : self::turnip_to_regex( $pattern ); + + $definitions[] = [ + 'label' => $matches[1] . ' ' . $pattern, + 'regex' => $regex, + ]; + } + + return $definitions; + } + + /** + * Converts a Turnip pattern, such as `a WP install(ation) in :subdir`, to a regex. + * + * @param string $pattern + * @return string + */ + public static function turnip_to_regex( $pattern ) { + $words = []; + + foreach ( explode( ' ', $pattern ) as $word ) { + // `foo/bar` accepts either word, unless the word holds a placeholder. + if ( false !== strpos( $word, '/' ) && false === strpos( $word, ':' ) ) { + $words[] = '(?:' . implode( '|', array_map( [ self::class, 'turnip_word_to_regex' ], explode( '/', $word ) ) ) . ')'; + continue; + } + + $words[] = self::turnip_word_to_regex( $word ); + } + + return '/^' . implode( ' ', $words ) . '$/'; + } + + /** + * @param string $word + * @return string + */ + private static function turnip_word_to_regex( $word ) { + $regex = ''; + $offset = 0; + + preg_match_all( '/:(\w+)|\(([^)]*)\)/', $word, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); + + foreach ( $matches as $match ) { + $regex .= preg_quote( substr( $word, $offset, $match[0][1] - $offset ), '/' ); + + if ( isset( $match[2] ) && -1 !== $match[2][1] ) { + $regex .= '(?:' . preg_quote( $match[2][0], '/' ) . ')?'; + } else { + $regex .= '(?:"[^"]*"|\'[^\']*\'|[^\s"\']+)'; + } + + $offset = $match[0][1] + strlen( $match[0][0] ); + } + + return $regex . preg_quote( substr( $word, $offset ), '/' ); + } + + /** + * Lists the steps of a feature file that no definition matches. + * + * Steps of a scenario outline that hold a `` are only + * checked once the placeholder is filled in, so they are left out. + * + * @param string $contents Contents of the feature file. + * @param array $definitions + * @return array Undefined steps, keyed by line number. + */ + public static function find_undefined_steps( $contents, array $definitions ) { + $undefined = []; + $fence = null; + + foreach ( preg_split( '/\R/', $contents ) ?: [] as $index => $line ) { + $trimmed = trim( $line ); + + if ( null !== $fence ) { + if ( $trimmed === $fence ) { + $fence = null; + } + continue; + } + + if ( '"""' === $trimmed || '```' === $trimmed ) { + $fence = $trimmed; + continue; + } + + if ( ! preg_match( '/^(?:Given|When|Then|And|But|\*)\s+(.+)$/', $trimmed, $matches ) ) { + continue; + } + + $step = $matches[1]; + + if ( self::is_defined( $step, $definitions ) || preg_match( '/<[^>\s]+>/', $step ) ) { + continue; + } + + $undefined[ $index + 1 ] = $trimmed; + } + + return $undefined; + } + + /** + * @param string $step Step text without its keyword. + * @param array $definitions + * @return bool + */ + private static function is_defined( $step, array $definitions ) { + foreach ( $definitions as $definition ) { + if ( 1 === @preg_match( $definition['regex'], $step ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A definition this cannot parse simply does not match. + return true; + } + } + + return false; + } + + /** + * Picks the definitions that read most like the given step. + * + * @param string $step Step, with or without its keyword. + * @param array $definitions + * @param int $count + * @return array Labels of the closest definitions, closest first. + */ + public static function suggest( $step, array $definitions, $count = 3 ) { + $step = strtolower( (string) preg_replace( '/^(?:Given|When|Then|And|But|\*)\s+/', '', trim( $step ) ) ); + $scores = []; + + foreach ( $definitions as $definition ) { + similar_text( $step, self::readable( $definition['label'], $step ), $percent ); + $scores[ $definition['label'] ] = $percent; + } + + arsort( $scores ); + + return array_slice( array_keys( $scores ), 0, $count ); + } + + /** + * Renders a definition the way a step using it would read, as close to the + * given step as its alternatives allow, so that the two can be compared. + * + * @param string $label Definition label, keyword included. + * @param string $step Lowercase step text without its keyword. + * @return string + */ + private static function readable( $label, $step ) { + $text = strtolower( (string) preg_replace( '/^(?:Given|When|Then)\s+/', '', $label ) ); + + if ( ! preg_match( '/^\/\^?(.*?)\$?\/[a-z]*$/', $text, $matches ) ) { + // A Turnip pattern: placeholders read as a value, optional parts as written. + return (string) preg_replace( [ '/:\w+/', '/[()]/' ], [ 'x', '' ], $text ); + } + + $text = $matches[1]; + + // Innermost groups first: a list of words becomes the one closest to the + // step, an optional part stays only if the step has it, and anything + // else that captures a value reads as a value. + do { + $text = (string) preg_replace_callback( + '/\((?:\?:)?([^()]*)\)(\?)?/', + static function ( $group ) use ( $step ) { + $alternatives = explode( '|', $group[1] ); + if ( preg_match( '/[\[\\.+*]/', $group[1] ) ) { + return 'x'; + } + if ( ! empty( $group[2] ) ) { + return false !== strpos( $step, trim( $group[1] ) ) ? $group[1] : ''; + } + $best = $alternatives[0]; + foreach ( $alternatives as $alternative ) { + if ( '' !== $alternative && false !== strpos( $step, $alternative ) && strlen( $alternative ) > strlen( $best ) ) { + $best = $alternative; + } + } + return false !== strpos( $step, $best ) ? $best : $alternatives[0]; + }, + $text, + -1, + $replaced + ); + } while ( $replaced > 0 ); + + return stripslashes( $text ); + } +} diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php new file mode 100644 index 000000000..598ed6a3d --- /dev/null +++ b/tests/tests/TestStepChecker.php @@ -0,0 +1,105 @@ + + */ + private function definitions(): array { + return StepChecker::parse_definitions( self::LISTING ); + } + + public function test_parses_every_definition(): void { + $this->assertCount( 9, $this->definitions() ); + $this->assertSame( 'Given an empty directory', $this->definitions()[0]['label'] ); + } + + /** + * @return array + */ + public static function data_defined_steps(): array { + return [ + 'plain turnip' => [ 'Given an empty directory' ], + 'regex with alternatives' => [ 'And a wp-cli.yml file:' ], + 'turnip optional part' => [ 'Given a WP installation in subdir' ], + 'turnip without it' => [ "Given a WP install in 'foo bar'" ], + 'regex with backticks' => [ 'When I try `wp cli version --debug`' ], + 'optional regex group' => [ 'Then the return code should not be 1' ], + 'turnip placeholder' => [ 'Then the HTTP status code should be 200' ], + 'but keyword' => [ 'But STDERR should be empty' ], + 'star keyword' => [ '* STDOUT should strictly contain:' ], + ]; + } + + /** + * @dataProvider data_defined_steps + */ + #[DataProvider( 'data_defined_steps' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound + public function test_defined_steps_are_not_reported( string $step ): void { + $this->assertSame( [], StepChecker::find_undefined_steps( "Feature: X\n Scenario: Y\n {$step}\n", $this->definitions() ) ); + } + + public function test_reports_undefined_steps_with_their_line(): void { + $feature = implode( + "\n", + [ + 'Feature: X', + ' Scenario Outline: Y', + ' Given an empty directory', + ' Then STDOUT should equal:', + ' """', + ' Then this line is not a step', + ' """', + ' And the exit code should be 0', + ' And the return code should be ', + ' | not | a step |', + ] + ); + + $this->assertSame( + [ + 4 => 'Then STDOUT should equal:', + 8 => 'And the exit code should be 0', + ], + StepChecker::find_undefined_steps( $feature, $this->definitions() ) + ); + } + + /** + * @return array + */ + public static function data_suggestions(): array { + return [ + 'wrong verb' => [ 'Then STDOUT should equal:', 'Then /^(STDOUT|STDERR) should( strictly)? (be|contain|not contain):$/' ], + 'wrong noun' => [ 'And the exit code should be 0', 'Then /^the return code should( not)? be (\d+)$/' ], + 'wrong article' => [ 'Given the empty directory', 'Given an empty directory' ], + 'missing colon' => [ 'Then STDOUT should be JSON containing', 'Then /^STDOUT should be JSON containing:$/' ], + ]; + } + + /** + * @dataProvider data_suggestions + */ + #[DataProvider( 'data_suggestions' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound + public function test_suggests_the_closest_definition_first( string $step, string $expected ): void { + $this->assertSame( $expected, StepChecker::suggest( $step, $this->definitions() )[0] ); + } +} diff --git a/utils/check-feature-steps.php b/utils/check-feature-steps.php new file mode 100644 index 000000000..fedebe84f --- /dev/null +++ b/utils/check-feature-steps.php @@ -0,0 +1,92 @@ +[:] ...] + * + * Expects to run from the package root with BEHAT_PARAMS set the way + * run-behat-tests sets it. Exits with 1 if it finds an undefined step, and + * with 0 if it does not, or if the definitions cannot be listed. + */ + +namespace WP_CLI\Tests; + +use FilesystemIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; + +require_once __DIR__ . '/../src/StepChecker.php'; + +/** + * Lists the feature files that the given Behat path arguments point to. + * + * @param string[] $args Command-line arguments, options included. + * @return string[] + */ +function feature_files_from_args( array $args ) { + $paths = []; + foreach ( $args as $arg ) { + if ( '' === $arg || '-' === $arg[0] ) { + continue; + } + $paths[] = (string) preg_replace( '/:\d+(?:-\d+)?$/', '', $arg ); + } + if ( empty( $paths ) ) { + $paths = [ 'features' ]; + } + + $files = []; + foreach ( $paths as $path ) { + if ( is_file( $path ) && '.feature' === substr( $path, -8 ) ) { + $files[] = $path; + } elseif ( is_dir( $path ) ) { + $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, FilesystemIterator::SKIP_DOTS ) ); + foreach ( $iterator as $file ) { + if ( '.feature' === substr( $file->getFilename(), -8 ) ) { + $files[] = $file->getPathname(); + } + } + } + } + sort( $files ); + + return $files; +} + +/** + * @param string[] $args Command-line arguments, options included. + * @return int Exit status. + */ +function check_feature_steps( array $args ) { + if ( ! is_file( 'vendor/bin/behat' ) ) { + return 0; + } + + $listing = (string) shell_exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors 2>/dev/null' ); + $definitions = StepChecker::parse_definitions( $listing ); + if ( empty( $definitions ) ) { + return 0; + } + + $found = 0; + foreach ( feature_files_from_args( $args ) as $file ) { + foreach ( StepChecker::find_undefined_steps( (string) file_get_contents( $file ), $definitions ) as $line => $step ) { + ++$found; + echo "{$file}:{$line}: No step definition matches \"{$step}\". Closest existing steps:\n"; + foreach ( StepChecker::suggest( $step, $definitions ) as $suggestion ) { + echo " {$suggestion}\n"; + } + } + } + + if ( 0 === $found ) { + return 0; + } + + echo "\n{$found} undefined " . ( 1 === $found ? 'step' : 'steps' ) . ". Use an existing step rather than defining a new one; `composer behat -- --definitions=l` lists them all.\n"; + + return 1; +} + +exit( check_feature_steps( array_slice( $argv, 1 ) ) ); From 94fd83748b58085ff7776ef142a246574bc08fcd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:36:51 +0000 Subject: [PATCH 05/18] Match undefined steps the way Behat does - Read regexes with any delimiter Behat accepts, and convert Turnip patterns like Behat: case-insensitive, with the spaces around an optional word optional too. - Open and close doc strings at lines that start with the delimiter, so ```yaml works. - With file.feature:, check only the selected scenarios and the backgrounds. - Skip the values of options such as --tags when collecting paths, and list the definitions with the --config and --profile of the run. - Leave out --rerun-only like --rerun. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 2 +- src/StepChecker.php | 214 +++++++++++++++++++++++++------- tests/tests/TestStepChecker.php | 59 ++++++++- utils/check-feature-steps.php | 47 +------ 4 files changed, 229 insertions(+), 93 deletions(-) diff --git a/bin/run-behat-tests b/bin/run-behat-tests index 524835eec..a09e53d78 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -331,7 +331,7 @@ BEHAT_TAGS=$(php "$WP_CLI_TESTS_ROOT"/utils/behat-tags.php) CHECK_STEPS=1 for arg in "$@"; do case "$arg" in - -d*|--definitions|--definitions=*|--rerun|--init|-h|--help|--story-syntax) CHECK_STEPS="";; + -d*|--definitions|--definitions=*|--rerun|--rerun-only|--init|-h|--help|--story-syntax) CHECK_STEPS="";; esac done if [ -n "${CHECK_STEPS}" ] && ! php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$@"; then diff --git a/src/StepChecker.php b/src/StepChecker.php index 7a9484641..492321622 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -12,6 +12,89 @@ */ final class StepChecker { + /** + * Behat options that take a value, which may come as the next argument. + */ + const VALUE_OPTIONS = [ '-s', '--suite', '-f', '--format', '-o', '--out', '--format-settings', '--editor-url', '--remove-prefix', '--lang', '--name', '--tags', '--tag-expression', '--role', '--narrative', '-d', '--definitions', '--snippets-type', '--order', '-p', '--profile', '-c', '--config' ]; + + /** + * Splits the given Behat arguments into the paths and the options that pick + * the configuration, which the definitions have to be listed with. + * + * @param string[] $args Command-line arguments, options included. + * @return array{paths: string[], config: string[]} + */ + public static function split_args( array $args ) { + $paths = []; + $config = []; + for ( $i = 0, $count = count( $args ); $i < $count; $i++ ) { + $arg = $args[ $i ]; + if ( '' === $arg ) { + continue; + } + if ( '-' !== $arg[0] ) { + $paths[] = $arg; + continue; + } + $takes_next = in_array( $arg, self::VALUE_OPTIONS, true ) && $i + 1 < $count; + if ( preg_match( '/^(?:-[cp]|--config(?:=|$)|--profile(?:=|$))/', $arg ) ) { + $config[] = $arg; + if ( $takes_next ) { + $config[] = $args[ $i + 1 ]; + } + } + if ( $takes_next ) { + ++$i; + } + } + + return [ + 'paths' => $paths, + 'config' => $config, + ]; + } + + /** + * Lists the feature files that the given Behat paths point to, each with the + * line ranges that select its scenarios, or null for all of them. + * + * @param string[] $paths Paths as Behat takes them, such as `features/a.feature:10`. + * @return array|null> + */ + public static function feature_files( array $paths ) { + if ( empty( $paths ) ) { + $paths = [ 'features' ]; + } + + $files = []; + foreach ( $paths as $path ) { + $range = null; + if ( preg_match( '/^(.+):(\d+)(?:-(\d+|\*))?$/', $path, $matches ) ) { + $path = $matches[1]; + $end = isset( $matches[3] ) ? ( '*' === $matches[3] ? PHP_INT_MAX : (int) $matches[3] ) : (int) $matches[2]; + $range = [ (int) $matches[2], $end ]; + } + + if ( is_file( $path ) && '.feature' === substr( $path, -8 ) ) { + if ( null === $range ) { + $files[ $path ] = null; + } elseif ( ! array_key_exists( $path, $files ) || null !== $files[ $path ] ) { + $files[ $path ][] = $range; + } + } elseif ( is_dir( $path ) ) { + $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path, \FilesystemIterator::SKIP_DOTS ) ); + foreach ( $iterator as $file ) { + if ( '.feature' === substr( $file->getFilename(), -8 ) ) { + $files[ $file->getPathname() ] = null; + } + } + } + } + ksort( $files ); + + return $files; + } + /** * Reads the definitions from the output of `behat --definitions=l`. * @@ -27,7 +110,7 @@ public static function parse_definitions( $listing ) { } $pattern = $matches[2]; - $regex = preg_match( '/^\/.*\/[a-zA-Z]*$/', $pattern ) ? $pattern : self::turnip_to_regex( $pattern ); + $regex = self::is_regex( $pattern ) ? $pattern : self::turnip_to_regex( $pattern ); $definitions[] = [ 'label' => $matches[1] . ' ' . $pattern, @@ -39,50 +122,34 @@ public static function parse_definitions( $listing ) { } /** - * Converts a Turnip pattern, such as `a WP install(ation) in :subdir`, to a regex. + * Whether Behat reads a pattern as a regex rather than as Turnip, by the + * same rule as its RegexPatternPolicy. * * @param string $pattern - * @return string + * @return bool */ - public static function turnip_to_regex( $pattern ) { - $words = []; - - foreach ( explode( ' ', $pattern ) as $word ) { - // `foo/bar` accepts either word, unless the word holds a placeholder. - if ( false !== strpos( $word, '/' ) && false === strpos( $word, ':' ) ) { - $words[] = '(?:' . implode( '|', array_map( [ self::class, 'turnip_word_to_regex' ], explode( '/', $word ) ) ) . ')'; - continue; - } - - $words[] = self::turnip_word_to_regex( $word ); - } - - return '/^' . implode( ' ', $words ) . '$/'; + public static function is_regex( $pattern ) { + return (bool) preg_match( '/^(?:\\{.*\\}|([~\\/#`]).*\1)[imsxADSUXJu]*$/s', $pattern ); } /** - * @param string $word + * Converts a Turnip pattern, such as `a WP install(ation) in :subdir`, to a + * regex the way Behat's TurnipPatternPolicy does, except that a placeholder + * accepts any unquoted word, which can only leave out a false report. + * + * @param string $pattern * @return string */ - private static function turnip_word_to_regex( $word ) { - $regex = ''; - $offset = 0; - - preg_match_all( '/:(\w+)|\(([^)]*)\)/', $word, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); - - foreach ( $matches as $match ) { - $regex .= preg_quote( substr( $word, $offset, $match[0][1] - $offset ), '/' ); - - if ( isset( $match[2] ) && -1 !== $match[2][1] ) { - $regex .= '(?:' . preg_quote( $match[2][0], '/' ) . ')?'; - } else { - $regex .= '(?:"[^"]*"|\'[^\']*\'|[^\s"\']+)'; - } - - $offset = $match[0][1] + strlen( $match[0][0] ); - } - - return $regex . preg_quote( substr( $word, $offset ), '/' ); + public static function turnip_to_regex( $pattern ) { + $regex = preg_quote( $pattern, '/' ); + $regex = (string) preg_replace( '/\\\\:(\w+)/', '(?:"[^"]*"|\'[^\']*\'|[^\s"\']+)', $regex ); + // `(word)` is optional, and so are the spaces around it. + $regex = (string) preg_replace( '/(\s)?\\\\\(([^\\\]+)\\\\\)(\s)?/', '(?:\1)?(?:\2)?(?:\3)?', $regex ); + // `word/other` accepts either word; `\/` is a plain slash. + $regex = (string) preg_replace( '/(\w+)\\\\\/(\w+)/', '(?:\1|\2)', $regex ); + $regex = str_replace( '\\\/', '/', $regex ); + + return '/^' . $regex . '$/iu'; } /** @@ -93,43 +160,94 @@ private static function turnip_word_to_regex( $word ) { * * @param string $contents Contents of the feature file. * @param array $definitions + * @param array|null $lines Line ranges that select scenarios, + * as in `file.feature:10-20`. Only + * the scenarios they touch and the + * backgrounds are checked. Null + * checks the whole file. * @return array Undefined steps, keyed by line number. */ - public static function find_undefined_steps( $contents, array $definitions ) { + public static function find_undefined_steps( $contents, array $definitions, $lines = null ) { $undefined = []; $fence = null; + $scenario = null; // Line of the scenario the steps belong to, 0 for a background. + $starts = []; + $steps = []; foreach ( preg_split( '/\R/', $contents ) ?: [] as $index => $line ) { $trimmed = trim( $line ); - if ( null !== $fence ) { - if ( $trimmed === $fence ) { + // Behat opens and closes a doc string at a line that starts with the delimiter. + if ( preg_match( '/^("""|```)/', $trimmed, $delimiter ) ) { + if ( null === $fence ) { + $fence = $delimiter[1]; + continue; + } + if ( $fence === $delimiter[1] ) { $fence = null; + continue; } - continue; } - if ( '"""' === $trimmed || '```' === $trimmed ) { - $fence = $trimmed; + if ( null !== $fence ) { continue; } - if ( ! preg_match( '/^(?:Given|When|Then|And|But|\*)\s+(.+)$/', $trimmed, $matches ) ) { + if ( preg_match( '/^(?:(Background)|Scenario(?: Outline| Template)?|Example|(Rule|Feature))\s*:/', $trimmed, $header ) ) { + $starts[] = $index + 1; + $scenario = ! empty( $header[1] ) ? 0 : ( ! empty( $header[2] ) ? null : $index + 1 ); continue; } - $step = $matches[1]; + if ( preg_match( '/^(?:Given|When|Then|And|But|\*)\s+(.+)$/', $trimmed, $matches ) ) { + $steps[ $index + 1 ] = [ $matches[1], $trimmed, $scenario ]; + } + } - if ( self::is_defined( $step, $definitions ) || preg_match( '/<[^>\s]+>/', $step ) ) { + foreach ( $steps as $line => $step ) { + list( $text, $trimmed, $scenario ) = $step; + + if ( null !== $lines && ( null === $scenario || ( 0 !== $scenario && ! self::is_selected( $scenario, $starts, $lines ) ) ) ) { continue; } - $undefined[ $index + 1 ] = $trimmed; + if ( self::is_defined( $text, $definitions ) || preg_match( '/<[^>\s]+>/', $text ) ) { + continue; + } + + $undefined[ $line ] = $trimmed; } return $undefined; } + /** + * Whether any of the selected line ranges touches the scenario that starts + * at the given line, its examples included. + * + * @param int $scenario Line of the scenario. + * @param array $starts Lines at which a scenario, background, rule or feature starts. + * @param array $lines Selected line ranges. + * @return bool + */ + private static function is_selected( $scenario, array $starts, array $lines ) { + $end = PHP_INT_MAX; + foreach ( $starts as $start ) { + if ( $start > $scenario ) { + $end = $start - 1; + break; + } + } + + foreach ( $lines as $range ) { + if ( $range[0] <= $end && $range[1] >= $scenario ) { + return true; + } + } + + return false; + } + /** * @param string $step Step text without its keyword. * @param array $definitions @@ -178,7 +296,7 @@ public static function suggest( $step, array $definitions, $count = 3 ) { private static function readable( $label, $step ) { $text = strtolower( (string) preg_replace( '/^(?:Given|When|Then)\s+/', '', $label ) ); - if ( ! preg_match( '/^\/\^?(.*?)\$?\/[a-z]*$/', $text, $matches ) ) { + if ( ! self::is_regex( $text ) || ! preg_match( '/^[{~\/#`]\^?(.*?)\$?[}~\/#`][a-z]*$/is', $text, $matches ) ) { // A Turnip pattern: placeholders read as a value, optional parts as written. return (string) preg_replace( [ '/:\w+/', '/[()]/' ], [ 'x', '' ], $text ); } diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 598ed6a3d..f952e952a 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -18,6 +18,9 @@ class TestStepChecker extends TestCase { default | Then /^(STDOUT|STDERR) should be empty$/ default | Then the HTTP status code should be :code default | Then /^STDOUT should be JSON containing:$/ +default | Given I have (some) apples +default | Given ~^a widget named (\w+)$~i +default | Then {^the cache should( not)? be warm$} LISTING; /** @@ -28,7 +31,7 @@ private function definitions(): array { } public function test_parses_every_definition(): void { - $this->assertCount( 9, $this->definitions() ); + $this->assertCount( 12, $this->definitions() ); $this->assertSame( 'Given an empty directory', $this->definitions()[0]['label'] ); } @@ -46,6 +49,11 @@ public static function data_defined_steps(): array { 'turnip placeholder' => [ 'Then the HTTP status code should be 200' ], 'but keyword' => [ 'But STDERR should be empty' ], 'star keyword' => [ '* STDOUT should strictly contain:' ], + 'turnip other case' => [ 'Given An Empty Directory' ], + 'optional word left out' => [ 'Given I have apples' ], + 'optional word written' => [ 'Given I have some apples' ], + 'tilde regex' => [ 'Given A widget named foo' ], + 'brace regex' => [ 'Then the cache should not be warm' ], ]; } @@ -102,4 +110,53 @@ public static function data_suggestions(): array { public function test_suggests_the_closest_definition_first( string $step, string $expected ): void { $this->assertSame( $expected, StepChecker::suggest( $step, $this->definitions() )[0] ); } + + public function test_doc_strings_may_carry_a_content_type(): void { + $feature = implode( + "\n", + [ + 'Feature: X', + ' Scenario: Y', + ' Given a wp-cli.yml file:', + ' ```yaml', + ' Then this line is not a step', + ' ```', + ' And the exit code should be 0', + ] + ); + + $this->assertSame( [ 7 => 'And the exit code should be 0' ], StepChecker::find_undefined_steps( $feature, $this->definitions() ) ); + } + + public function test_selected_lines_check_only_their_scenarios_and_the_background(): void { + $feature = implode( + "\n", + [ + 'Feature: X', // 1 + ' Background:', // 2 + ' Given no such step', // 3 + '', // 4 + ' Scenario: Selected', // 5 + ' Given another missing step', // 6 + '', // 7 + ' @tag', // 8 + ' Scenario: Not selected', // 9 + ' Given a third missing step', // 10 + ] + ); + + $this->assertSame( [ 3, 6, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions() ) ) ); + $this->assertSame( [ 3, 6 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 5, 5 ] ] ) ) ); + $this->assertSame( [ 3, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 9, PHP_INT_MAX ] ] ) ) ); + } + + public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { + $this->assertSame( + [ + 'paths' => [ 'features/a.feature:10' ], + 'config' => [ '--profile', 'ci', '-cbehat.yml' ], + ], + StepChecker::split_args( [ '--tags', '@smoke', '--profile', 'ci', '-cbehat.yml', '--format=progress', 'features/a.feature:10' ] ) + ); + } } diff --git a/utils/check-feature-steps.php b/utils/check-feature-steps.php index fedebe84f..19a3fc9df 100644 --- a/utils/check-feature-steps.php +++ b/utils/check-feature-steps.php @@ -12,48 +12,8 @@ namespace WP_CLI\Tests; -use FilesystemIterator; -use RecursiveDirectoryIterator; -use RecursiveIteratorIterator; - require_once __DIR__ . '/../src/StepChecker.php'; -/** - * Lists the feature files that the given Behat path arguments point to. - * - * @param string[] $args Command-line arguments, options included. - * @return string[] - */ -function feature_files_from_args( array $args ) { - $paths = []; - foreach ( $args as $arg ) { - if ( '' === $arg || '-' === $arg[0] ) { - continue; - } - $paths[] = (string) preg_replace( '/:\d+(?:-\d+)?$/', '', $arg ); - } - if ( empty( $paths ) ) { - $paths = [ 'features' ]; - } - - $files = []; - foreach ( $paths as $path ) { - if ( is_file( $path ) && '.feature' === substr( $path, -8 ) ) { - $files[] = $path; - } elseif ( is_dir( $path ) ) { - $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, FilesystemIterator::SKIP_DOTS ) ); - foreach ( $iterator as $file ) { - if ( '.feature' === substr( $file->getFilename(), -8 ) ) { - $files[] = $file->getPathname(); - } - } - } - } - sort( $files ); - - return $files; -} - /** * @param string[] $args Command-line arguments, options included. * @return int Exit status. @@ -63,15 +23,16 @@ function check_feature_steps( array $args ) { return 0; } - $listing = (string) shell_exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors 2>/dev/null' ); + $args = StepChecker::split_args( $args ); + $listing = (string) shell_exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors ' . implode( ' ', array_map( 'escapeshellarg', $args['config'] ) ) . ' 2>/dev/null' ); $definitions = StepChecker::parse_definitions( $listing ); if ( empty( $definitions ) ) { return 0; } $found = 0; - foreach ( feature_files_from_args( $args ) as $file ) { - foreach ( StepChecker::find_undefined_steps( (string) file_get_contents( $file ), $definitions ) as $line => $step ) { + foreach ( StepChecker::feature_files( $args['paths'] ) as $file => $lines ) { + foreach ( StepChecker::find_undefined_steps( (string) file_get_contents( $file ), $definitions, $lines ) as $line => $step ) { ++$found; echo "{$file}:{$line}: No step definition matches \"{$step}\". Closest existing steps:\n"; foreach ( StepChecker::suggest( $step, $definitions ) as $suggestion ) { From f77fe79cc0cc44508579641808c07fc086c99605 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:41:26 +0000 Subject: [PATCH 06/18] Test which feature files and lines the step check reads Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- tests/tests/TestStepChecker.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index f952e952a..03a049aee 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -159,4 +159,30 @@ public function test_option_values_are_not_paths_and_the_configuration_is_kept() StepChecker::split_args( [ '--tags', '@smoke', '--profile', 'ci', '-cbehat.yml', '--format=progress', 'features/a.feature:10' ] ) ); } + + public function test_feature_files_keep_the_selected_lines(): void { + $dir = sys_get_temp_dir() . '/wp-cli-step-checker-' . uniqid(); + mkdir( $dir . '/sub', 0777, true ); + touch( $dir . '/a.feature' ); + touch( $dir . '/sub/b.feature' ); + touch( $dir . '/sub/notes.txt' ); + + try { + $this->assertSame( + [ + $dir . '/a.feature' => [ [ 10, 10 ], [ 20, 30 ] ], + $dir . '/sub/b.feature' => null, + ], + StepChecker::feature_files( [ $dir . '/a.feature:10', $dir . '/a.feature:20-30', $dir . '/sub', $dir . '/missing.feature' ] ) + ); + $this->assertSame( [ $dir . '/a.feature' => null ], StepChecker::feature_files( [ $dir . '/a.feature:5-*', $dir . '/a.feature' ] ) ); + $this->assertSame( [ [ 5, PHP_INT_MAX ] ], StepChecker::feature_files( [ $dir . '/a.feature:5-*' ] )[ $dir . '/a.feature' ] ); + } finally { + unlink( $dir . '/a.feature' ); + unlink( $dir . '/sub/b.feature' ); + unlink( $dir . '/sub/notes.txt' ); + rmdir( $dir . '/sub' ); + rmdir( $dir ); + } + } } From 3e4ea7377d40caf6ff06e68c6506472864f7da5b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:43:39 +0000 Subject: [PATCH 07/18] Expect the directory separator Windows uses for found feature files Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- tests/tests/TestStepChecker.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 03a049aee..e254b610f 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -171,7 +171,7 @@ public function test_feature_files_keep_the_selected_lines(): void { $this->assertSame( [ $dir . '/a.feature' => [ [ 10, 10 ], [ 20, 30 ] ], - $dir . '/sub/b.feature' => null, + $dir . '/sub' . DIRECTORY_SEPARATOR . 'b.feature' => null, ], StepChecker::feature_files( [ $dir . '/a.feature:10', $dir . '/a.feature:20-30', $dir . '/sub', $dir . '/missing.feature' ] ) ); From cef368ba70adb0eae3247dd724460c4c3ba577ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:43:50 +0000 Subject: [PATCH 08/18] Align the array arrows in the feature files test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- tests/tests/TestStepChecker.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index e254b610f..1416e9872 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -170,7 +170,7 @@ public function test_feature_files_keep_the_selected_lines(): void { try { $this->assertSame( [ - $dir . '/a.feature' => [ [ 10, 10 ], [ 20, 30 ] ], + $dir . '/a.feature' => [ [ 10, 10 ], [ 20, 30 ] ], $dir . '/sub' . DIRECTORY_SEPARATOR . 'b.feature' => null, ], StepChecker::feature_files( [ $dir . '/a.feature:10', $dir . '/a.feature:20-30', $dir . '/sub', $dir . '/missing.feature' ] ) From 33bc5e18eb88078b76776f782dc76dcc5b11230e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:55:36 +0000 Subject: [PATCH 09/18] Select the scenarios to check with Behat's own parser and filters The step check now parses feature files with the Gherkin parser of the Behat installation and selects scenarios with its line, tag and name filters, so it checks exactly what Behat would run: the generated environment tags and --tags/--name apply, and outline steps are checked per example. Runs that select scenarios in ways it cannot follow (tag expressions, role or narrative filters, or a profile, suite or config file without paths) skip the check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 2 +- src/StepChecker.php | 204 +++++++++++++++++++------------- tests/tests/TestStepChecker.php | 74 +++++++++++- utils/check-feature-steps.php | 17 ++- 4 files changed, 207 insertions(+), 90 deletions(-) diff --git a/bin/run-behat-tests b/bin/run-behat-tests index a09e53d78..981b2693c 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -334,7 +334,7 @@ for arg in "$@"; do -d*|--definitions|--definitions=*|--rerun|--rerun-only|--init|-h|--help|--story-syntax) CHECK_STEPS="";; esac done -if [ -n "${CHECK_STEPS}" ] && ! php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$@"; then +if [ -n "${CHECK_STEPS}" ] && ! php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$BEHAT_TAGS" "$@"; then exit 1 fi diff --git a/src/StepChecker.php b/src/StepChecker.php index 492321622..46d05db5f 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -2,6 +2,17 @@ namespace WP_CLI\Tests; +use Behat\Gherkin\Filter\LineFilter; +use Behat\Gherkin\Filter\LineRangeFilter; +use Behat\Gherkin\Filter\NameFilter; +use Behat\Gherkin\Filter\TagFilter; +use Behat\Gherkin\Keywords\CachedArrayKeywords; +use Behat\Gherkin\Lexer; +use Behat\Gherkin\Node\FeatureNode; +use Behat\Gherkin\Node\OutlineNode; +use Behat\Gherkin\Node\ScenarioInterface; +use Behat\Gherkin\Parser; + /** * Finds steps in feature files that no step definition matches, and suggests * the closest existing ones. @@ -18,40 +29,67 @@ final class StepChecker { const VALUE_OPTIONS = [ '-s', '--suite', '-f', '--format', '-o', '--out', '--format-settings', '--editor-url', '--remove-prefix', '--lang', '--name', '--tags', '--tag-expression', '--role', '--narrative', '-d', '--definitions', '--snippets-type', '--order', '-p', '--profile', '-c', '--config' ]; /** - * Splits the given Behat arguments into the paths and the options that pick - * the configuration, which the definitions have to be listed with. + * Splits the given Behat arguments into the paths, the filters that select + * scenarios, and the options that pick the configuration, which the + * definitions have to be listed with. + * + * `skip` is set when the run selects its scenarios in a way this cannot + * follow: with a tag expression, a role or narrative filter, or a profile, + * suite or configuration file that may have paths of its own. * * @param string[] $args Command-line arguments, options included. - * @return array{paths: string[], config: string[]} + * @return array{paths: string[], config: string[], tags: string[], names: string[], skip: bool} */ public static function split_args( array $args ) { - $paths = []; - $config = []; + $result = [ + 'paths' => [], + 'config' => [], + 'tags' => [], + 'names' => [], + 'skip' => false, + ]; + $selects_config = false; + for ( $i = 0, $count = count( $args ); $i < $count; $i++ ) { $arg = $args[ $i ]; if ( '' === $arg ) { continue; } if ( '-' !== $arg[0] ) { - $paths[] = $arg; + $result['paths'][] = $arg; continue; } + $takes_next = in_array( $arg, self::VALUE_OPTIONS, true ) && $i + 1 < $count; - if ( preg_match( '/^(?:-[cp]|--config(?:=|$)|--profile(?:=|$))/', $arg ) ) { - $config[] = $arg; - if ( $takes_next ) { - $config[] = $args[ $i + 1 ]; + $value = $takes_next ? $args[ $i + 1 ] : (string) substr( $arg, (int) strpos( $arg, '=' ) + 1 ); + $option = $takes_next || false === strpos( $arg, '=' ) ? $arg : substr( $arg, 0, (int) strpos( $arg, '=' ) ); + + if ( preg_match( '/^(?:-[cps]|--config(?:=|$)|--profile(?:=|$)|--suite(?:=|$))/', $arg ) ) { + $selects_config = true; + if ( ! preg_match( '/^(?:-s|--suite)/', $arg ) ) { + $result['config'][] = $arg; + if ( $takes_next ) { + $result['config'][] = $args[ $i + 1 ]; + } } + } elseif ( '--tags' === $option ) { + $result['tags'][] = $value; + } elseif ( '--name' === $option ) { + $result['names'][] = $value; + } elseif ( in_array( $option, [ '--tag-expression', '--role', '--narrative' ], true ) ) { + $result['skip'] = true; } + if ( $takes_next ) { ++$i; } } - return [ - 'paths' => $paths, - 'config' => $config, - ]; + if ( $selects_config && empty( $result['paths'] ) ) { + $result['skip'] = true; + } + + return $result; } /** @@ -153,99 +191,103 @@ public static function turnip_to_regex( $pattern ) { } /** - * Lists the steps of a feature file that no definition matches. + * Lists the steps of a feature file that no definition matches, in the + * scenarios that Behat would run with the same paths and filters. * - * Steps of a scenario outline that hold a `` are only - * checked once the placeholder is filled in, so they are left out. + * The scenarios are selected with Behat's own Gherkin parser and filters, + * and the steps of a scenario outline are checked once per example, with + * its values filled in. * * @param string $contents Contents of the feature file. * @param array $definitions * @param array|null $lines Line ranges that select scenarios, - * as in `file.feature:10-20`. Only - * the scenarios they touch and the - * backgrounds are checked. Null - * checks the whole file. - * @return array Undefined steps, keyed by line number. + * as in `file.feature:10-20`, or + * null for all of them. + * @param string[] $tags Values of `--tags`, all of which + * have to match. + * @param string[] $names Values of `--name`, all of which + * have to match. + * @return array Undefined steps, with their keyword, keyed by line number. */ - public static function find_undefined_steps( $contents, array $definitions, $lines = null ) { - $undefined = []; - $fence = null; - $scenario = null; // Line of the scenario the steps belong to, 0 for a background. - $starts = []; - $steps = []; - - foreach ( preg_split( '/\R/', $contents ) ?: [] as $index => $line ) { - $trimmed = trim( $line ); - - // Behat opens and closes a doc string at a line that starts with the delimiter. - if ( preg_match( '/^("""|```)/', $trimmed, $delimiter ) ) { - if ( null === $fence ) { - $fence = $delimiter[1]; - continue; - } - if ( $fence === $delimiter[1] ) { - $fence = null; - continue; - } - } + public static function find_undefined_steps( $contents, array $definitions, $lines = null, array $tags = [], array $names = [] ) { + try { + $feature = self::parser()->parse( $contents ); + } catch ( \Exception $exception ) { + // Behat reports a feature file it cannot parse itself. + return []; + } - if ( null !== $fence ) { - continue; - } + if ( ! $feature instanceof FeatureNode ) { + return []; + } - if ( preg_match( '/^(?:(Background)|Scenario(?: Outline| Template)?|Example|(Rule|Feature))\s*:/', $trimmed, $header ) ) { - $starts[] = $index + 1; - $scenario = ! empty( $header[1] ) ? 0 : ( ! empty( $header[2] ) ? null : $index + 1 ); - continue; - } + $filters = []; + foreach ( $tags as $tag ) { + $filters[] = new TagFilter( $tag ); + } + foreach ( $names as $name ) { + $filters[] = new NameFilter( $name ); + } + foreach ( $filters as $filter ) { + $feature = $filter->filterFeature( $feature ); + } - if ( preg_match( '/^(?:Given|When|Then|And|But|\*)\s+(.+)$/', $trimmed, $matches ) ) { - $steps[ $index + 1 ] = [ $matches[1], $trimmed, $scenario ]; + // Each path is a run of its own, so the scenarios its lines select add up. + $scenarios = []; + $selected = null === $lines ? [ $feature ] : []; + foreach ( (array) $lines as $range ) { + $filter = $range[0] === $range[1] ? new LineFilter( $range[0] ) : new LineRangeFilter( $range[0], PHP_INT_MAX === $range[1] ? '*' : $range[1] ); + $selected[] = $filter->filterFeature( $feature ); + } + foreach ( $selected as $filtered ) { + // Newer versions of behat/gherkin deprecate getScenarios() for this. + $children = is_callable( [ $filtered, 'getExecutableChildren' ] ) ? $filtered->getExecutableChildren() : call_user_func( [ $filtered, 'getScenarios' ] ); + foreach ( $children as $scenario ) { + if ( $scenario instanceof ScenarioInterface ) { + $scenarios[ $scenario->getLine() ] = $scenario; + } } } - foreach ( $steps as $line => $step ) { - list( $text, $trimmed, $scenario ) = $step; + if ( empty( $scenarios ) ) { + return []; + } - if ( null !== $lines && ( null === $scenario || ( 0 !== $scenario && ! self::is_selected( $scenario, $starts, $lines ) ) ) ) { - continue; + $steps = $feature->hasBackground() ? $feature->getBackground()->getSteps() : []; + foreach ( $scenarios as $scenario ) { + if ( $scenario instanceof OutlineNode ) { + foreach ( $scenario->getExamples() as $example ) { + $steps = array_merge( $steps, $example->getSteps() ); + } + } else { + $steps = array_merge( $steps, $scenario->getSteps() ); } + } - if ( self::is_defined( $text, $definitions ) || preg_match( '/<[^>\s]+>/', $text ) ) { - continue; + $undefined = []; + foreach ( $steps as $step ) { + if ( ! isset( $undefined[ $step->getLine() ] ) && ! self::is_defined( $step->getText(), $definitions ) ) { + $undefined[ $step->getLine() ] = $step->getKeyword() . ' ' . $step->getText(); } - - $undefined[ $line ] = $trimmed; } + ksort( $undefined ); return $undefined; } /** - * Whether any of the selected line ranges touches the scenario that starts - * at the given line, its examples included. + * The Gherkin parser of the Behat installation. * - * @param int $scenario Line of the scenario. - * @param array $starts Lines at which a scenario, background, rule or feature starts. - * @param array $lines Selected line ranges. - * @return bool + * @return Parser */ - private static function is_selected( $scenario, array $starts, array $lines ) { - $end = PHP_INT_MAX; - foreach ( $starts as $start ) { - if ( $start > $scenario ) { - $end = $start - 1; - break; - } + private static function parser() { + // Older versions of behat/gherkin ship the keywords in their root folder, newer ones still do. + $dir = dirname( (string) ( new \ReflectionClass( CachedArrayKeywords::class ) )->getFileName() ); + while ( ! file_exists( $dir . '/i18n.php' ) && dirname( $dir ) !== $dir ) { + $dir = dirname( $dir ); } - foreach ( $lines as $range ) { - if ( $range[0] <= $end && $range[1] >= $scenario ) { - return true; - } - } - - return false; + return new Parser( new Lexer( new CachedArrayKeywords( $dir . '/i18n.php' ) ) ); } /** diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 1416e9872..3ec46cffc 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -70,15 +70,13 @@ public function test_reports_undefined_steps_with_their_line(): void { "\n", [ 'Feature: X', - ' Scenario Outline: Y', + ' Scenario: Y', ' Given an empty directory', ' Then STDOUT should equal:', ' """', ' Then this line is not a step', ' """', ' And the exit code should be 0', - ' And the return code should be ', - ' | not | a step |', ] ); @@ -91,6 +89,46 @@ public function test_reports_undefined_steps_with_their_line(): void { ); } + public function test_outline_steps_are_checked_per_example(): void { + $feature = implode( + "\n", + [ + 'Feature: X', + ' Scenario Outline: Y', + ' Then the return code should be ', + ' And the code should be 0', + '', + ' Examples:', + ' | code | noun |', + ' | 0 | return |', + ' | 1 | exit |', + ] + ); + + $this->assertSame( [ 4 => 'And the exit code should be 0' ], StepChecker::find_undefined_steps( $feature, $this->definitions() ) ); + } + + public function test_tags_and_names_select_scenarios_like_behat(): void { + $feature = implode( + "\n", + [ + 'Feature: X', + '', + ' @wip', + ' Scenario: Unfinished', + ' Given a step that does not exist yet', + '', + ' Scenario: Finished', + ' Given another missing step', + ] + ); + + $this->assertSame( [ 5, 8 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions() ) ) ); + $this->assertSame( [ 8 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), null, [ '~@wip&&~@broken' ] ) ) ); + $this->assertSame( [], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), null, [ '~@wip', '@wip' ] ) ) ); + $this->assertSame( [ 5 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), null, [], [ 'Unfinished' ] ) ) ); + } + /** * @return array */ @@ -148,6 +186,8 @@ public function test_selected_lines_check_only_their_scenarios_and_the_backgroun $this->assertSame( [ 3, 6, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions() ) ) ); $this->assertSame( [ 3, 6 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 5, 5 ] ] ) ) ); $this->assertSame( [ 3, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 9, PHP_INT_MAX ] ] ) ) ); + $this->assertSame( [ 3, 6, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 5, 5 ], [ 9, 9 ] ] ) ) ); + $this->assertSame( [], StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 6, 6 ] ] ) ); } public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { @@ -155,11 +195,37 @@ public function test_option_values_are_not_paths_and_the_configuration_is_kept() [ 'paths' => [ 'features/a.feature:10' ], 'config' => [ '--profile', 'ci', '-cbehat.yml' ], + 'tags' => [ '~@broken', '@smoke' ], + 'names' => [ 'install' ], + 'skip' => false, ], - StepChecker::split_args( [ '--tags', '@smoke', '--profile', 'ci', '-cbehat.yml', '--format=progress', 'features/a.feature:10' ] ) + StepChecker::split_args( [ '--tags=~@broken', '--tags', '@smoke', '--name=install', '--profile', 'ci', '-cbehat.yml', '--format=progress', 'features/a.feature:10' ] ) ); } + /** + * @return array + */ + public static function data_unfollowed_selections(): array { + return [ + 'tag expression' => [ [ '--tag-expression', 'not @wip' ] ], + 'role' => [ [ '--role=admin', 'features/a.feature' ] ], + 'profile without paths' => [ [ '-p', 'ci' ] ], + 'suite without paths' => [ [ '--suite=core' ] ], + 'config file without paths' => [ [ '--config=custom.yml' ] ], + ]; + } + + /** + * @dataProvider data_unfollowed_selections + * + * @param string[] $args + */ + #[DataProvider( 'data_unfollowed_selections' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound + public function test_selections_it_cannot_follow_skip_the_check( array $args ): void { + $this->assertTrue( StepChecker::split_args( $args )['skip'] ); + } + public function test_feature_files_keep_the_selected_lines(): void { $dir = sys_get_temp_dir() . '/wp-cli-step-checker-' . uniqid(); mkdir( $dir . '/sub', 0777, true ); diff --git a/utils/check-feature-steps.php b/utils/check-feature-steps.php index 19a3fc9df..c4faf36f7 100644 --- a/utils/check-feature-steps.php +++ b/utils/check-feature-steps.php @@ -3,7 +3,7 @@ * Reports steps in feature files that no step definition matches, with the * closest existing steps, before any scenario has to be set up. * - * Usage: php check-feature-steps.php [[:] ...] + * Usage: php check-feature-steps.php [ ...] * * Expects to run from the package root with BEHAT_PARAMS set the way * run-behat-tests sets it. Exits with 1 if it finds an undefined step, and @@ -12,7 +12,12 @@ namespace WP_CLI\Tests; -require_once __DIR__ . '/../src/StepChecker.php'; +if ( is_file( 'vendor/autoload.php' ) ) { + require_once 'vendor/autoload.php'; +} +if ( ! class_exists( StepChecker::class ) ) { + require_once __DIR__ . '/../src/StepChecker.php'; +} /** * @param string[] $args Command-line arguments, options included. @@ -23,7 +28,11 @@ function check_feature_steps( array $args ) { return 0; } - $args = StepChecker::split_args( $args ); + $args = StepChecker::split_args( $args ); + if ( $args['skip'] ) { + return 0; + } + $listing = (string) shell_exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors ' . implode( ' ', array_map( 'escapeshellarg', $args['config'] ) ) . ' 2>/dev/null' ); $definitions = StepChecker::parse_definitions( $listing ); if ( empty( $definitions ) ) { @@ -32,7 +41,7 @@ function check_feature_steps( array $args ) { $found = 0; foreach ( StepChecker::feature_files( $args['paths'] ) as $file => $lines ) { - foreach ( StepChecker::find_undefined_steps( (string) file_get_contents( $file ), $definitions, $lines ) as $line => $step ) { + foreach ( StepChecker::find_undefined_steps( (string) file_get_contents( $file ), $definitions, $lines, $args['tags'], $args['names'] ) as $line => $step ) { ++$found; echo "{$file}:{$line}: No step definition matches \"{$step}\". Closest existing steps:\n"; foreach ( StepChecker::suggest( $step, $definitions ) as $suggestion ) { From 698bb193d211769ea9b8295cfc9ee9ed94b40020 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:59:31 +0000 Subject: [PATCH 10/18] Check the steps of rules, and a rule's background only for its scenarios The checker skipped the scenarios inside a Rule, and parsed only in the legacy Gherkin mode, which cannot read rules at all. It now parses in the mode the installed Behat uses by default, trying the other modes if that fails, and checks a rule's background only when one of that rule's scenarios is selected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 76 +++++++++++++++++++++++++++------ tests/tests/TestStepChecker.php | 33 ++++++++++++++ 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index 46d05db5f..be9235a06 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -210,14 +210,8 @@ public static function turnip_to_regex( $pattern ) { * @return array Undefined steps, with their keyword, keyed by line number. */ public static function find_undefined_steps( $contents, array $definitions, $lines = null, array $tags = [], array $names = [] ) { - try { - $feature = self::parser()->parse( $contents ); - } catch ( \Exception $exception ) { - // Behat reports a feature file it cannot parse itself. - return []; - } - - if ( ! $feature instanceof FeatureNode ) { + $feature = self::parse( $contents ); + if ( null === $feature ) { return []; } @@ -239,12 +233,22 @@ public static function find_undefined_steps( $contents, array $definitions, $lin $filter = $range[0] === $range[1] ? new LineFilter( $range[0] ) : new LineRangeFilter( $range[0], PHP_INT_MAX === $range[1] ? '*' : $range[1] ); $selected[] = $filter->filterFeature( $feature ); } + // The background of a rule only applies to the scenarios of that rule. + $backgrounds = []; foreach ( $selected as $filtered ) { // Newer versions of behat/gherkin deprecate getScenarios() for this. $children = is_callable( [ $filtered, 'getExecutableChildren' ] ) ? $filtered->getExecutableChildren() : call_user_func( [ $filtered, 'getScenarios' ] ); - foreach ( $children as $scenario ) { - if ( $scenario instanceof ScenarioInterface ) { - $scenarios[ $scenario->getLine() ] = $scenario; + foreach ( $children as $child ) { + if ( $child instanceof ScenarioInterface ) { + $scenarios[ $child->getLine() ] = $child; + } elseif ( is_object( $child ) && is_callable( [ $child, 'getExecutableChildren' ] ) ) { + $rule_scenarios = $child->getExecutableChildren(); + foreach ( $rule_scenarios as $scenario ) { + $scenarios[ $scenario->getLine() ] = $scenario; + } + if ( ! empty( $rule_scenarios ) && is_callable( [ $child, 'getBackground' ] ) && null !== $child->getBackground() ) { + $backgrounds[ $child->getBackground()->getLine() ] = $child->getBackground(); + } } } } @@ -254,6 +258,9 @@ public static function find_undefined_steps( $contents, array $definitions, $lin } $steps = $feature->hasBackground() ? $feature->getBackground()->getSteps() : []; + foreach ( $backgrounds as $background ) { + $steps = array_merge( $steps, $background->getSteps() ); + } foreach ( $scenarios as $scenario ) { if ( $scenario instanceof OutlineNode ) { foreach ( $scenario->getExamples() as $example ) { @@ -267,7 +274,7 @@ public static function find_undefined_steps( $contents, array $definitions, $lin $undefined = []; foreach ( $steps as $step ) { if ( ! isset( $undefined[ $step->getLine() ] ) && ! self::is_defined( $step->getText(), $definitions ) ) { - $undefined[ $step->getLine() ] = $step->getKeyword() . ' ' . $step->getText(); + $undefined[ $step->getLine() ] = rtrim( $step->getKeyword() ) . ' ' . $step->getText(); } } ksort( $undefined ); @@ -275,6 +282,51 @@ public static function find_undefined_steps( $contents, array $definitions, $lin return $undefined; } + /** + * Parses a feature file as the Behat installation does by default. + * + * A project can configure another Gherkin compatibility mode, so the + * other modes are tried when the default one cannot parse the file. + * + * @param string $contents Contents of the feature file. + * @return FeatureNode|null Null if no mode can parse the file, which + * Behat then reports itself. + */ + private static function parse( $contents ) { + $parser = self::parser(); + $modes = [ null ]; + $enum = 'Behat\\Gherkin\\GherkinCompatibilityMode'; + if ( class_exists( $enum ) && method_exists( $parser, 'setGherkinCompatibilityMode' ) ) { + // Newest first. Behat 4 parses like recent cucumber/gherkin versions by default, Behat 3 in the legacy mode. + $modes = array_reverse( call_user_func( [ $enum, 'cases' ] ) ); + $legacy = constant( $enum . '::LEGACY' ); + $behat = class_exists( '\\Composer\\InstalledVersions' ) && \Composer\InstalledVersions::isInstalled( 'behat/behat' ) ? (string) \Composer\InstalledVersions::getVersion( 'behat/behat' ) : ''; + if ( version_compare( $behat, '4', '<' ) ) { + $others = array_filter( + $modes, + function ( $mode ) use ( $legacy ) { + return $mode !== $legacy; + } + ); + $modes = array_merge( [ $legacy ], $others ); + } + } + + foreach ( $modes as $mode ) { + if ( null !== $mode ) { + $parser->setGherkinCompatibilityMode( $mode ); + } + try { + $feature = $parser->parse( $contents ); + } catch ( \Exception $exception ) { + continue; + } + return $feature instanceof FeatureNode ? $feature : null; + } + + return null; + } + /** * The Gherkin parser of the Behat installation. * diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 3ec46cffc..d76642efa 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -190,6 +190,39 @@ public function test_selected_lines_check_only_their_scenarios_and_the_backgroun $this->assertSame( [], StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 6, 6 ] ] ) ); } + public function test_a_rule_background_applies_only_to_the_scenarios_of_its_rule(): void { + if ( ! class_exists( 'Behat\\Gherkin\\GherkinCompatibilityMode' ) ) { + $this->markTestSkipped( 'This version of behat/gherkin cannot parse rules.' ); + } + + $feature = implode( + "\n", + [ + 'Feature: X', + '', + ' Rule: First', + ' Background:', + ' Given a step that does not exist yet', + '', + ' Scenario: In the first rule', + ' Given I have apples', + '', + ' Rule: Second', + ' Scenario: In the second rule', + ' Given another missing step', + ] + ); + + $expected = [ + 5 => 'Given a step that does not exist yet', + 12 => 'Given another missing step', + ]; + $this->assertSame( $expected, StepChecker::find_undefined_steps( $feature, $this->definitions() ) ); + $this->assertSame( [ 12 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 11, 11 ] ] ) ) ); + $this->assertSame( [ 12 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), null, [], [ 'second' ] ) ) ); + $this->assertSame( [ 5 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 7, 7 ] ] ) ) ); + } + public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { $this->assertSame( [ From 725cec1639f77a2aa9de53fd9619f6f089718c61 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:08:50 +0000 Subject: [PATCH 11/18] Skip the step check when the Behat configuration may filter scenarios Behat applies the filters of the configuration on top of the ones on the command line, so a scenario a suite filter excludes could still block the run with an undefined step. The checker does not follow those filters, so it now steps aside whenever the configuration files or BEHAT_PARAMS mention filters, or import other files that might. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 46 +++++++++++++++++++++++++++++++++ tests/tests/TestStepChecker.php | 21 +++++++++++++++ utils/check-feature-steps.php | 2 +- 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index be9235a06..88363463b 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -92,6 +92,52 @@ public static function split_args( array $args ) { return $result; } + /** + * Whether the Behat configuration might filter scenarios of its own. + * + * Behat applies the filters of the configuration on top of the ones on + * the command line, which the checker does not follow. It treats any + * mention of filters, or any import that might hold them, in the + * configuration files or in BEHAT_PARAMS as a filter. + * + * @param string[] $config Configuration options from split_args(). + * @param string $dir Directory Behat runs in. + * @param string $behat_params Value of BEHAT_PARAMS. + * @return bool + */ + public static function config_may_filter( array $config, $dir, $behat_params ) { + if ( false !== stripos( $behat_params, 'filter' ) ) { + return true; + } + + $files = []; + for ( $i = 0, $count = count( $config ); $i < $count; $i++ ) { + if ( in_array( $config[ $i ], [ '-c', '--config' ], true ) && $i + 1 < $count ) { + $files[] = $config[ ++$i ]; + } elseif ( 0 === strpos( $config[ $i ], '--config=' ) ) { + $files[] = substr( $config[ $i ], strlen( '--config=' ) ); + } elseif ( preg_match( '/^-c(.+)$/', $config[ $i ], $matches ) ) { + $files[] = $matches[1]; + } + } + if ( empty( $files ) ) { + foreach ( [ '', 'config/' ] as $folder ) { + foreach ( [ 'behat.php', 'behat.dist.php', 'behat.yaml', 'behat.yml', 'behat.yaml.dist', 'behat.yml.dist', 'behat.dist.yaml', 'behat.dist.yml' ] as $name ) { + $files[] = $folder . $name; + } + } + } + + foreach ( $files as $file ) { + $path = preg_match( '#^(?:/|[A-Za-z]:[\\\\/])#', $file ) ? $file : $dir . '/' . $file; + if ( is_file( $path ) && preg_match( '/filter|import/i', (string) file_get_contents( $path ) ) ) { + return true; + } + } + + return false; + } + /** * Lists the feature files that the given Behat paths point to, each with the * line ranges that select its scenarios, or null for all of them. diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index d76642efa..954daf6b6 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -259,6 +259,27 @@ public function test_selections_it_cannot_follow_skip_the_check( array $args ): $this->assertTrue( StepChecker::split_args( $args )['skip'] ); } + public function test_filters_in_the_configuration_skip_the_check(): void { + $dir = sys_get_temp_dir() . '/wp-cli-step-checker-config-' . uniqid(); + mkdir( $dir ); + file_put_contents( $dir . '/behat.yml', "default:\n suites:\n default:\n paths:\n - features\n" ); + file_put_contents( $dir . '/filtered.yml', "default:\n suites:\n default:\n filters:\n tags: '~@broken'\n" ); + + try { + $this->assertFalse( StepChecker::config_may_filter( [], $dir, '' ) ); + $this->assertFalse( StepChecker::config_may_filter( [ '-p', 'default' ], $dir, '{"suites":{"default":{"paths":["features"]}}}' ) ); + $this->assertTrue( StepChecker::config_may_filter( [], $dir, '{"suites":{"default":{"filters":{"tags":"~@broken"}}}}' ) ); + $this->assertTrue( StepChecker::config_may_filter( [ '-c', 'filtered.yml' ], $dir, '' ) ); + $this->assertTrue( StepChecker::config_may_filter( [ '--config=' . $dir . '/filtered.yml' ], '/nonexistent', '' ) ); + + file_put_contents( $dir . '/behat.yml', "imports:\n - filtered.yml\n" ); + $this->assertTrue( StepChecker::config_may_filter( [], $dir, '' ) ); + } finally { + array_map( 'unlink', (array) glob( $dir . '/*' ) ); + rmdir( $dir ); + } + } + public function test_feature_files_keep_the_selected_lines(): void { $dir = sys_get_temp_dir() . '/wp-cli-step-checker-' . uniqid(); mkdir( $dir . '/sub', 0777, true ); diff --git a/utils/check-feature-steps.php b/utils/check-feature-steps.php index c4faf36f7..37cf936dc 100644 --- a/utils/check-feature-steps.php +++ b/utils/check-feature-steps.php @@ -29,7 +29,7 @@ function check_feature_steps( array $args ) { } $args = StepChecker::split_args( $args ); - if ( $args['skip'] ) { + if ( $args['skip'] || StepChecker::config_may_filter( $args['config'], (string) getcwd(), (string) getenv( 'BEHAT_PARAMS' ) ) ) { return 0; } From 3545042d83060e25bc0d61cce8eeb34162c424d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:21:35 +0000 Subject: [PATCH 12/18] Fill in outline examples in the steps of a rule's background Behat adds the background of a rule to each of its scenarios before an outline fills in its examples, so a placeholder in such a background takes the values of every example. The checker checked it literally. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 12 +++++++----- tests/tests/TestStepChecker.php | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index 88363463b..c3b7a6cb0 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -288,13 +288,15 @@ public static function find_undefined_steps( $contents, array $definitions, $lin if ( $child instanceof ScenarioInterface ) { $scenarios[ $child->getLine() ] = $child; } elseif ( is_object( $child ) && is_callable( [ $child, 'getExecutableChildren' ] ) ) { - $rule_scenarios = $child->getExecutableChildren(); - foreach ( $rule_scenarios as $scenario ) { + foreach ( $child->getExecutableChildren() as $scenario ) { + // As in Behat, the steps of the background come first, and an outline fills in its examples in them too. + if ( is_callable( [ $scenario, 'extractFromRule' ] ) ) { + $scenario = $scenario->extractFromRule( $child ); + } elseif ( is_callable( [ $child, 'getBackground' ] ) && null !== $child->getBackground() ) { + $backgrounds[ $child->getBackground()->getLine() ] = $child->getBackground(); + } $scenarios[ $scenario->getLine() ] = $scenario; } - if ( ! empty( $rule_scenarios ) && is_callable( [ $child, 'getBackground' ] ) && null !== $child->getBackground() ) { - $backgrounds[ $child->getBackground()->getLine() ] = $child->getBackground(); - } } } } diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 954daf6b6..b9b65541d 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -221,6 +221,27 @@ public function test_a_rule_background_applies_only_to_the_scenarios_of_its_rule $this->assertSame( [ 12 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 11, 11 ] ] ) ) ); $this->assertSame( [ 12 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), null, [], [ 'second' ] ) ) ); $this->assertSame( [ 5 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 7, 7 ] ] ) ) ); + + $outline = implode( + "\n", + [ + 'Feature: X', + '', + ' Rule: With examples', + ' Background:', + ' Given I have apples', + '', + ' Scenario Outline: Counting', + ' Given I have apples', + '', + ' Examples:', + ' | amount |', + ' | some |', + ' | many |', + ] + ); + + $this->assertSame( [ 5 => 'Given I have many apples' ], StepChecker::find_undefined_steps( $outline, $this->definitions() ) ); } public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { From 4d09b2135c3a2afe78ed9a85bf88872ce811304e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:22:33 +0000 Subject: [PATCH 13/18] Run Behat anyway when the step check itself fails The check runs with the PHP on the host, which may not load the project's dependencies, for example when the tests run in Docker with another PHP version. Only undefined steps, exit status 1, stop the run now; any other failure of the check prints a warning and Behat runs as it would without it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- bin/run-behat-tests | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/bin/run-behat-tests b/bin/run-behat-tests index 981b2693c..cd2ba2095 100755 --- a/bin/run-behat-tests +++ b/bin/run-behat-tests @@ -334,8 +334,16 @@ for arg in "$@"; do -d*|--definitions|--definitions=*|--rerun|--rerun-only|--init|-h|--help|--story-syntax) CHECK_STEPS="";; esac done -if [ -n "${CHECK_STEPS}" ] && ! php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$BEHAT_TAGS" "$@"; then - exit 1 +# Only a finding stops the run: if the check itself fails, for example because the PHP on the host +# cannot load the project's dependencies, Behat runs as it would without it. +if [ -n "${CHECK_STEPS}" ]; then + CHECK_STEPS_STATUS=0 + php "$WP_CLI_TESTS_ROOT"/utils/check-feature-steps.php "$BEHAT_TAGS" "$@" || CHECK_STEPS_STATUS=$? + if [ "${CHECK_STEPS_STATUS}" -eq 1 ]; then + exit 1 + elif [ "${CHECK_STEPS_STATUS}" -ne 0 ]; then + echo "Warning: could not check the feature files for undefined steps (exit status ${CHECK_STEPS_STATUS}), running Behat without the check." >&2 + fi fi BEHAT_EXTRA_ARGS=() From 8208ee6b5ffb34811a23085e635cb80513f63c68 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:23:34 +0000 Subject: [PATCH 14/18] Expect Behat 3's legacy reading of a rule in the outline test Behat 3 parses in the legacy Gherkin mode by default, which reads a rule at the top of a feature as part of its description, so the background belongs to the feature and an outline does not fill it in. The checker follows that; the test now expects it on Behat 3. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- tests/tests/TestStepChecker.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index b9b65541d..113917e69 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -241,7 +241,11 @@ public function test_a_rule_background_applies_only_to_the_scenarios_of_its_rule ] ); - $this->assertSame( [ 5 => 'Given I have many apples' ], StepChecker::find_undefined_steps( $outline, $this->definitions() ) ); + // Behat 3 parses in the legacy mode by default, which reads the rule as part of the description, + // so that its background becomes the background of the feature, which an outline does not fill in. + $behat_3 = version_compare( (string) \Composer\InstalledVersions::getVersion( 'behat/behat' ), '4', '<' ); + $expected = $behat_3 ? 'Given I have apples' : 'Given I have many apples'; + $this->assertSame( [ 5 => $expected ], StepChecker::find_undefined_steps( $outline, $this->definitions() ) ); } public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { From 9e7cc9638c4f959d41f30c6676e0d816d1dcd1c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:34:27 +0000 Subject: [PATCH 15/18] Follow BEHAT_FEATURES_FOLDER, and let workers and listing failures pass The step check defaulted to features/ where the parallel runner honours BEHAT_FEATURES_FOLDER. Workers of a parallel run, which get a list of the scenarios the host already checked, no longer list the definitions for nothing. A failed definition listing, which may be incomplete, now exits with 2, which run-behat-tests does not take for a finding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 2 +- tests/tests/TestStepChecker.php | 4 ++++ utils/check-feature-steps.php | 22 ++++++++++++++++++---- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index c3b7a6cb0..b0c1cfb50 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -147,7 +147,7 @@ public static function config_may_filter( array $config, $dir, $behat_params ) { */ public static function feature_files( array $paths ) { if ( empty( $paths ) ) { - $paths = [ 'features' ]; + $paths = [ getenv( 'BEHAT_FEATURES_FOLDER' ) ?: 'features' ]; } $files = []; diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 113917e69..58b2f20b2 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -322,7 +322,11 @@ public function test_feature_files_keep_the_selected_lines(): void { ); $this->assertSame( [ $dir . '/a.feature' => null ], StepChecker::feature_files( [ $dir . '/a.feature:5-*', $dir . '/a.feature' ] ) ); $this->assertSame( [ [ 5, PHP_INT_MAX ] ], StepChecker::feature_files( [ $dir . '/a.feature:5-*' ] )[ $dir . '/a.feature' ] ); + + putenv( 'BEHAT_FEATURES_FOLDER=' . $dir . '/sub' ); + $this->assertSame( [ $dir . '/sub' . DIRECTORY_SEPARATOR . 'b.feature' => null ], StepChecker::feature_files( [] ) ); } finally { + putenv( 'BEHAT_FEATURES_FOLDER' ); unlink( $dir . '/a.feature' ); unlink( $dir . '/sub/b.feature' ); unlink( $dir . '/sub/notes.txt' ); diff --git a/utils/check-feature-steps.php b/utils/check-feature-steps.php index 37cf936dc..6c3bfbaee 100644 --- a/utils/check-feature-steps.php +++ b/utils/check-feature-steps.php @@ -6,8 +6,8 @@ * Usage: php check-feature-steps.php [ ...] * * Expects to run from the package root with BEHAT_PARAMS set the way - * run-behat-tests sets it. Exits with 1 if it finds an undefined step, and - * with 0 if it does not, or if the definitions cannot be listed. + * run-behat-tests sets it. Exits with 1 if it finds an undefined step, with 2 + * if the definitions cannot be listed, and with 0 otherwise. */ namespace WP_CLI\Tests; @@ -33,8 +33,22 @@ function check_feature_steps( array $args ) { return 0; } - $listing = (string) shell_exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors ' . implode( ' ', array_map( 'escapeshellarg', $args['config'] ) ) . ' 2>/dev/null' ); - $definitions = StepChecker::parse_definitions( $listing ); + // A worker of a parallel run gets a list of the scenarios to run, all of which were checked before. + foreach ( $args['paths'] as $path ) { + if ( is_file( $path ) && '.feature' !== substr( $path, -8 ) ) { + return 0; + } + } + + $listing = []; + exec( escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat --definitions=l --no-colors ' . implode( ' ', array_map( 'escapeshellarg', $args['config'] ) ) . ' 2>/dev/null', $listing, $status ); + if ( 0 !== $status ) { + // Some of the definitions may be missing, which run-behat-tests does not take for a finding. + fwrite( STDERR, "Could not list the step definitions (exit status {$status}).\n" ); + return 2; + } + + $definitions = StepChecker::parse_definitions( implode( "\n", $listing ) ); if ( empty( $definitions ) ) { return 0; } From 29dbbd4dff09079060a3f39cf171c5db2127f001 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:36:30 +0000 Subject: [PATCH 16/18] Report only steps that are undefined in every reading of the file A project can configure the Gherkin compatibility mode, which the checker cannot see, and the modes may read a file differently: the legacy mode of Behat 3 takes a single rule for description, so an outline does not fill in its background. The checker now reads the file in every mode that parses it and reports only the steps that are undefined in all of them, so it cannot block a run that the configured mode would accept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 37 ++++++++++++++++++++++++--------- tests/tests/TestStepChecker.php | 4 ++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index b0c1cfb50..a0a19edb6 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -256,11 +256,26 @@ public static function turnip_to_regex( $pattern ) { * @return array Undefined steps, with their keyword, keyed by line number. */ public static function find_undefined_steps( $contents, array $definitions, $lines = null, array $tags = [], array $names = [] ) { - $feature = self::parse( $contents ); - if ( null === $feature ) { - return []; + // A project can configure the Gherkin compatibility mode, which may read a file differently, so + // only steps that are undefined however the file is read are reported, in the default reading. + $undefined = null; + foreach ( self::parse( $contents ) as $feature ) { + $found = self::undefined_steps_in( $feature, $definitions, $lines, $tags, $names ); + $undefined = null === $undefined ? $found : array_intersect_key( $undefined, $found ); } + return (array) $undefined; + } + + /** + * @param FeatureNode $feature + * @param array $definitions + * @param array|null $lines + * @param string[] $tags + * @param string[] $names + * @return array + */ + private static function undefined_steps_in( FeatureNode $feature, array $definitions, $lines, array $tags, array $names ) { $filters = []; foreach ( $tags as $tag ) { $filters[] = new TagFilter( $tag ); @@ -331,14 +346,13 @@ public static function find_undefined_steps( $contents, array $definitions, $lin } /** - * Parses a feature file as the Behat installation does by default. + * Parses a feature file in every Gherkin compatibility mode that can. * - * A project can configure another Gherkin compatibility mode, so the - * other modes are tried when the default one cannot parse the file. + * The reading of the mode the Behat installation uses by default comes + * first. None if no mode can parse the file, which Behat then reports. * * @param string $contents Contents of the feature file. - * @return FeatureNode|null Null if no mode can parse the file, which - * Behat then reports itself. + * @return FeatureNode[] */ private static function parse( $contents ) { $parser = self::parser(); @@ -360,6 +374,7 @@ function ( $mode ) use ( $legacy ) { } } + $features = []; foreach ( $modes as $mode ) { if ( null !== $mode ) { $parser->setGherkinCompatibilityMode( $mode ); @@ -369,10 +384,12 @@ function ( $mode ) use ( $legacy ) { } catch ( \Exception $exception ) { continue; } - return $feature instanceof FeatureNode ? $feature : null; + if ( $feature instanceof FeatureNode ) { + $features[] = $feature; + } } - return null; + return $features; } /** diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index 58b2f20b2..d3aa2130a 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -246,6 +246,10 @@ public function test_a_rule_background_applies_only_to_the_scenarios_of_its_rule $behat_3 = version_compare( (string) \Composer\InstalledVersions::getVersion( 'behat/behat' ), '4', '<' ); $expected = $behat_3 ? 'Given I have apples' : 'Given I have many apples'; $this->assertSame( [ 5 => $expected ], StepChecker::find_undefined_steps( $outline, $this->definitions() ) ); + + // A project on Behat 3 may parse like recent cucumber/gherkin versions, which fills in the examples. + $defined = str_replace( '| many |', '| some |', $outline ); + $this->assertSame( [], StepChecker::find_undefined_steps( $defined, $this->definitions() ) ); } public function test_option_values_are_not_paths_and_the_configuration_is_kept(): void { From 3259cd1f7d33dc0c58a16c6a3cdf3bb5029533aa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:54:19 +0000 Subject: [PATCH 17/18] Match placeholders like Behat, and keep every selected outline subset A placeholder in quotes of the pattern itself, as in `a file named ":name"`, now takes any quoted value, with Behat's own token expression. Two paths that select different examples of one outline no longer replace each other, and the test restores BEHAT_FEATURES_FOLDER as it found it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 10 ++++++---- tests/tests/TestStepChecker.php | 28 ++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index a0a19edb6..fe0da3170 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -226,7 +226,8 @@ public static function is_regex( $pattern ) { */ public static function turnip_to_regex( $pattern ) { $regex = preg_quote( $pattern, '/' ); - $regex = (string) preg_replace( '/\\\\:(\w+)/', '(?:"[^"]*"|\'[^\']*\'|[^\s"\']+)', $regex ); + // Behat's own token: a quoted value, also inside quotes of the pattern itself, or a single word. + $regex = (string) preg_replace( '/\\\\:(\w+)/', '["\']?(?:(?<=")[^"]*(?=")|(?<=\')[^\']*(?=\')|\-?[\w\.\,]+)[\'"]?', $regex ); // `(word)` is optional, and so are the spaces around it. $regex = (string) preg_replace( '/(\s)?\\\\\(([^\\\]+)\\\\\)(\s)?/', '(?:\1)?(?:\2)?(?:\3)?', $regex ); // `word/other` accepts either word; `\/` is a plain slash. @@ -287,7 +288,8 @@ private static function undefined_steps_in( FeatureNode $feature, array $definit $feature = $filter->filterFeature( $feature ); } - // Each path is a run of its own, so the scenarios its lines select add up. + // Each path is a run of its own, so the scenarios its lines select add up. Two paths can select + // different examples of one outline, so the scenarios are kept apart even when they share a line. $scenarios = []; $selected = null === $lines ? [ $feature ] : []; foreach ( (array) $lines as $range ) { @@ -301,7 +303,7 @@ private static function undefined_steps_in( FeatureNode $feature, array $definit $children = is_callable( [ $filtered, 'getExecutableChildren' ] ) ? $filtered->getExecutableChildren() : call_user_func( [ $filtered, 'getScenarios' ] ); foreach ( $children as $child ) { if ( $child instanceof ScenarioInterface ) { - $scenarios[ $child->getLine() ] = $child; + $scenarios[] = $child; } elseif ( is_object( $child ) && is_callable( [ $child, 'getExecutableChildren' ] ) ) { foreach ( $child->getExecutableChildren() as $scenario ) { // As in Behat, the steps of the background come first, and an outline fills in its examples in them too. @@ -310,7 +312,7 @@ private static function undefined_steps_in( FeatureNode $feature, array $definit } elseif ( is_callable( [ $child, 'getBackground' ] ) && null !== $child->getBackground() ) { $backgrounds[ $child->getBackground()->getLine() ] = $child->getBackground(); } - $scenarios[ $scenario->getLine() ] = $scenario; + $scenarios[] = $scenario; } } } diff --git a/tests/tests/TestStepChecker.php b/tests/tests/TestStepChecker.php index d3aa2130a..b27b8c2a4 100644 --- a/tests/tests/TestStepChecker.php +++ b/tests/tests/TestStepChecker.php @@ -21,6 +21,7 @@ class TestStepChecker extends TestCase { default | Given I have (some) apples default | Given ~^a widget named (\w+)$~i default | Then {^the cache should( not)? be warm$} +default | Given a file named ":name" LISTING; /** @@ -31,7 +32,7 @@ private function definitions(): array { } public function test_parses_every_definition(): void { - $this->assertCount( 12, $this->definitions() ); + $this->assertCount( 13, $this->definitions() ); $this->assertSame( 'Given an empty directory', $this->definitions()[0]['label'] ); } @@ -54,6 +55,8 @@ public static function data_defined_steps(): array { 'optional word written' => [ 'Given I have some apples' ], 'tilde regex' => [ 'Given A widget named foo' ], 'brace regex' => [ 'Then the cache should not be warm' ], + 'quoted placeholder word' => [ 'Given a file named "foo"' ], + 'quoted placeholder text' => [ 'Given a file named "foo bar"' ], ]; } @@ -188,6 +191,24 @@ public function test_selected_lines_check_only_their_scenarios_and_the_backgroun $this->assertSame( [ 3, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 9, PHP_INT_MAX ] ] ) ) ); $this->assertSame( [ 3, 6, 10 ], array_keys( StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 5, 5 ], [ 9, 9 ] ] ) ) ); $this->assertSame( [], StepChecker::find_undefined_steps( $feature, $this->definitions(), [ [ 6, 6 ] ] ) ); + + $outline = implode( + "\n", + [ + 'Feature: X', // 1 + ' Scenario Outline: Codes', // 2 + ' Then the return code should be ', // 3 + '', // 4 + ' Examples:', // 5 + ' | code |', // 6 + ' | many |', // 7 + ' | 0 |', // 8 + ] + ); + + // Two paths that select different examples of one outline both count. + $this->assertSame( [ 3 ], array_keys( StepChecker::find_undefined_steps( $outline, $this->definitions(), [ [ 7, 7 ], [ 8, 8 ] ] ) ) ); + $this->assertSame( [], StepChecker::find_undefined_steps( $outline, $this->definitions(), [ [ 8, 8 ] ] ) ); } public function test_a_rule_background_applies_only_to_the_scenarios_of_its_rule(): void { @@ -327,10 +348,13 @@ public function test_feature_files_keep_the_selected_lines(): void { $this->assertSame( [ $dir . '/a.feature' => null ], StepChecker::feature_files( [ $dir . '/a.feature:5-*', $dir . '/a.feature' ] ) ); $this->assertSame( [ [ 5, PHP_INT_MAX ] ], StepChecker::feature_files( [ $dir . '/a.feature:5-*' ] )[ $dir . '/a.feature' ] ); + $features_folder = getenv( 'BEHAT_FEATURES_FOLDER' ); putenv( 'BEHAT_FEATURES_FOLDER=' . $dir . '/sub' ); $this->assertSame( [ $dir . '/sub' . DIRECTORY_SEPARATOR . 'b.feature' => null ], StepChecker::feature_files( [] ) ); } finally { - putenv( 'BEHAT_FEATURES_FOLDER' ); + if ( isset( $features_folder ) ) { + putenv( false === $features_folder ? 'BEHAT_FEATURES_FOLDER' : 'BEHAT_FEATURES_FOLDER=' . $features_folder ); + } unlink( $dir . '/a.feature' ); unlink( $dir . '/sub/b.feature' ); unlink( $dir . '/sub/notes.txt' ); From 4b3d28d649f3d3c4b91c736d7230f334b5d428eb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:56:39 +0000 Subject: [PATCH 18/18] Describe the placeholder token as it now is Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- src/StepChecker.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/StepChecker.php b/src/StepChecker.php index fe0da3170..b83f3d9d4 100644 --- a/src/StepChecker.php +++ b/src/StepChecker.php @@ -218,8 +218,8 @@ public static function is_regex( $pattern ) { /** * Converts a Turnip pattern, such as `a WP install(ation) in :subdir`, to a - * regex the way Behat's TurnipPatternPolicy does, except that a placeholder - * accepts any unquoted word, which can only leave out a false report. + * regex the way Behat's TurnipPatternPolicy does, with the same token for + * a placeholder: a quoted value, or a word of letters, digits, `.` and `,`. * * @param string $pattern * @return string