8000 Added tests for docs generator. by AlexSkrypnyk · Pull Request #383 · drevops/behat-steps · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Added tests for docs generator. #383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 4, 2025
Merged

Conversation

AlexSkrypnyk
Copy link
Member
@AlexSkrypnyk AlexSkrypnyk commented May 3, 2025

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive unit testing support with PHPUnit, including configuration files and new commands to run tests with or without coverage.
    • Added extensive unit tests covering documentation parsing, formatting, validation, and content replacement.
    • Enabled configurable base path support for documentation generation scripts.
    • Simplified linting and database commands for improved usability.
    • Split CI test steps to run unit and BDD tests with coverage separately.
  • Chores

    • Updated configuration files for unit testing, code coverage, and static analysis.
    • Added multiple development dependencies for testing, linting, static analysis, and code quality.
    • Enhanced .gitignore to exclude PHPUnit cache files.
    • Simplified test fixture composer configurations for minimal, stable setups.
    • Refined composer merging logic for better dependency management.
  • Refactor

    • Improved modularity and error handling in documentation generation scripts.
    • Updated static analysis and code style configurations to reflect new directory structures.
    • Replaced dynamic Drupal root detection with a fixed path in Rector configuration.
  • Documentation

    • Clarified usage descriptions for test commands.
    • Expanded README with detailed instructions distinguishing unit and Behat tests.

Copy link
coderabbitai bot commented May 3, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces and configures PHPUnit-based unit testing to the project. It adds a PHPUnit configuration file, new development dependencies, and a dedicated autoload section for unit tests. The .ahoy.yml file is updated with commands for running unit tests with and without code coverage. The .gitignore, phpcs.xml, and phpstan.neon files are modified to accommodate the new test directories and cache files. The docs.php script is refactored for improved modularity and configurability. Two new unit test classes, including a comprehensive test suite for documentation utilities, are added under tests/phpunit/src/. The CircleCI configuration is adjusted to separate unit and BDD test steps, and the provisioning script modifies composer.json merging logic for dev dependencies and autoload sections. The README is updated to clarify testing instructions for unit and Behat tests. Additional changes include simplification of the Drupal 10 Behat fixture composer.json, addition of a .gitignore file in the fixture directory, and modification of the Rector configuration to use a static Drupal root path.

Changes

File(s) Change Summary
.ahoy.yml Added test-unit and test-unit-coverage commands for PHPUnit; fixed shell condition chaining; simplified lint and lint-fix commands; updated usage for test-bdd-coverage.
.gitignore Added /.phpunit.cache to ignore PHPUnit cache files.
composer.json Added require-dev dependencies for testing, linting, static analysis; added autoload-dev for unit tests; reordered keys; added patches; updated allowed plugins.
phpunit.xml Added new PHPUnit configuration file with coverage, logging, and suite setup for tests/phpunit/src/.
phpcs.xml, phpstan.neon Updated scan paths to include tests/phpunit/src; removed relative parent directory prefixes; added error ignores for test code.
docs.php Refactored main execution into main() function; added --path option for base directory; improved modularity, file path handling, and comment parsing robustness.
tests/phpunit/src/UnitTestCase.php Added base unit test class extending PHPUnit helpers.
tests/phpunit/src/DocsTest.php Added comprehensive PHPUnit test class for documentation-related functions with multiple data providers.
.circleci/config.yml Split single test step into separate steps for unit tests with coverage and BDD tests with coverage.
.circleci/provision.sh Modified composer.json merging logic to selectively merge require-dev and autoload sections from base composer.json before merging.
README.md Expanded test documentation to distinguish unit and Behat tests; added commands for running unit tests and coverage; clarified Behat test commands.
rector.php Removed dynamic Drupal root detection; hardcoded Drupal root path; removed Drupal Rector sets.
tests/behat/fixtures/d10/.gitignore Added .gitignore file ignoring composer.lock, vendor/, and .gitattributes.
tests/behat/fixtures/d10/composer.json Simplified and cleaned Drupal 10 Behat fixture composer.json; reduced dependencies and configuration complexity.
tests/behat/fixtures/d11/composer.json Simplified and cleaned Drupal 11 Behat fixture composer.json; reduced dependencies and configuration complexity.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant CLI
    participant PHPUnit
    participant Codebase

    Developer->>CLI: Run "ahoy test-unit" or "ahoy test-unit-coverage"
    CLI->>PHPUnit: Execute PHPUnit (with/without coverage)
    PHPUnit->>Codebase: Load tests from tests/phpunit/src/
    Codebase-->>PHPUnit: Execute test cases
    PHPUnit-->>CLI: Output results (with/without coverage report)
    CLI-->>Developer: Display test summary and reports
Loading

Poem

🐇
A hop, a skip, a test anew,
With PHPUnit, our code we view.
New commands to run and check with glee,
Coverage reports as clear as can be.
Docs and configs now neat and tight—
The rabbit approves, all tests in sight!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 14b6ef2 and cfb3cd5.

📒 Files selected for processing (13)
  • .ahoy.yml (4 hunks)
  • .circleci/config.yml (1 hunks)
  • .circleci/provision.sh (1 hunks)
  • README.md (2 hunks)
  • composer.json (2 hunks)
  • phpcs.xml (1 hunks)
  • phpstan.neon (1 hunks)
  • phpunit.xml (1 hunks)
  • rector.php (1 hunks)
  • tests/behat/fixtures/d10/.gitignore (1 hunks)
  • tests/behat/fixtures/d10/composer.json (3 hunks)
  • tests/behat/fixtures/d11/composer.json (3 hunks)
  • tests/phpunit/src/DocsTest.php (1 hunks)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 362f2a8 and 38ce9b4.

📒 Files selected for processing (9)
  • .ahoy.yml (1 hunks)
  • .gitignore (1 hunks)
  • composer.json (2 hunks)
  • docs.php (4 hunks)
  • phpcs.xml (1 hunks)
  • phpstan.neon (2 hunks)
  • phpunit.xml (1 hunks)
  • tests/phpunit/src/DocsTest.php (1 hunks)
  • tests/phpunit/src/UnitTestCase.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
docs.php (1)
tests/behat/bootstrap/FeatureContext.php (1)
  • FeatureContext (46-93)
🔇 Additional comments (21)
phpstan.neon (4)

14-14: Good addition of PHPUnit test directory to PHPStan analysis

Including the unit test directory in static analysis ensures test code is also held to high code quality standards.


23-24: Improved Behat path reference

Using a relative path for the Behat binary improves consistency and portability across different environments.


25-27: Proper configuration of PHPUnit dependencies for analysis

Adding the PHPUnit and helpers packages to scan directories enables PHPStan to better understand the code and reduces false positives in analysis.


29-36: Well-documented error suppression for test files

The error suppression is:

  1. Properly scoped to only test files
  2. Narrowly targeted to a specific error type
  3. Well-documented with clear reasoning

This is the right approach for handling the common issue of iterable types in test data providers.

.ahoy.yml (2)

135-142: Well-implemented unit test commands

The new test commands properly integrate PHPUnit into the project workflow. The test-unit command runs basic tests while test-unit-coverage enables code coverage reporting via pcov.


148-148: Updated description for consistency

Good update to the description for test-bdd-coverage, making it clear that this command runs tests with coverage, consistent with the new test-unit-coverage command.

composer.json (2)

31-38: Well-structured autoloading for tests

The autoload-dev section is properly configured to support the test infrastructure. Including docs.php in the files section ensures it's available during testing.


48-51: Appropriate test dependencies

The required dev dependencies are specifically chosen to support the unit testing infrastructure. PHPUnit v11 is the latest version and alexskrypnyk/phpunit-helpers provides useful testing utilities.

docs.php (8)

17-17: Improved CLI interface with path option

Good addition of the --path option to allow specifying a custom base directory, which enhances the script's flexibility and reusability.


22-26: Improved modularity with conditional main execution

The script now only executes the main function when run directly, not when included. This is a good practice that makes the script more testable and reusable as a library.


28-81: Well-structured main function extraction

Extracting the main functionality into a separate function improves testability and organization. The function properly handles options and has appropriate code coverage annotations.


100-100: Base path parameter added for better flexibility

The extract_info function now accepts a base path parameter, allowing for more flexible file resolution. This aligns well with the new --path CLI option.


207-209: Enhanced robustness in comment parsing

Early return for empty comments improves robustness and prevents potential issues with null or empty values.


310-310: Consistent base path parameter across functions

The render_info function also accepts a base path parameter now, maintaining consistency with other functions and supporting the --path CLI option.


317-320: Improved error handling with full paths

Error messages now include full paths which makes debugging easier, especially when using custom base paths.


327-331: Appropriate code coverage exclusions

The code that checks for example file existence is properly excluded from code coverage since it's difficult to test and primarily for runtime validation.

tests/phpunit/src/DocsTest.php (2)

23-35: Typo in data-provider name makes the intent unclear

Both the #[DataProvider] attribute (line 23) and the corresponding static method (line 35) are spelled dataProverParseMethodComment (“Prover” instead of “Provider”).
While this still works because the names match, the misspelling is confusing for future readers and for IDE code-completion / navigation.

-#[DataProvider('dataProverParseMethodComment')]
+#[DataProvider('dataProviderParseMethodComment')]
 ...
-public static function dataProverParseMethodComment(): array {
+public static function dataProviderParseMethodComment(): array {

[ suggest_nitpick ]


253-256: Verify desired behaviour for consecutive capital letters

The test case for HTTPRequest expects the result h_t_t_p_request, i.e. every capital letter is split by an underscore.
Most “camel-to-snake” helpers convert an acronym to a single word (http_request). Please double-check that the production function really intends the more verbose behaviour and that other call-sites rely on it; otherwise the test may cement an un-idiomatic conversion rule.
[ request_verification ]

.gitignore (1)

5-5: Approve addition of PHPUnit cache directory to .gitignore.
Ignoring /.phpunit.cache prevents PHPUnit’s cache files from being committed, keeping the repo clean.

phpcs.xml (1)

25-25: Approve inclusion of PHPUnit test source directory in PHPCS configuration.
Adding <file>../tests/phpunit/src</file> aligns the CodeSniffer rules with the new PHPUnit test suite so that test code is style-checked.

tests/phpunit/src/UnitTestCase.php (1)

1-14: Approve the new base test case class.
The class correctly enables strict types, declares the DrevOps\BehatSteps\Tests namespace, and extends the upstream helper, providing a solid foundation for writing unit tests.

phpunit.xml Outdated
Comment on lines 1 to 45
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="false"
beStrictAboutOutputDuringTests="true"
failOnRisky="true"
failOnWarning="true"
displayDetailsOnTestsThatTriggerWarnings="true"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerDeprecations="true"
displayDetailsOnPhpunitDeprecations="true">
<php>
<env name="SCRIPT_RUN_SKIP" value="1"/>
</php>
<testsuites>
<testsuite name="default">
<directory>tests/phpunit/src/</directory>
</testsuite>
</testsuites>
<source restrictNotices="true"
restrictWarnings="true"
ignoreIndirectDeprecations="true">
<include>
<file>docs.php</file>
</include>
<exclude>
<directory>tests/phpunit/src</directory>
</exclude>
</source>
<coverage pathCoverage="false"
ignoreDeprecatedCodeUnits="true"
disableCodeCoverageIgnore="false">
<report>
<html outputDirectory=".logs/phpunit/.coverage-html" lowUpperBound="50" highLowerBound="90"/>
<cobertura outputFile=".logs/phpunit/cobertura.xml"/>
</report>
</coverage>
<logging>
<junit outputFile=".logs/phpunit/junit.xml"/>
</logging>
</phpunit>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Well-structured PHPUnit configuration

The PHPUnit configuration is comprehensive and follows best practices:

  • Proper bootstrap configuration
  • Appropriate caching setup
  • Test suite correctly targets the new unit tests
  • Coverage reporting is well configured with both HTML and Cobertura XML
  • JUnit XML logging for CI integration

One suggestion regarding the coverage configuration:

Consider adding a comment explaining the purpose of the SCRIPT_RUN_SKIP environment variable since its usage might not be immediately clear to other developers.

Comment on lines +417 to +420
if (isset($info['MissingTrait'])) {
$src_file_path = $base_path . DIRECTORY_SEPARATOR . 'src/MissingTrait.php';
@unlink($src_file_path);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Minor: remove unused $methods variable to silence IDE warnings

Inside the foreach ($info as $trait => $methods) loop $methods is never used.
Replacing it with the throw-away variable _ (or omitting it with foreach (array_keys($info) as $trait)) avoids “unused variable” inspections.

-foreach ($info as $trait => $methods) {
+foreach (array_keys($info) as $trait) {

10000

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

♻️ Duplicate comments (3)
tests/phpunit/src/DocsTest.php (3)

410-412: Suppressing errors with @mkdir() may hide real problems
(See the same remark in the previous review.)

Using @ discards permission and race-condition failures that would otherwise give an immediate, helpful stack-trace. Swap it with an assertion (or remove the @) so the test fails loudly if the directory cannot be created.


414-423: Variable $methods is never used inside the loop

The value part of the foreach ($info as $trait => $methods) isn’t referenced, so most IDEs will mark $methods as unused. Switching to foreach (array_keys($info) as $trait) (or _) silences the warning and conveys intent more clearly.


427-428: 🛠️ Refactor suggestion

Avoid silencing potential failures with @unlink()

If @unlink() fails (e.g. file already removed or permission denied) the test proceeds in an inconsistent state and might produce misleading assertions later.
Remove the @ operator and optionally wrap the call with self::assertTrue(unlink($src_file_path)) to surface the real error.

-  @unlink($src_file_path);
+  self::assertTrue(
+    !file_exists($src_file_path) || unlink($src_file_path),
+    "Failed to delete temporary file $src_file_path"
+  );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 38ce9b4 and 90f7e91.

📒 Files selected for processing (6)
  • .ahoy.yml (1 hunks)
  • .circleci/config.yml (1 hunks)
  • .circleci/provision.sh (1 hunks)
  • README.md (2 hunks)
  • composer.json (2 hunks)
  • tests/phpunit/src/DocsTest.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/phpunit/src/DocsTest.php (2)
tests/phpunit/src/UnitTestCase.php (1)
  • UnitTestCase (12-14)
docs.php (6)
  • parse_method_comment (206-297)
  • camel_to_snake (462-479)
  • array_to_markdown_table (524-536)
  • render_info (310-382)
  • validate (393-449)
  • replace_content (493-511)
🔇 Additional comments (2)
composer.json (1)

31-35: PSR-4 dev autoload and dev dependencies correctly added
The new autoload-dev block and require-dev section properly configure PHPUnit and test helpers for the DrevOps\BehatSteps\Tests\ namespace. Great setup for your unit testing framework.

Also applies to: 45-48

.ahoy.yml (1)

152-153: Usage text refined for BDD coverage command
The test-bdd-coverage usage has been updated to clarify it runs BDD tests with coverage. This aligns with the naming of the new unit test commands.

Comment on lines +35 to +37
name: Run Unit tests with coverage
command: ahoy test-unit-coverage || [ "${CI_TEST_IGNORE_FAILURE:-0}" -eq 1 ]

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add timeouts to new test steps for consistency
The new “Run Unit tests with coverage” and “Run BDD tests with coverage” steps mirror the existing build step but lack a no_output_timeout. To prevent CI hangs on long-running tests, consider adding a no_output_timeout (e.g., no_output_timeout: 30m) to both steps.

Also applies to: 38-40

Comment on lines 29 to 49
php -r '
$base = json_decode(file_get_contents("/app/composer.json"), true);
$override = json_decode(file_get_contents("/app/build/composer.json"), true);
unset($base["require-dev"]);
$base["autoload-dev"] = $base["autoload"];
unset($base["autoload"]);
echo json_encode(array_replace_recursive($base, $override), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
' > "/app/build/composer2.json" && mv -f "/app/build/composer2.json" "/app/build/composer.json"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Inconsistent comment vs. code for JSON encoding flags
The inline comment advises not to add JSON_UNESCAPED_SLASHES, yet the json_encode call includes it. This discrepancy risks breaking the intended sed-based path replacements.

Apply this diff to align code with the comment:

-echo json_encode(array_replace_recursive($base, $override), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+echo json_encode(array_replace_recursive($base, $override), JSON_PRETTY_PRINT);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
php -r '
$base = json_decode(file_get_contents("/app/composer.json"), true);
$override = json_decode(file_get_contents("/app/build/composer.json"), true);
unset($base["require-dev"]);
$base["autoload-dev"] = $base["autoload"];
unset($base["autoload"]);
echo json_encode(array_replace_recursive($base, $override), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
' > "/app/build/composer2.json" && mv -f "/app/build/composer2.json" "/app/build/composer.json"
php -r '
$base = json_decode(file_get_contents("/app/composer.json"), true);
$override = json_decode(file_get_contents("/app/build/composer.json"), true);
unset($base["require-dev"]);
$base["autoload-dev"] = $base["autoload"];
unset($base["autoload"]);
echo json_encode(array_replace_recursive($base, $override), JSON_PRETTY_PRINT);
' > "/app/build/composer2.json" && mv -f "/app/build/composer2.json" "/app/build/composer.json"

.ahoy.yml Outdated
Comment on lines 135 to 137
test-unit:
usage: Run Unit tests.
cmd: |
[ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
ahoy cli "./vendor/bin/phpunit -c phpunit.xml --no-coverage $@"

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure PHPUnit executable check in test-unit command
Using the presence of the entire vendor directory to skip composer install can lead to cases where vendor exists but vendor/bin/phpunit is missing (e.g., after a --no-dev install).

Apply this diff:

-      [ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
+      [ ! -f vendor/bin/phpunit ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction

.ahoy.yml Outdated
test-unit-coverage:
usage: Run Unit tests with coverage.
cmd: |
[ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
ahoy cli "php -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Enable PCOV when generating coverage in test-unit-coverage
The current command sets pcov.directory but doesn’t enable PCOV, so coverage reports may not be generated.

Apply this diff:

-      ahoy cli "php -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
+      ahoy cli "php -dpcov.enabled=1 -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test-unit-coverage:
usage: Run Unit tests with coverage.
cmd: |
[ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
ahoy cli "php -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
test-unit-coverage:
usage: Run Unit tests with coverage.
cmd: |
[ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
ahoy cli "php -dpcov.enabled=1 -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"

Comment on lines +26 to +30
protected function setUp(): void {
parent::setUp();

require_once __DIR__ . '/../../../docs.php';
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Load the target code once via PHPUnit bootstrap instead of per-test require_once

Including docs.php in setUp() means the file is loaded before every single test method, incurring unnecessary I/O and making it harder to share the bootstrap logic with other future tests.
Consider moving the include to PHPUnit’s bootstrap (see phpunit.xml) or Composer’s autoload-dev so it is executed only once.

-  protected function setUp(): void {
-    parent::setUp();
-
-    require_once __DIR__ . '/../../../docs.php';
-  }
+  // setUp() can stay empty once docs.php is required from phpunit.xml:
+  protected function setUp(): void {
+    parent::setUp();
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
protected function setUp(): void {
parent::setUp();
require_once __DIR__ . '/../../../docs.php';
}
// setUp() can stay empty once docs.php is required from phpunit.xml:
protected function setUp(): void {
parent::setUp();
}

@AlexSkrypnyk AlexSkrypnyk force-pushed the feature/docs-generator-tests branch from 90f7e91 to c8534c3 Compare May 4, 2025 00:54
Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (8)
.circleci/config.yml (1)

35-40: 🛠️ Refactor suggestion

Add timeouts to new test steps for consistency

The new "Run Unit tests with coverage" and "Run BDD tests with coverage" steps mirror the existing build step but lack a no_output_timeout. To prevent CI hangs on long-running tests, consider adding a no_output_timeout (e.g., no_output_timeout: 30m) to both steps.

    - run:
        name: Run Unit tests with coverage
        command: ahoy test-unit-coverage || [ "${CI_TEST_IGNORE_FAILURE:-0}" -eq 1 ]
+       no_output_timeout: 30m

    - run:
        name: Run BDD tests with coverage
        command: ahoy test-bdd-coverage || [ "${CI_TEST_IGNORE_FAILURE:-0}" -eq 1 ]
+       no_output_timeout: 30m
README.md (1)

136-148: Inconsistent heading levels between test sections

The “Unit tests” section uses a fourth-level heading (####), while “Behat tests” uses a third-level heading (###). For consistency and better hierarchy, align both sections to the same heading level (e.g., ###).

.ahoy.yml (2)

139-144: ⚠️ Potential issue

Enable PCOV in coverage command

Coverage may not be generated since PCOV isn’t enabled. Modify to:

- ahoy cli "php -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
+ ahoy cli "php -dpcov.enabled=1 -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"

133-138: ⚠️ Potential issue

Use executable check instead of directory presence

Checking only for the existence of vendor can skip composer install when vendor/bin/phpunit is missing. Update the condition:

- [ ! -d vendor ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
+ [ ! -f vendor/bin/phpunit ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction
tests/phpunit/src/DocsTest.php (4)

32-34: Rename typo in data-provider attribute for consistency

dataProverParseMethodComment looks like a misspelling of “Provider” and was flagged previously.
Please rename both the method and the attribute reference to dataProviderParseMethodComment to improve readability.

-#[DataProvider('dataProverParseMethodComment')]
+#[DataProvider('dataProviderParseMethodComment')]

-public static function dataProverParseMethodComment(): array {
+public static function dataProviderParseMethodComment(): array {

26-30: Load docs.php once via PHPUnit bootstrap instead of per-test include

Requiring the target file in every setUp() incurs unnecessary I/O.
Move the include to phpunit.xml’s <bootstrap> or rely on Composer autoload.


410-411: Avoid silencing errors with @mkdir()

The error-control operator hides real problems (e.g. permission issues) and can cause confusing failures later in the test.
Use an assertion or let the exception surface:

-@mkdir($trait_dir, 0777, TRUE);
-@mkdir($features_dir, 0777, TRUE);
+self::assertTrue(is_dir($trait_dir) || mkdir($trait_dir, 0777, true));
+self::assertTrue(is_dir($features_dir) || mkdir($features_dir, 0777, true));

414-414: Remove unused $methods variable to silence IDE/static-analysis warnings

The loop value is never referenced; replace it with a throw-away variable:

-foreach ($info as $trait => $methods) {
+foreach (array_keys($info) as $trait) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 90f7e91 and c8534c3.

📒 Files selected for processing (11)
  • .ahoy.yml (3 hunks)
  • .circleci/config.yml (1 hunks)
  • .circleci/provision.sh (1 hunks)
  • README.md (2 hunks)
  • composer.json (2 hunks)
  • phpcs.xml (1 hunks)
  • phpstan.neon (1 hunks)
  • rector.php (1 hunks)
  • tests/behat/fixtures/d10/.gitignore (1 hunks)
  • tests/behat/fixtures/d10/composer.json (3 hunks)
  • tests/phpunit/src/DocsTest.php (1 hunks)
🔇 Additional comments (18)
rector.php (1)

32-32: Hardcoded Drupal root improves configuration simplicity

The change to use a hardcoded path ($drupalRoot = 'build/web') rather than dynamic detection simplifies the Rector configuration and removes unnecessary dependencies. This aligns well with the project's move toward streamlined testing infrastructure.

tests/behat/fixtures/d10/.gitignore (1)

1-3: Appropriate Git ignore patterns for Composer-managed project

The added ignore patterns are standard for Composer projects and will correctly exclude generated files from version control.

phpcs.xml (2)

23-26: PHPCS file paths correctly include new test directory

The updated paths properly include the new PHPUnit tests directory and remove relative parent directory prefixes, making paths more consistent and maintainable.


29-30: Correctly updated CircleCI config exclusion patterns

Exclusion patterns for CircleCI configuration files now use the correct relative paths without parent directory prefixes.

phpstan.neon (4)

12-15: Approve static analysis paths update

Including tests/phpunit/src and removing relative parent prefixes ensures PHPStan analyzes all relevant code.


20-21: Approve updated excludePaths

Excluding tests/behat/bootstrap/BehatCliContext.php prevents unwanted context files from being analyzed.


25-28: Approve scanDirectories expansion

Adding vendor/phpunit/phpunit and vendor/alexskrypnyk/phpunit-helpers allows PHPStan to inspect development dependencies for better type coverage.


29-37: Approve ignoreErrors configuration

Suppressing missing iterable type annotation errors in test files is a scoped and maintainable approach.

tests/behat/fixtures/d10/composer.json (4)

5-5: Approve project type for fixture

Using "type": "project" accurately reflects that this is a standalone Drupal site fixture.


23-23: Approve retained webflo/drupal-finder dependency

Including webflo/drupal-finder is necessary for locating the Drupal root; its presence here aligns with fixture requirements.


26-26: Approve minimal require-dev inclusion

Keeping only drupal/core-dev as a development dependency ensures essential tooling for the fixture while minimizing bloat.


45-46: Approve fixture config adjustments

Setting "process-timeout": 0 and "sort-packages": true prevents composer timeouts and ensures deterministic installs in CI.

.ahoy.yml (4)

33-36: Approve DB command chaining adjustments

Using && ensures commands execute sequentially on macOS and improves readability.


114-118: Approve lint command simplification

Running linters directly without copying config files reduces complexity and keeps the pipeline DRY.


122-123: Approve lint-fix command cleanup

Removing redundant copy steps and running PHPCBF directly streamlines code style corrections.


150-151: Verify PCOV directory path for BDD coverage

Ensure -dpcov.directory=/app/src points to the correct source directory when running Behat coverage, as fixtures execute in /app/build.

composer.json (2)

50-54: 👍 Good addition of autoload-dev for test namespace

Mapping DrevOps\BehatSteps\Tests\ to tests/phpunit/src/ enables IDE discovery and Composer autoloading of the new test classes.
No action required.


39-42:

✅ Verification successful

Potential dependency conflict between PHPUnit 11 and Prophecy bridge

phpspec/prophecy-phpunit 2.x is only compatible with PHPUnit ≤ 9.x.
Requiring phpunit/phpunit": "^11" will cause Composer to enter a version-solving conflict or silently install an incompatible major of Prophecy (none exists yet).

Consider one of the following:

-        "phpspec/prophecy-phpunit": "^2.3",
-        "phpunit/phpunit": "^11",
+        "phpspec/prophecy-phpunit": "^3.0", # when released for PHPUnit ≥10
+        "phpunit/phpunit": "^10 || ^11"     # or pin to ^10 for now

Please run composer update --dry-run to verify the constraint graph before merging.


🏁 Script executed:

#!/bin/bash
set -e
# Fetch Prophecy bridge package metadata from Packagist and list PHPUnit constraints for v2.x releases
curl -s 'https://repo.packagist.org/p2/phpspec/prophecy-phpunit.json' | \
  jq -r '.packages["phpspec/prophecy-phpunit"][]
    | select(.version | test("^2\\."))
    | "\(.version) => PHPUnit constraint: \(.require["phpunit/phpunit"] // "none")"'

Length of output: 251


🏁 Script executed:

#!/bin/bash
set -e
URL='https://repo.packagist.org/p2/phpspec/prophecy-phpunit.json'

echo "====== Root keys ======"
curl -s "$URL" | jq 'keys'

echo "====== packages keys ======"
curl -s "$URL" | jq '.packages | keys'

echo "====== Fields in first version entry ======"
curl -s "$URL" | jq '.packages["phpspec/prophecy-phpunit"][0] | keys'

echo "====== require and require-dev for v2.x versions ======"
curl -s "$URL" | jq -r '
  .packages["phpspec/prophecy-phpunit"][]
  | select(.version | test("^2\\."))
  | "\(.version) => require: \((.require // {}) | keys | join(",")), require-dev: \((.["require-dev"] // {}) | keys | join(","))"'

Length of output: 1336


🏁 Script executed:

#!/bin/bash
set -e
URL="https://repo.packagist.org/p2/phpspec/prophecy-phpunit.json"

echo "v2.x versions and their phpunit/phpunit constraints:"
curl -s "$URL" | jq -r '
  .packages["phpspec/prophecy-phpunit"][] |
  select(.version | test("^2\\.")) |
  "\(.version)\t\(.require["phpunit/phpunit"] // "<none>")"'

Length of output: 411


🏁 Script executed:

#!/bin/bash
set -e
URL="https://repo.packagist.org/p2/phpspec/prophecy-phpunit.json"

echo "ALL VERSIONS:"
curl -s "$URL" | jq -r '.packages["phpspec/prophecy-phpunit"][] | .version'

echo
echo "VERSION => REQUIRE:"
curl -s "$URL" | jq -r '
  .packages["phpspec/prophecy-phpunit"][] |
  "\(.version) => \((.require // {}) | to_entries | map("\(.key)=\(.value)") | join(", "))"'

Length of output: 992


phpspec/prophecy-phpunit ^2.3 supports PHPUnit 11 – no conflict

The constraint "phpspec/prophecy-phpunit": "^2.3" will install v2.3.0, which declares support for phpunit/phpunit ^9.1 || ^10.1 || ^11.0. Requiring "phpunit/phpunit": "^11" therefore satisfies both constraints without issue.

No changes required in composer.json (lines 39–42).

$package_filtered["autoload"] = $package["autoload"];
$package_filtered["autoload-dev"]["psr-4"]["DrevOps\\BehatSteps\\"] = "../src/";

echo json_encode(array_replace_recursive($package_filtered, $fixture), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Inconsistent JSON encoding flags

The inline comment warns against JSON_UNESCAPED_SLASHES, yet the json_encode call includes it. This mismatch can break the subsequent sed path replacement. Remove JSON_UNESCAPED_SLASHES from the flags.

Comment on lines +29 to +47
php -r '
$package = json_decode(file_get_contents("/app/composer.json"), true);
$fixture = json_decode(file_get_contents("/app/build/composer.json"), true);

// Cherry-pick the required properties from the base composer.json.
$package_filtered["require-dev"] = $package["require"];

// Deps required to run Behat tests.
$package_filtered["require-dev"] = array_merge($package_filtered["require-dev"], array_filter($package["require-dev"], function ($ver, $name) {
return in_array($name, [
"drevops/behat-phpserver",
"drevops/behat-screenshot",
"dvdoug/behat-code-coverage",
]);
}, ARRAY_FILTER_USE_BOTH));
unset($package_filtered["require-dev"]["php"]);

$package_filtered["autoload"] = $package["autoload"];
$package_filtered["autoload-dev"]["psr-4"]["DrevOps\\BehatSteps\\"] = "../src/";

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider modularizing merge logic

Embedding multi-step PHP for composer-json merging directly in the shell script reduces readability and maintainability. Extract this block into a standalone PHP script (e.g., scripts/merge-fixture-composer.php) and invoke it from here.

Comment on lines +240 to +242
$actual = camel_to_snake($input, $separator);
$this->assertEquals($expected, $actual);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Nitpick: prefer assertSame when comparing strings

Using assertSame() (strict) instead of assertEquals() avoids accidental type juggling and gives slightly clearer failure messages for string tests.

-    $this->assertEquals($expected, $actual);
+    $this->assertSame($expected, $actual);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$actual = camel_to_snake($input, $separator);
$this->assertEquals($expected, $actual);
}
$actual = camel_to_snake($input, $separator);
$this->assertSame($expected, $actual);
}

@AlexSkrypnyk AlexSkrypnyk force-pushed the feature/docs-generator-tests branch from c8534c3 to 14b6ef2 Compare May 4, 2025 03:40
Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

♻️ Duplicate comments (5)
.circleci/config.yml (1)

35-40: Add timeouts to new test steps
The new “Run Unit tests with coverage” and “Run BDD tests with coverage” steps mirror existing steps but lack a no_output_timeout. To prevent CI hangs on long-running tests, add no_output_timeout: 30m to both.

.circleci/provision.sh (1)

28-49: 🧹 Nitpick (assertive)

Selective merge logic is solid, but modularizing it would improve maintainability.
The inline PHP block effectively cherry-picks dependencies and autoload entries, but embedding multi-step logic in the shell script reduces readability. Consider extracting this into a standalone PHP script (e.g., scripts/merge-composer.php) and invoking it here for clarity.

.ahoy.yml (1)

138-141: Enable PCOV for coverage reports.
The coverage command sets pcov.directory but does not enable PCOV. Without -dpcov.enabled=1, coverage may not be generated. Apply:

- ahoy cli "php -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
+ ahoy cli "php -dpcov.enabled=1 -d pcov.directory=. ./vendor/bin/phpunit -c phpunit.xml $@"
tests/phpunit/src/DocsTest.php (2)

26-30: Load docs.php once via PHPUnit bootstrap instead of every test

Including the script inside setUp() re-executes the file before every test method, wasting I/O and hiding fatal errors behind dozens of stack traces.
Move the include to phpunit.xml (<phpunit bootstrap="docs.php">) or Composer autoload so it is executed exactly once.

(This was noted in an earlier review)


409-414: 🛠️ Refactor suggestion

Check mkdir() return value to surface permission problems

If the directory cannot be created (e.g. read-only FS in CI) the test continues and fails later in a non-obvious place.
Capture the boolean result and assert success:

-mkdir($trait_dir, 0777, true);
-mkdir($features_dir, 0777, true);
+self::assertTrue(
+  is_dir($trait_dir) || mkdir($trait_dir, 0777, true),
+  "Failed to create $trait_dir"
+);
+self::assertTrue(
+  is_dir($features_dir) || mkdir($features_dir, 0777, true),
+  "Failed to create $features_dir"
+);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between c8534c3 and 14b6ef2.

📒 Files selected for processing (12)
  • .ahoy.yml (4 hunks)
  • .circleci/config.yml (1 hunks)
  • .circleci/provision.sh (1 hunks)
  • README.md (2 hunks)
  • composer.json (2 hunks)
  • phpcs.xml (1 hunks)
  • phpstan.neon (1 hunks)
  • phpunit.xml (1 hunks)
  • rector.php (1 hunks)
  • tests/behat/fixtures/d10/.gitignore (1 hunks)
  • tests/behat/fixtures/d10/composer.json (3 hunks)
  • tests/phpunit/src/DocsTest.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/phpunit/src/DocsTest.php (2)
tests/phpunit/src/UnitTestCase.php (1)
  • UnitTestCase (12-14)
docs.php (6)
  • parse_method_comment (206-297)
  • camel_to_snake (462-479)
  • array_to_markdown_table (524-536)
  • render_info (310-382)
  • validate (393-449)
  • replace_content (493-511)
🔇 Additional comments (25)
phpcs.xml (2)

23-26: Include PHPUnit tests in PHPCS scanning
Adding tests/phpunit/src to the <file> paths ensures your new unit tests are analyzed by PHPCS, and removing the ../ prefix makes the paths relative to the repo root—this aligns with other configuration updates.


29-30: Exclude updated CircleCI config patterns
Removing the ../ prefix from the <exclude-pattern> entries correctly matches the current file locations for CircleCI configs.

tests/behat/fixtures/d10/.gitignore (1)

1-3: Review .gitignore entries for the fixture
Ignoring composer.lock and vendor/ is appropriate to keep the fixture directory clean. However, confirm whether .gitattributes should indeed be ignored—sometimes it's beneficial to keep it versioned to enforce consistent file handling.

README.md (1)

142-146: Good use of language identifier
Including bash on the unit test code block ensures proper syntax highlighting and readability.

.circleci/provision.sh (1)

48-48: Ensure JSON_UNESCAPED_SLASHES does not interfere with path adjustments.
You’re using JSON_UNESCAPED_SLASHES; confirm that the subsequent sed substitution still matches correctly, or adjust the regex if needed.

phpstan.neon (4)

12-15: Paths updated for new test sources.
Including tests/phpunit/src and docs.php in paths aligns with the added unit tests and code under analysis. This ensures PHPStan will analyze the new test sources and documentation utilities.


20-21: Exclude generated Behat context.
Ignoring tests/behat/bootstrap/BehatCliContext.php reduces noise from automatically generated context classes.


25-28: Register PHPStan extension directories.
Adding vendor/phpunit/phpunit and vendor/alexskrypnyk/phpunit-helpers under scanDirectories is correct for discovering PHPUnit extensions and custom helpers.


29-37: Ignore type annotation errors in test code.
Suppressing “no value type specified in iterable type” errors in tests/phpunit/* acknowledges that test methods often omit docblock parameter types. This keeps analysis focused on production code.

phpunit.xml (5)

1-15: Review PHPUnit baseline settings.
The configuration enables strict failure modes, caching, and execution ordering, aligning with best practices for test reliability and performance.


17-20: Define default test suite.
Pointing the default testsuite at tests/phpunit/src/ correctly scopes your unit tests.


21-30: Configure coverage source inclusion/exclusion.
Including docs.php and excluding the test directory ensures coverage metrics focus on production code.


31-38: Coverage report formats set.
HTML and Cobertura reports with defined thresholds facilitate both human inspection and CI integration.


39-41: JUnit logging for CI.
Generating JUnit XML output in .logs/phpunit/junit.xml integrates seamlessly with CI pipelines.

tests/behat/fixtures/d10/composer.json (5)

5-5: Project type is appropriate for a fixture.
Changing "type" to "project" aligns with how this composer.json functions as a standalone Drupal site.


23-23: Verify necessity of webflo/drupal-finder.
The webflo/drupal-finder package helps locate Drupal roots, but confirm it’s used by your provisioning or test setup. Remove it if it’s not required by your fixture.


26-27: Minimal dev dependency set.
Including only drupal/core-dev keeps the fixture lean while satisfying Drupal’s development requirements.


45-47: Configuration keys updated.
Setting "process-timeout": 0 and enabling "sort-packages" improves install reliability and consistency.


54-55: Allow PHPStan extension installer plugin.
Granting permission for phpstan/extension-installer matches the static analysis configuration and supports custom extensions.

.ahoy.yml (5)

9-15: Improve the dependency install check in the build command.
Currently, it checks for the host's vendor directory before running composer install inside the CLI container. This could skip installation if the host directory exists but is incomplete. Consider verifying a more specific indicator (like a lockfile or the presence of key binaries) to ensure dependencies are installed correctly.


34-37: Fixed macOS DB command chaining.
The updated use of mdfind and conditional chaining for Sequel Ace improves compatibility on Darwin systems. This reads cleanly and exits gracefully when not supported.


115-118: Simplified lint command.
Removing redundant file-copy steps and running tools directly via the CLI container streamlines the lint workflow.


123-124: Streamlined lint-fix command.
Executing Rector and PHP Code Beautifier directly in the CLI context enhances maintainability.


146-149: Verify PCOV directory for BDD coverage.
The pcov.directory for BDD tests is set to /app/src, but tests are executed in /app/build. Confirm this path points to the correct source location to ensure accurate coverage metrics.

composer.json (1)

50-54: Autoload-dev path looks correct — nice one

tests/phpunit/src/ is now discoverable under DrevOps\BehatSteps\Tests\ which lets IDEs and PHPUnit resolve test classes without extra bootstrap glue.

@@ -30,8 +29,7 @@
use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector;

return static function (RectorConfig $rectorConfig): void {
$drupalFinder = new DrupalFinderComposerRuntime();
$drupalRoot = $drupalFinder->getDrupalRoot();
$drupalRoot = 'build/web';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Simplify Drupal root configuration
Switching to a static $drupalRoot = 'build/web'; streamlines the setup and removes the dependency on runtime detection. Please verify that build/web exists in all environments (CI and local) and update any related documentation or scripts accordingly. You may also consider removing the now-unused imports for the Drupal set lists since those sets have been dropped.


🏁 Script executed:

#!/bin/bash
# Check if the build/web directory exists in the repo
echo "Checking for build/web directory:"
if [ -d build/web ]; then
  echo "✅ build/web exists"
else
  echo "❌ build/web not found"
fi

# Locate drupalRoot assignment(s)
echo -e "\nSearching for drupalRoot assignments:"
rg "drupalRoot" -n rector.php

# Show the top of rector.php to inspect imports and context
echo -e "\nDisplaying first 100 lines of rector.php:"
sed -n '1,100p' rector.php

# Look for imported SetList classes in rector.php
echo -e "\nSearching for SetList imports in rector.php:"
grep -R "use .*SetList" -n rector.php || echo "No SetList imports found"

# Search globally for any SetList references to see if they’re still in use
echo -e "\nGlobal search for SetList references:"
rg "SetList" -n .

Length of output: 4314


Verify drupalRoot and clean up unused imports

  • The build/web directory isn’t present in the repo — confirm it’s generated or exists in both CI and local environments, and update any documentation or scripts that depend on it.
  • In rector.php, remove the now-unused Drupal set list imports at the top of the file (lines 15–17):
- use DrupalRector\Set\Drupal10SetList;
- use DrupalRector\Set\Drupal8SetList;
- use DrupalRector\Set\Drupal9SetList;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$drupalRoot = 'build/web';
- use DrupalRector\Set\Drupal10SetList;
- use DrupalRector\Set\Drupal8SetList;
- use DrupalRector\Set\Drupal9SetList;

Comment on lines +134 to +141
There are two types of tests in this repository: unit tests and Behat tests.

#### Unit tests

Unit tests are run using PHPUnit installed in the root of the repository and
are independent of the Drupal version. This allows us to use the latest
features of PHPUnit.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Normalize heading level for Unit tests
The new test section intro is clear, but using #### Unit tests makes it one level deeper than top-level sections. Change it to ### Unit tests for consistent hierarchy.

Comment on lines +29 to +30
$package = json_decode(file_get_contents("/app/composer.json"), true);
$fixture = json_decode(file_get_contents("/app/build/composer.json"), true);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add error handling for JSON parsing.
If json_decode fails, $package or $fixture may be null, leading to invalid output. Consider validating the result of json_decode and exiting with a descriptive error if parsing fails.

Comment on lines +134 to +137
test-unit:
usage: Run Unit tests.
cmd: ahoy cli "./vendor/bin/phpunit -c phpunit.xml --no-coverage $@"

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Ensure dependencies before running unit tests.
The test-unit command assumes vendor/bin/phpunit is present. For a smoother developer experience, consider adding a pre-check to install dependencies if missing:

[ ! -f vendor/bin/phpunit ] && composer install --prefer-dist --no-progress --no-suggest --no-interaction

Comment on lines +26 to +44
"require-dev": {
"alexskrypnyk/phpunit-helpers": "^0.5.1",
"cweagans/composer-patches": "^1.7",
"dantleech/gherkin-lint": "^0.2.3",
"dealerdirect/phpcodesniffer-composer-installer": "^1",
"drevops/behat-phpserver": "^2.1.1",
"drevops/behat-screenshot": "^2.1",
"drupal/coder": "^8.3.28",
"dvdoug/behat-code-coverage": "^5.3.2.1",
"ergebnis/composer-normalize": "^2.47",
"mglaman/phpstan-drupal": "^1.3.7", 10000
"php-parallel-lint/php-parallel-lint": "^1.4",
"phpcompatibility/php-compatibility": "^9.3.5",
"phpspec/prophecy-phpunit": "^2.3",
"phpstan/extension-installer": "^1.4.3",
"phpstan/phpstan": "^1.12.25",
"phpunit/phpunit": "^11",
"rector/rector": "^1.2"
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider pinning dev-tools to patch versions to keep CI deterministic

Almost every entry in "require-dev" is specified with a loose ^ constraint (major version float).
Because these packages are used only for QA / CI, unexpected minor/patch upgrades can suddenly break the pipeline (PHPUnit, Rector, PHP-Stan, etc.). A common practice is:

  • lock large tools to an exact patch version ("phpunit/phpunit": "11.1.2"),
  • bump them deliberately in a dedicated “Update tools” PR.

This keeps builds reproducible and makes regressions easier to bisect.
If you prefer the current policy, feel free to ignore.

Comment on lines +239 to +242
public function testCamelToSnake(string $input, string $expected, string $separator = '_'): void {
$actual = camel_to_snake($input, $separator);
$this->assertEquals($expected, $actual);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Prefer assertSame() for string comparisons to avoid type juggling

assertEquals() performs loose comparison; for pure strings the strict variant is safer and yields clearer diff output.

-$this->assertEquals($expected, $actual);
+$this->assertSame($expected, $actual);

Apply to all string-only assertions in testCamelToSnake, testArrayToMarkdownTable, and testReplaceContent.

Also applies to: 313-315, 652-654

Comment on lines +427 to +428
$src_file_path = $base_path . DIRECTORY_SEPARATOR . 'src/MissingTrait.php';
@unlink($src_file_path);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Avoid silencing errors with @unlink

The error-control operator suppresses useful diagnostics if the file cannot be removed.
Either skip the call when the file does not exist or assert its success:

-@unlink($src_file_path);
+if (file_exists($src_file_path)) {
+  self::assertTrue(unlink($src_file_path), "Failed to remove $src_file_path");
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$src_file_path = $base_path . DIRECTORY_SEPARATOR . 'src/MissingTrait.php';
@unlink($src_file_path);
$src_file_path = $base_path . DIRECTORY_SEPARATOR . 'src/MissingTrait.php';
if (file_exists($src_file_path)) {
self::assertTrue(unlink($src_file_path), "Failed to remove $src_file_path");
}

Copy link
codecov bot commented May 4, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 81.57%. Comparing base (362f2a8) to head (cfb3cd5).
Report is 2 commits behind head on 3.x.

Additional details and impacted files
@@           Coverage Diff           @@
##              3.x     #383   +/-   ##
=======================================
  Coverage   81.57%   81.57%           
=======================================
  Files          31       31           
  Lines        1677     1677           
=======================================
  Hits         1368     1368           
  Misses        309      309           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@AlexSkrypnyk AlexSkrypnyk force-pushed the feature/docs-generator-tests branch from 14b6ef2 to cfb3cd5 Compare May 4, 2025 03:49
@AlexSkrypnyk AlexSkrypnyk merged commit 1673c87 into 3.x May 4, 2025
4 checks passed
@AlexSkrypnyk AlexSkrypnyk deleted the feature/docs-generator-tests branch May 4, 2025 03:57
@coderabbitai coderabbitai bot mentioned this pull request May 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant
0