diff --git a/.github/workflows/props-bot.yml b/.github/workflows/props-bot.yml deleted file mode 100644 index 61eca3e..0000000 --- a/.github/workflows/props-bot.yml +++ /dev/null @@ -1,92 +0,0 @@ -name: Props Bot - -on: - # This event runs anytime a PR is (re)opened, updated, marked ready for review, or labeled. - # GitHub does not allow filtering the `labeled` event by a specific label. - # However, the logic below will short-circuit the workflow when the `props-bot` label is not the one being added. - # Note: The pull_request_target event is used instead of pull_request because this workflow needs permission to comment - # on the pull request. Because this event grants extra permissions to `GITHUB_TOKEN`, any code changes within the PR - # should be considered untrusted. See https://securitylab.github.com/research/github-actions-preventing-pwn-requests/. - pull_request_target: - types: - - opened - - synchronize - - reopened - - labeled - - ready_for_review - # This event runs anytime a comment is added or deleted. - # You cannot filter this event for PR comments only. - # However, the logic below does short-circuit the workflow for issues. - issue_comment: - types: - - created - # This event will run everytime a new PR review is initially submitted. - pull_request_review: - types: - - submitted - # This event runs anytime a PR review comment is created or deleted. - pull_request_review_comment: - types: - - created - -# Cancels all previous workflow runs for pull requests that have not completed. -concurrency: - # The concurrency group contains the workflow name and the branch name for pull requests - # or the commit hash for any other events. - group: ${{ github.workflow }}-${{ contains( fromJSON( '["pull_request_target", "pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && github.head_ref || github.sha }} - cancel-in-progress: true - -# Disable permissions for all available scopes by default. -# Any needed permissions should be configured at the job level. -permissions: {} - -jobs: - # Compiles a list of props for a pull request. - # - # Performs the following steps: - # - Collects a list of contributor props and leaves a comment. - # - Removes the props-bot label, if necessary. - props-bot: - name: Generate a list of props - runs-on: ubuntu-24.04 - permissions: - # The action needs permission `write` permission for PRs in order to add a comment. - pull-requests: write - contents: read - timeout-minutes: 20 - # The job will run when pull requests are open, ready for review and: - # - # - A comment is added to the pull request. - # - A review is created or commented on (unless PR originates from a fork). - # - The pull request is opened, synchronized, marked ready for review, or reopened. - # - The `props-bot` label is added to the pull request. - if: | - ( - github.event_name == 'issue_comment' && github.event.issue.pull_request || - ( contains( fromJSON( '["pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && ! github.event.pull_request.head.repo.fork ) || - github.event_name == 'pull_request_target' && github.event.action != 'labeled' || - 'props-bot' == github.event.label.name - ) && - ( ! github.event.pull_request.draft && github.event.pull_request.state == 'open' || ! github.event.issue.draft && github.event.issue.state == 'open' ) - - steps: - - name: Gather a list of contributors - uses: WordPress/props-bot-action@trunk - with: - format: 'git' - - - name: Remove the props-bot label - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - if: ${{ github.event.action == 'labeled' && 'props-bot' == github.event.label.name }} - with: - retries: 2 - retry-exempt-status-codes: 418 - script: | - github.rest.issues.removeLabel({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: process.env.ISSUE_NUMBER, - name: 'props-bot' - }); - env: - ISSUE_NUMBER: ${{ github.event.number }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 12af84a..eff3b5e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,47 +20,81 @@ on: # - cron: '0 0 * * *' # Every 30 minutes. # - cron: '0/30 * * * *' + push: + branches: + - main workflow_dispatch: + inputs: + test_group: + description: 'Run only tests in this @group. Defaults to full suite.' + required: false + default: '' + type: choice + options: + - '' + - actions + - canonical + - comment + - cron + - db + - feed + - filters + - formatting + - http + - image + - l10n + - media + - ms-site + - option + - post + - query + - rest-api + - rewrite + - taxonomy + - themes + - upload + - user + - utf8 + test_filter: + description: 'PHPUnit --filter pattern — matches against class and method names. Examples: Tests_DB, Tests_Options, Tests_Post_Types::test_register. Overrides test_group if set.' + required: false + default: '' -# Cancels all previous workflow runs for pull requests that have not completed. +# Only one run at a time — prevents simultaneous runs from conflicting +# over the same wptests_* tables on the shared Pantheon environment. concurrency: - # The concurrency group contains the workflow name and the branch name for pull requests - # or the commit hash for any other events. - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + group: ${{ github.workflow }} cancel-in-progress: true jobs: - # Tests the PHPUnit test runner. + # Runs the WordPress PHPUnit test suite on the Pantheon environment via Terminus. # - # Performs the following steps: - # - Checks out the repository. - # - Installs PHP. - # - Installs NodeJS 14 with caching configured. - # - Prepares the environment for tests. - # - Runs the tests. - # - Reports the results. - # - Cleans up. + # Flow: + # 1. Prepare: git clone wordpress-develop locally, rsync to Pantheon, run composer on Pantheon. + # 2. Test: run PHPUnit on Pantheon via terminus remote:wp eval --skip-wordpress. + # 3. Report: rsync results from Pantheon, upload to WordPress.org. + # 4. Cleanup: remove test dir on Pantheon and locally. test: name: Run Core PHPUnit tests runs-on: ubuntu-latest - - # Remove this line if Github Actions is your preferred means of running the tests. - if: ${{ false }} + timeout-minutes: 120 env: - # This is only a subset/example of env vars available. See the `.env.default` file for a full list. WPT_PREPARE_DIR: ${{ secrets.WPT_PREPARE_DIR }} WPT_TEST_DIR: ${{ secrets.WPT_TEST_DIR }} WPT_REPORT_API_KEY: ${{ secrets.WPT_REPORT_API_KEY }} - WPT_PHP_EXECUTABLE: ${{ secrets.WPT_PHP_EXECUTABLE }} - # Database settings - WPT_DB_NAME: ${{ secrets.WPT_DB_NAME }} - WPT_DB_USER: ${{ secrets.WPT_DB_USER }} - WPT_DB_PASSWORD: ${{ secrets.WPT_DB_PASSWORD }} - WPT_DB_HOST: ${{ secrets.WPT_DB_HOST }} - # SSH settings for connecting to the test environment. - WPT_SSH_CONNECT: ${{ secrets.WPT_SSH_CONNECT }} + # PHP binary on the Pantheon container — use 'php' so it follows whatever + # version the environment is configured to run, without hardcoding a version. + WPT_PHP_EXECUTABLE: php + # SSH key for Terminus SSH operations (remote:wp, remote:composer). WPT_SSH_PRIVATE_KEY_BASE64: ${{ secrets.WPT_SSH_PRIVATE_KEY_BASE64 }} + # Pantheon-specific variables. + PANTHEON_SITE_NAME: ${{ secrets.PANTHEON_SITE_NAME }} + PANTHEON_SITE_ENV: ${{ secrets.PANTHEON_SITE_ENV }} + TERMINUS_MACHINE_TOKEN: ${{ secrets.TERMINUS_MACHINE_TOKEN }} + # Optional test scoping — set via workflow_dispatch inputs. + WPT_TEST_GROUP: ${{ inputs.test_group }} + WPT_TEST_FILTER: ${{ inputs.test_filter }} steps: - name: Checkout repository @@ -69,7 +103,7 @@ jobs: - name: Set up PHP uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 with: - php-version: '7.4' + php-version: '8.4' coverage: none - name: Install NodeJS @@ -77,6 +111,23 @@ jobs: with: node-version: 20 + - name: Install Terminus + uses: pantheon-systems/terminus-github-actions@409451ede17f75acac08f42edc823fee6c435057 # v1 + with: + pantheon-machine-token: ${{ secrets.TERMINUS_MACHINE_TOKEN }} + + - name: Install Terminus plugins + run: | + terminus self:plugin:install pantheon-systems/terminus-composer-plugin + + - name: Wake and configure Pantheon environment + run: | + terminus art wordpress + terminus env:wake ${{ secrets.PANTHEON_SITE_NAME }}.${{ secrets.PANTHEON_SITE_ENV }} + terminus site:info ${{ secrets.PANTHEON_SITE_NAME }} + terminus env:info ${{ secrets.PANTHEON_SITE_NAME }}.${{ secrets.PANTHEON_SITE_ENV }} + terminus connection:set ${{ secrets.PANTHEON_SITE_NAME }}.${{ secrets.PANTHEON_SITE_ENV }} sftp + - name: Prepare environment run: php prepare.php diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..3f8f7ed --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @pantheon-systems/devrel diff --git a/README.md b/README.md index 5baa664..ad96bdb 100644 --- a/README.md +++ b/README.md @@ -1,395 +1,79 @@ -# PHPUnit Test Runner +# WordPress PHPUnit Test Runner — Pantheon -Thanks for running the WordPress PHPUnit test suite on your infrastructure. We appreciate you helping to ensure WordPress’s compatibility for your users. +This is Pantheon's fork of the [WordPress PHPUnit Test Runner](https://github.com/WordPress/phpunit-test-runner), adapted to run the WordPress core hosting test suite on a Pantheon site and report results to the [WordPress.org hosting test results page](https://make.wordpress.org/hosting/test-results/). -If you haven't already, [please first read through the "Getting Started" documentation](https://make.wordpress.org/hosting/handbook/tests/). +The Pantheon site used as the test target runs the empty WordPress upstream (`empty-wp`). -The test suite runner is designed to be used without any file modification. Configuration happens with a series of environment variables (see [.env.default](.env.default) for an annotated overview). +For general background on the hosting tests, see the [Getting Started documentation](https://make.wordpress.org/hosting/handbook/tests/). -At a high level, the test suite runner: +## How it works -1. Prepares the test environment for the test suite. -2. Runs the PHPUnit tests in the test environment. -3. Reports the PHPUnit test results to WordPress.org -4. Cleans up the test suite environment. +Tests run directly on the Pantheon site via Terminus. The workflow: -## Setup +1. **Prepare** — clones `wordpress-develop` on the Pantheon site via `terminus remote:wp eval`, generates `wp-tests-config.php` using Pantheon's internal DB credentials, and installs PHPUnit dependencies via `terminus remote:composer`. +2. **Test** — runs the full WordPress PHPUnit suite on the Pantheon site via `terminus remote:wp eval`. +3. **Report** — retrieves results from the Pantheon site, fetches the current WordPress SVN revision, and uploads to WordPress.org. +4. **Cleanup** — removes the test directory from the Pantheon site. -The test suite runner can be used in one of two ways: +## GitHub Actions secrets -1. With GitHub Actions, (or Travis, Circle, or another CI service) as the controller that connects to the remote test environment. -2. With the runner cloned to and run directly within the test environment. +| Secret | Description | +|--------|-------------| +| `PANTHEON_SITE_NAME` | Pantheon site name (e.g. `my-site`) | +| `PANTHEON_SITE_ENV` | Pantheon environment (e.g. `dev`) | +| `TERMINUS_MACHINE_TOKEN` | Terminus machine token for the Pantheon account that owns the site | +| `WPT_SSH_PRIVATE_KEY_BASE64` | RSA private key (base64-encoded) registered on the Pantheon account — required for `terminus remote:wp` and `terminus remote:composer` | +| `WPT_PREPARE_DIR` | Local GHA path for temporary files (e.g. `/tmp/wp-test-runner`) | +| `WPT_TEST_DIR` | Path on the Pantheon site where tests run (e.g. `/code/wp-test-runner`) | +| `WPT_REPORT_API_KEY` | WordPress.org API key in `username:password` format | -The test runner is configured through environment variables, documented in [`.env.default`](.env.default). It shouldn't need any code modifications; in fact, please refrain from editing the scripts entirely, as it will make it easier to stay up to date. +## Running the tests -With a direct Git clone, you can: +### Scheduled runs -```bash -# Copy the default .env file. -cp .env.default .env -# Edit the .env file to define your variables. -vim .env -# Load your variables into scope. -source .env -``` - -In a CI service, you can set these environment variables through the service's web console. Importantly, the `WPT_SSH_CONNECT` environment variable determines whether the test suite is run locally or against a remote environment. - -Concurrently run tests in the same environment by appending build ids to the test directory and table prefix: - -```bash -export WPT_TEST_DIR=wp-test-runner-$TRAVIS_BUILD_NUMBER -export WPT_TABLE_PREFIX=wptests_$TRAVIS_BUILD_NUMBER\_ -``` - -Connect to a remote environment over SSH by having the CI job provision the SSH key: - -```bash -# 1. Create a SSH key pair for the controller to use -ssh-keygen -t rsa -b 4096 -C "travis@travis-ci.org" -# 2. base64 encode the private key for use with the environment variable -cat ~/.ssh/id_rsa | base64 --wrap=0 -# 3. Append id_rsa.pub to authorized_keys so the CI service can SSH in -cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys -``` - -Use a more complex SSH connection process by creating an SSH alias: - -```bash -# 1. Add the following to ~/.ssh/config to create a 'wpt' alias -Host wpt - Hostname 123.45.67.89 - User wpt - Port 1234 -# 2. Use 'wpt' wherever you might normally use a SSH connection string -ssh wpt -``` - -## Running - -The test suite runner is run in four steps. This explanation is for the local execution. - -### Requirements - -To use the Runner, the following is required (testing WordPress 6.5): - -- Server / hosting (infrastructure) with the usual configuration you use -- A database where you can test (tables will be created and destroyed several times) -- PHP 7.2+ -- MySQL 5.5.5+ / MariaDB 5.5.5+ -- NodeJS 20.x / npm 10.x / grunt -- PHP Composer -- Git, RSync, WGet, UnZip - -Test environment: - -- Writable filesystem for the entire test directory (see [#40910](https://core.trac.wordpress.org/ticket/40910)). -- Run with a non-root user, both for security and practical purposes (see [#44233](https://core.trac.wordpress.org/ticket/44233#comment:34)/[#46577](https://core.trac.wordpress.org/ticket/46577)). - -#### Database creation - -_This is an example for MySQL / MariaDB._ - -```sql -CREATE DATABASE wordpressdatabase CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci; -GRANT ALL ON wordpressdatabase.* TO 'wordpressusername'@'localhost' IDENTIFIED BY 'wordpresspassword'; -GRANT ALL ON wordpressdatabase.* TO 'wordpressusername'@'127.0.0.1' IDENTIFIED BY 'wordpresspassword'; -FLUSH PRIVILEGES; -``` - -#### NodeJS installation - -_This is an example for Debian / Ubuntu._ - -```bash -curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - -sudo apt -y install nodejs -sudo npm install -g npm@latest -nodejs --version -npm --version -``` +The workflow runs automatically on an hourly schedule. Results appear on the [WordPress.org hosting test results page](https://make.wordpress.org/hosting/test-results/). -#### PHP Composer +### Manual runs -_This is an example for Debian / Ubuntu._ +Trigger a run manually from **Actions → WordPress PHPUnit tests → Run workflow**. -```bash -curl -sS https://getcomposer.org/installer -o composer-setup.php -php composer-setup.php --install-dir=/usr/local/bin --filename=composer -composer --version -``` - -#### Git - -_This is an example for Debian / Ubuntu._ - -```bash -apt -y install git -git --version -``` - -### Installing the Test Runner +Two optional inputs are available for targeted runs: -First, download the software. This example uses `/home/wptestrunner/` folder, but set the best for this environment. +#### `test_group` (dropdown) -```bash -cd /home/wptestrunner/ -git clone https://github.com/WordPress/phpunit-test-runner.git -cd phpunit-test-runner/ -``` - -The next step will be to configure the environment. To do this, make a copy of the example file and then configure it. - -```bash -cp .env.default .env -vim .env -``` +Runs only tests tagged with a specific `@group` annotation. Useful for quickly validating a specific feature area without running the full ~29,000 test suite. Available groups include `post`, `query`, `user`, `taxonomy`, `comment`, `db`, `formatting`, `rest-api`, and others. -The content (in summary form) can be something like this: - -```bash -### -# Configuration environment variables used by the test runner -# -# # Create a copy for your local environment -# $ cp .env.default .env -# -# # Make any necessary changes to the default values -# $ vim .env -# -# # Load your variables into your environment -# $ source .env -### +Leave blank to run the full suite. -# Path to the directory where files can be prepared before being delivered to the environment. -export WPT_PREPARE_DIR=/tmp/wp-test-runner +#### `test_filter` -# Path to the directory where the WordPress develop checkout can be placed and tests can be run. -# When running tests in the same environment, set WPT_TEST_DIR to WPT_PREPARE_DIR -export WPT_TEST_DIR=/tmp/wp-test-runner +A PHPUnit `--filter` pattern matched against class and method names. More flexible than `test_group` — accepts any pattern PHPUnit's `--filter` supports. -# API key to authenticate with the reporting service in 'username:password' format. -export WPT_REPORT_API_KEY= +Examples: +- `Tests_DB` — all tests in the `Tests_DB` class +- `Tests_Options` — all options tests +- `Tests_Post_Types::test_register` — a specific method -# (Optionally) define an alternate reporting URL -export WPT_REPORT_URL= +If both inputs are set, `test_filter` takes precedence over `test_group`. -# Credentials for a database that can be written to and reset. -# WARNING!!! This database will be destroyed between tests. Only use safe database credentials. -# Please note that you must escape _or_ refrain from using # as special character in your credentials. -export WPT_DB_NAME= -export WPT_DB_USER= -export WPT_DB_PASSWORD= -export WPT_DB_HOST= +> **Note:** Partial runs still report to WordPress.org. Use these inputs for pipeline testing only, not as your regular scheduled run. -# (Optionally) set a custom table prefix to permit concurrency against the same database. -export WPT_TABLE_PREFIX=${WPT_TABLE_PREFIX-wptests_} +## Upstream sync -# (Optionally) define the PHP executable to be called -export WPT_PHP_EXECUTABLE=${WPT_PHP_EXECUTABLE-php} - -# (Optionally) define the PHPUnit command execution call. -# Use if `php phpunit.phar` can't be called directly for some reason. -export WPT_PHPUNIT_CMD= - -# (Optionally) define the command execution to remove the test directory -# Use if `rm -r` can't be called directly for some reason. -export WPT_RM_TEST_DIR_CMD= - -# SSH connection string (can also be an alias). -# Leave empty if tests are meant to run in the same environment. -export WPT_SSH_CONNECT= - -# Any options to be passed to the SSH connection -# Defaults to '-o StrictHostKeyChecking=no' -export WPT_SSH_OPTIONS= - -# SSH private key, base64 encoded. -export WPT_SSH_PRIVATE_KEY_BASE64= - -# Output logging -# Use 'verbose' to increase verbosity -export WPT_DEBUG= - -# Certificate validation -# Use 1 to validate, and 0 to not validate -export WPT_CERTIFICATE_VALIDATION=1 - -# WordPress flavor -# 0 = WordPress (simple version) -# 1 = WordPress Multisite -export WPT_FLAVOR=1 - -# Extra tests (groups) -# 0 = none -# 1 = ajax -# 2 = ms-files -# 3 = external-http -export WPT_EXTRATESTS=0 -``` - -Configure the folder where the WordPress software downloads and the database accesses will be made in order to prepare the tests. - -### Preparing the environment - -Before performing the first test, let’s update all the components. This process can be run before each test in this environment if wanted to keep it up to date, although it will depend more if it is in a production environment. +This fork tracks [WordPress/phpunit-test-runner](https://github.com/WordPress/phpunit-test-runner). To pull in upstream changes: ```bash -cd /home/wptestrunner/phpunit-test-runner/ -git pull -source .env -git checkout master +git fetch upstream +git merge upstream/master ``` -If you want to check a different branch, you can change it doing: - -```bash -git checkout example-branch -``` - -## Preparing the test - -Now there is the environment ready, run the test preparation. - -```bash -php prepare.php -``` - -The system will run a long series of installations, configurations and compilations of different elements in order to prepare the test. If warnings and warnings come out you should not worry too much, as it is quite normal. At the end of the process it will warn you if it needs something it doesn’t have. If it works, you should see something like this at the end: - -``` -Success: Prepared environment. -``` - -Now that the environment has been prepared, the next step is to run the tests for the first time. - -### Running the test - -Now that the environment is ready, let’s run the tests. To do this, execute the file that will perform it. - -```bash -php test.php -``` - -What do the symbols mean? - -`.` → Each dot means that the test has been passed correctly. - -`S` → It means the test has been skipped. This is usually because these tests are only valid in certain configurations. - -`F` → Means that the test has failed. Information about why this happened is displayed at the end. - -`E` → It means that the test has failed due to a PHP error, which can be an error, warning or notice. - -`I` → Means that the test has been marked as incomplete. - -If you follow these steps, everything should work perfectly and not make any mistakes. In case you get any error, it may be normal due to some missing adjustment or extension of PHP, among others. We recommend that you adjust the configuration until it works correctly. After all, this tool is to help you improve the optimal configuration for WordPress in that infrastructure. - -### Creating a report - -Even if the test has failed, a report will be made. The first one shows the information about our environment. Among the most important elements are the extensions that are commonly used in WordPress and some utilities that are also generally useful. - -```bash -cat /tmp/wp-test-runner/tests/phpunit/build/logs/env.json -``` - -The content of this file is somewhat similar to this: - -```bash -{ - "php_version": "7.4.5", - "php_modules": { - "bcmath": false, - "curl": "7.4.5", - "filter": "7.4.5", - "gd": false, - "libsodium": false, - "mcrypt": false, - "mod_xml": false, - "mysqli": "7.4.5", - "imagick": false, - "pcre": "7.4.5", - "xml": "7.4.5", - "xmlreader": "7.4.5", - "zlib": "7.4.5" - }, - "system_utils": { - "curl": "7.58.0 (x86_64-pc-linux-gnu) libcurl\/7.58.0 OpenSSL\/1.1.1g zlib\/1.2.11 libidn2\/2.3.0 libpsl\/0.19.1 (+libidn2\/2.0.4) nghttp2\/1.30.0 librtmp\/2.3", - "ghostscript": "", - "imagemagick": false, - "openssl": "1.1.1g 21 Apr 2020" - }, - "mysql_version": "mysql Ver 15.1 Distrib 10.4.12-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2", - "os_name": "Linux", - "os_version": "4.15.0-20-generic" -} -``` - -In addition to this report, a definitive file with all the information of what happened in the tests. This is the one that includes all the tests that are made (more than 10,000) giving information of the time that they take to be executed, problems that have arisen… - -```bash -cat /tmp/wp-test-runner/tests/phpunit/build/logs/junit.xml -``` - -At this point we can generate the reports by sending them to WordPress.org, if necessary. Even if you haven’t included the WordPress user (see below for how to create it), you can still run this file. - -```bash -php report.php -``` - -### Cleaning up the environment for other tests - -Having the tests working, all that remains is to delete all the files that have been created so that we can start over. To do this, execute the following command: - -```bash -php cleanup.php -``` - -### Automatic running - -The best way to run this test is to create a cron that runs everything. Having in mind that the tests can overlap, the best way can be using a systemd timer. - -```bash -cat > /etc/systemd/system/wordpressphpunittestrunner.service << EOF -[Unit] -Description=WordPress PHPUnit Test Runner -[Service] -Type=oneshot -ExecStart=cd /home/wptestrunner/phpunit-test-runner/ && source .env && php prepare.php && php test.php && php report.php && php cleanup.php -User=wptestrunner -Group=wptestrunner -EOF -``` - -```bash -cat > /etc/systemd/system/wordpressphpunittestrunner.timer << EOF -[Unit] -Description=WordPress PHPUnit Test Runner -[Timer] -OnCalendar=*-*-* *:*:00 -Persistent=true -[Install] -WantedBy=timers.target -EOF -``` - -```bash -systemctl daemon-reload -systemctl enable wordpressphpunittestrunner.timer -systemctl start wordpressphpunittestrunner.timer -systemctl status wordpressphpunittestrunner.timer -``` - -If you want to check how is everything working... - -```bash -journalctl -u wordpressphpunittestrunner.timer -journalctl -n 120 -u wordpressphpunittestrunner.service -``` +Conflicts will occur in `prepare.php`, `test.php`, `report.php`, `cleanup.php`, and the workflow — these files contain Pantheon-specific logic that differs from the upstream approach. Everything else should merge cleanly. ## Contributing -If you have questions about the process or run into test failures along the way, please [open an issue in the project repository](https://github.com/WordPress/phpunit-test-runner/issues) and we’ll help diagnose/get the documentation updated. Alternatively, you can also pop into the `#hosting` channel on [WordPress.org Slack](https://make.wordpress.org/chat/) for help. +For issues specific to this Pantheon fork, open an issue in this repository. For issues with the upstream test runner, open an issue in [WordPress/phpunit-test-runner](https://github.com/WordPress/phpunit-test-runner/issues). + +For questions about the WordPress hosting tests generally, visit the `#hosting` channel on [WordPress.org Slack](https://make.wordpress.org/chat/). ## License diff --git a/catalog-info.yaml b/catalog-info.yaml new file mode 100644 index 0000000..af21779 --- /dev/null +++ b/catalog-info.yaml @@ -0,0 +1,17 @@ +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: wporg-phpunit-test-runner + description: Runs WordPress core hosting tests for WordPress.org hosting test results listing + annotations: + github.com/project-slug: pantheon-systems/wporg-phpunit-test-runner + tags: + - wordpress + - testing + - phpunit + - hosting +spec: + type: tool + lifecycle: production + owner: devrel diff --git a/cleanup.php b/cleanup.php index a0d8ad0..dd76a20 100644 --- a/cleanup.php +++ b/cleanup.php @@ -1,47 +1,30 @@ trim( getenv( 'WPT_REPORT_API_KEY' ) ), // Miscellaneous 'WPT_DEBUG' => (bool) getenv( 'WPT_DEBUG' ), + // Pantheon-specific + 'PANTHEON_SITE_NAME' => trim( getenv( 'PANTHEON_SITE_NAME' ) ), + 'PANTHEON_SITE_ENV' => trim( getenv( 'PANTHEON_SITE_ENV' ) ), ) ); } diff --git a/prepare.php b/prepare.php index b58d7d6..2ed5c3b 100644 --- a/prepare.php +++ b/prepare.php @@ -1,112 +1,95 @@ > ~/.ssh/config', + 'echo " HostKeyAlgorithms +ssh-rsa" >> ~/.ssh/config', + 'echo " PubkeyAcceptedKeyTypes +ssh-rsa" >> ~/.ssh/config', + 'echo "StrictHostKeyChecking no" >> ~/.ssh/config', + ) ); } - /** - * Performs a series of operations to set up the test environment. This includes creating a preparation directory, - * cloning the WordPress development repository, and preparing the environment with npm. + * Fetch Pantheon's internal DB credentials and PHP version in one terminus call. + * Using internal credentials means tests connect to localhost — no latency. */ -// Prepare an array of shell commands to set up the testing environment. -perform_operations( array( - - // Create the preparation directory if it doesn't exist. The '-p' flag creates intermediate directories as required. - 'mkdir -p ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ), +log_message( 'Fetching Pantheon environment DB credentials and PHP version' ); +$info_php = 'echo json_encode(["host"=>getenv("DB_HOST"),"port"=>getenv("DB_PORT"),"name"=>getenv("DB_NAME"),"user"=>getenv("DB_USER"),"pass"=>getenv("DB_PASSWORD"),"php"=>PHP_VERSION]);'; +$info_json = trim( shell_exec( 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( $info_php ) . ' --skip-wordpress --quiet 2>/dev/null' ) ); +$pantheon = json_decode( $info_json, true ); - // Clone the WordPress develop repository from GitHub into the preparation directory. - // The '--depth=1' flag creates a shallow clone with a history truncated to the last commit. - 'git clone --depth=1 https://github.com/WordPress/wordpress-develop.git ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ), +if ( empty( $pantheon ) || empty( $pantheon['host'] ) ) { + error_message( 'Could not retrieve Pantheon environment info. Check Terminus authentication and site/env names.' ); +} - // Change directory to the preparation directory, install npm dependencies, and build the project. - 'cd ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ) . '; npm install && npm run build' +$env_php_version = $pantheon['php']; +$pantheon_db_host = $pantheon['host'] . ':' . $pantheon['port']; +$php_bin = 'php' . implode( '.', array_slice( explode( '.', $env_php_version ), 0, 2 ) ); -) ); +log_message( 'Pantheon PHP: ' . $env_php_version . ' (binary: ' . $php_bin . ')' ); +log_message( 'Pantheon DB host: ' . $pantheon_db_host ); -// Log a message indicating the start of the variable replacement process for configuration. -log_message( 'Replacing variables in wp-tests-config.php' ); +if ( version_compare( $env_php_version, '7.2', '<' ) ) { + error_message( 'The test runner is not compatible with PHP < 7.2.' ); +} /** - * Reads the contents of the WordPress test configuration sample file. - * This file contains template placeholders that need to be replaced with actual values - * from environment variables to configure the WordPress test environment. + * Clone wordpress-develop directly on Pantheon's container. + * Pantheon has git and outbound HTTPS, so this avoids any rsync/SSH-key dependency. + * npm build is intentionally skipped — PHP unit tests do not require compiled JS/CSS. */ -$contents = file_get_contents( $runner_vars['WPT_PREPARE_DIR'] . '/wp-tests-config-sample.php' ); +log_message( 'Cloning wordpress-develop on Pantheon' ); +$clone_cmd = 'rm -rf ' . escapeshellarg( $test_dir ) . ' && git clone --depth=1 https://github.com/WordPress/wordpress-develop.git ' . escapeshellarg( $test_dir ) . ' 2>&1'; +perform_operations( array( + 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( 'passthru(' . var_export( $clone_cmd, true ) . ');' ) . ' --skip-wordpress', +) ); /** - * Prepares a script to log system information relevant to the testing environment. - * The script checks for the existence of the log directory and creates it if it does not exist. - * It then collects various pieces of system information including PHP version, loaded PHP modules, - * MySQL version, operating system details, and versions of key utilities like cURL and OpenSSL. - * This information is collected in an array and written to a JSON file in the log directory. - * Additionally, if running from the command line during a WordPress installation process, - * it outputs the PHP version and executable path. + * Generate wp-tests-config.php locally using Pantheon's internal DB credentials, + * then upload it to Pantheon by base64-encoding it through terminus eval. + * This avoids any file transfer over SSH/rsync. */ +log_message( 'Generating wp-tests-config.php' ); +$sample_php = 'echo base64_encode(file_get_contents(' . var_export( $test_dir . '/wp-tests-config-sample.php', true ) . '));'; +$sample_b64 = trim( shell_exec( 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( $sample_php ) . ' --skip-wordpress --quiet 2>/dev/null' ) ); + +if ( empty( $sample_b64 ) ) { + error_message( 'Could not read wp-tests-config-sample.php from Pantheon. Did the git clone succeed?' ); +} + +$contents = base64_decode( $sample_b64 ); + $system_logger = <<query("SELECT VERSION()")->fetch_row()[0]; -//\$mysqli->close(); file_put_contents( __DIR__ . '/tests/phpunit/build/logs/env.json', json_encode( \$env, JSON_PRETTY_PRINT ) ); if ( 'cli' === php_sapi_name() && defined( 'WP_INSTALLING' ) && WP_INSTALLING ) { echo PHP_EOL; @@ -197,149 +177,35 @@ function curl_selected_bits(\$k) { return in_array(\$k, array('version', 'ssl_ve } EOT; -// Initialize a string that will be used to identify the database settings section in the configuration file. $logger_replace_string = '// ** Database settings ** //' . PHP_EOL; +$system_logger = $logger_replace_string . $system_logger; -// Prepend the logger script to the database settings identifier to ensure it gets included in the wp-tests-config.php file. -$system_logger = $logger_replace_string . $system_logger; - -// Define a string that will set the 'WP_PHP_BINARY' constant to the path of the PHP executable. -$php_binary_string = 'define( \'WP_PHP_BINARY\', \''. $runner_vars['WPT_PHP_EXECUTABLE'] . '\' );'; - -/** - * An associative array mapping configuration file placeholders to environment-specific values. - * This array is used in the subsequent str_replace operation to replace placeholders - * in the wp-tests-config-sample.php file with values from the environment or defaults if none are provided. - */ $search_replace = array( - 'wptests_' => trim( getenv( 'WPT_TABLE_PREFIX' ) ) ? : 'wptests_', - 'youremptytestdbnamehere' => trim( getenv( 'WPT_DB_NAME' ) ), - 'yourusernamehere' => trim( getenv( 'WPT_DB_USER' ) ), - 'yourpasswordhere' => trim( getenv( 'WPT_DB_PASSWORD' ) ), - 'localhost' => trim( getenv( 'WPT_DB_HOST' ) ), - 'define( \'WP_PHP_BINARY\', \'php\' );' => $php_binary_string, + 'wptests_' => trim( getenv( 'WPT_TABLE_PREFIX' ) ) ?: 'wptests_', + 'youremptytestdbnamehere' => $pantheon['name'], + 'yourusernamehere' => $pantheon['user'], + 'yourpasswordhere' => $pantheon['pass'], + 'localhost' => $pantheon_db_host, + 'define( \'WP_PHP_BINARY\', \'php\' );' => 'define( \'WP_PHP_BINARY\', \'' . $php_bin . '\' );', $logger_replace_string => $system_logger, ); -// Replace the placeholders in the wp-tests-config-sample.php file content with actual values. $contents = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $contents ); -// Write the modified content to the wp-tests-config.php file, which will be used by the test suite. -file_put_contents( $runner_vars['WPT_PREPARE_DIR'] . '/wp-tests-config.php', $contents ); - -/** - * Determines the PHP version of the test environment to ensure the correct version of PHPUnit is installed. - * It constructs a command that prints out the PHP version in a format compatible with PHPUnit's version requirements. - */ -$php_version_cmd = $runner_vars['WPT_PHP_EXECUTABLE'] . " -r \"print PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;\""; - -/** - * If an SSH connection string is provided, the command to determine the PHP version is modified - * to execute remotely over SSH. This is required if the test environment is not the local machine. - */ -if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { - // The PHP version check command is prefixed with the SSH command, including SSH options, - // and the connection string, ensuring the command is executed on the remote machine. - $php_version_cmd = 'ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] ) . ' ' . escapeshellarg( $php_version_cmd ); -} - -// Initialize return value variable for the exec function call. -$retval = 0; - -/** - * Executes the constructed command to obtain the PHP version of the test environment. - * The output is stored in $env_php_version, and the return value of the command execution is stored in $retval. - */ -$env_php_version = exec( $php_version_cmd, $output, $retval ); - -// Check if the command execution was successful by inspecting the return value. -if ( $retval !== 0 ) { - // If the return value is not zero, an error occurred, and a message is logged. - error_message( 'Could not retrieve the environment PHP Version.' ); -} - -// Log the obtained PHP version for confirmation and debugging purposes. -log_message( 'Environment PHP Version: ' . $env_php_version ); - -/** - * Checks if the detected PHP version is below 7.2. - * The test runner requires PHP version 7.2 or above, and if the environment's PHP version - * is lower, it logs an error message and could terminate the script. - */ -if ( version_compare( $env_php_version, '7.2', '<' ) ) { - // Logs an error message indicating the test runner's incompatibility with PHP versions below 7.2. - error_message( 'The test runner is not compatible with PHP < 7.2.' ); -} - -/** - * Use Composer to manage PHPUnit and its dependencies. - * This allows for better dependency management and compatibility. - */ - -// Check if Composer is installed and available in the PATH. -$composer_cmd = 'cd ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ) . ' && '; -$retval = 0; -$composer_path = escapeshellarg( system( 'which composer', $retval ) ); - -if ( $retval === 0 ) { - - // If Composer is available, prepare the command to use the Composer binary. - $composer_cmd .= $composer_path . ' '; - -} else { - - // If Composer is not available, download the Composer phar file. - log_message( 'Local Composer not found. Downloading latest stable ...' ); - - perform_operations( array( - 'wget -O ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] . '/composer.phar' ) . ' https://getcomposer.org/composer-stable.phar', - ) ); - - // Update the command to use the downloaded Composer phar file. - $composer_cmd .= $runner_vars['WPT_PHP_EXECUTABLE'] . ' composer.phar '; -} - -// Set the PHP version for Composer to ensure compatibility and update dependencies. +// Upload the generated config to Pantheon via base64 through terminus eval. +$config_b64 = base64_encode( $contents ); +$write_php = 'file_put_contents(' . var_export( $test_dir . '/wp-tests-config.php', true ) . ', base64_decode(' . var_export( $config_b64, true ) . ')); echo "Config written.\n";'; perform_operations( array( - $composer_cmd . 'config platform.php ' . escapeshellarg( $env_php_version ), - $composer_cmd . 'update', + 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( $write_php ) . ' --skip-wordpress', ) ); /** - * If an SSH connection is configured, use rsync to transfer the prepared files to the remote test environment. - * The -r option for rsync enables recursive copying to handle directory structures. - * Additional rsync options may be included for more verbose output if debugging is enabled. + * Run Composer on Pantheon to install PHPUnit and its dependencies. */ -if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { - // Initialize rsync options with recursive copying. - $rsync_options = '-r'; - - // If debug mode is set to verbose, append 'v' to rsync options for verbose output. - if ( $runner_vars['WPT_DEBUG'] ) { - $rsync_options = $rsync_options . 'v'; - } - - // Perform the rsync operation with the configured options and exclude patterns. - // This operation synchronizes the test environment with the prepared files, excluding - // version control directories and other non-essential files for test execution. - perform_operations( - array( - 'rsync ' . $rsync_options - . ' --exclude=".git/"' - . ' --exclude="node_modules/"' - . ' --exclude="composer.phar"' - . ' --exclude=".cache/"' - . ' --exclude=".devcontainer/"' - . ' --exclude=".github/"' - . ' --exclude="tools/"' - // Exclude all subdirectories in tests/ except phpunit/. - . ' --exclude="tests/*" --include="tests/phpunit/**"' - . ' -e "ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . '" ' - . escapeshellarg( trailingslashit( $runner_vars['WPT_PREPARE_DIR'] ) ) - . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] . ':' . $runner_vars['WPT_TEST_DIR'] ), - ) - ); -} +log_message( 'Running Composer on Pantheon' ); +perform_operations( array( + 'terminus remote:composer ' . $site_env . ' -- config platform.php ' . escapeshellarg( $env_php_version ) . ' --working-dir=' . escapeshellarg( $test_dir ), + 'terminus remote:composer ' . $site_env . ' -- update --working-dir=' . escapeshellarg( $test_dir ), +) ); -// Log a success message indicating that the environment has been prepared. log_message( 'Success: Prepared environment.' ); diff --git a/report.php b/report.php index 4265db0..7e42ba0 100644 --- a/report.php +++ b/report.php @@ -1,151 +1,134 @@ trim(shell_exec("git -C " . escapeshellarg(' . var_export( $test_dir, true ) . ') . " log -1 --pretty=%H 2>/dev/null")), "msg"=>trim(shell_exec("git -C " . escapeshellarg(' . var_export( $test_dir, true ) . ') . " log -1 --pretty=%s 2>/dev/null"))]);'; +$git_json = trim( shell_exec( 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( $git_php ) . ' --skip-wordpress --quiet 2>/dev/null' ) ); +$git_info = json_decode( $git_json, true ); +$hash = $git_info['hash'] ?? ''; +$message = $git_info['msg'] ?? ''; + +// The WordPress.org hosting test API expects an SVN revision number for 'commit' (e.g. 62519). +// Fetch the current trunk revision from the SVN WebDAV endpoint using curl (no svn client needed). +$svn_xml = shell_exec( 'curl -s --max-time 10 -X PROPFIND "https://develop.svn.wordpress.org/trunk" -H "Depth: 0" 2>/dev/null' ); +preg_match( '/<[^>]+version-name[^>]*>(\d+)/dev/null' ) ); +log_message( $ls_out ?: '(empty)' ); + +foreach ( array( 'junit.xml', 'env.json', 'testdox.txt' ) as $result_file ) { + log_message( 'Fetching ' . $result_file . ' ...' ); + // Gzip before base64 so large files (junit.xml can be 5MB+) don't overwhelm the terminus connection. + $read_php = 'if(file_exists(' . var_export( $logs_dir . $result_file, true ) . ')){echo base64_encode(gzencode(file_get_contents(' . var_export( $logs_dir . $result_file, true ) . ')));}else{echo "";}'; + $encoded = trim( shell_exec( 'terminus remote:wp ' . $site_env . ' -- eval ' . escapeshellarg( $read_php ) . ' --skip-wordpress --quiet 2>/dev/null' ) ); + if ( ! empty( $encoded ) ) { + $decoded = gzdecode( base64_decode( $encoded ) ); + file_put_contents( $logs_local . $result_file, $decoded ); + log_message( 'Retrieved ' . $result_file . ' (' . strlen( $decoded ) . ' bytes)' ); + } else { + log_message( 'Warning: ' . $result_file . ' not found on Pantheon.' ); + } +} /** - * Processes and uploads the junit.xml file. - * First, a log message is recorded to indicate the start of processing the junit.xml file. - * Then, the contents of the junit.xml file are read from the prepared directory into a string. - * This XML string is then passed to a function that processes the XML data, presumably to prepare - * it for upload or to extract relevant test run information. + * Process and upload results. */ -log_message( 'Processing and uploading junit.xml' ); -$xml = file_get_contents( $runner_vars['WPT_PREPARE_DIR'] . '/junit.xml' ); +log_message( 'Processing junit.xml' ); + +if ( ! file_exists( $logs_local . 'junit.xml' ) ) { + error_message( 'junit.xml not found — test run did not complete (probable PHP crash). This is a hard failure.' ); +} + +$xml = file_get_contents( $logs_local . 'junit.xml' ); $results = process_junit_xml( $xml ); -/** - * Retrieves environment details from a JSON file or generates them if not available. - * Initializes the environment details string. If an 'env.json' file exists in the prepared - * directory, its contents are read into the environment details string. If the file doesn't - * exist but the prepared directory is the same as the test directory, the environment details - * are generated by calling a function that retrieves these details, then encoded into JSON format. - */ $env = ''; -if ( file_exists( $runner_vars['WPT_PREPARE_DIR'] . '/env.json' ) ) { - $env = file_get_contents( $runner_vars['WPT_PREPARE_DIR'] . '/env.json' ); -} elseif ( $runner_vars['WPT_PREPARE_DIR'] === $runner_vars['WPT_TEST_DIR'] ) { - $env = json_encode( get_env_details(), JSON_PRETTY_PRINT ); +if ( file_exists( $logs_local . 'env.json' ) ) { + $env = file_get_contents( $logs_local . 'env.json' ); + log_message( 'env.json loaded' ); } /** - * Attempts to upload test results if an API key is available, otherwise logs the results locally. - * Checks if an API key for reporting is present. If so, it attempts to upload the test results - * using the `upload_results` function and processes the HTTP response. A success message is logged - * if the upload is successful, indicated by a 20x HTTP status code. If the upload fails, an error - * message is logged along with the HTTP status. If no API key is provided, it logs the test results - * and environment details locally. + * Write a GHA step summary with key run info. */ -if( ! empty( $runner_vars['WPT_REPORT_API_KEY'] ) ) { +$summary_file = getenv( 'GITHUB_STEP_SUMMARY' ); +if ( $summary_file ) { + $env_data = $env ? json_decode( $env, true ) : array(); + $summary = "## WordPress PHPUnit Test Results\n\n"; + $summary .= '| | |' . "\n" . '|---|---|' . "\n"; + $summary .= '| **Site** | ' . $PANTHEON_SITE_NAME . '.' . $PANTHEON_SITE_ENV . " |\n"; + $summary .= '| **Revision** | ' . ( $rev ?: 'unknown' ) . " |\n"; + $summary .= '| **Commit** | ' . ( $message ?: 'unknown' ) . " |\n"; + $summary .= '| **PHP** | ' . ( $env_data['php_version'] ?? 'unknown' ) . " |\n"; + $summary .= '| **MySQL** | ' . ( $env_data['mysql_version'] ?? 'unknown' ) . " |\n"; + file_put_contents( $summary_file, $summary, FILE_APPEND ); +} - // Upload the results and capture the HTTP status and response body - list( $http_status, $response_body ) = upload_results( $results, $rev, $message, $env, $runner_vars['WPT_REPORT_API_KEY'] ); +log_message( 'Uploading results' ); - // Decode the JSON response body - $response = json_decode( $response_body, true ); - if ( 20 == substr( $http_status, 0, 2 ) ) { +if ( ! empty( $runner_vars['WPT_REPORT_API_KEY'] ) ) { - // Construct and log a success message with a link if provided in the response - $message = 'Results successfully uploaded'; - $message .= isset( $response['link'] ) ? ': ' . $response['link'] : ''; - log_message( $message ); + list( $http_status, $response_body ) = upload_results( $results, $rev, $message, $env, $runner_vars['WPT_REPORT_API_KEY'] ); + $response = json_decode( $response_body, true ); + if ( 20 == substr( $http_status, 0, 2 ) ) { + $upload_msg = 'Results successfully uploaded'; + $upload_msg .= isset( $response['link'] ) ? ': ' . $response['link'] : ''; + log_message( $upload_msg ); + if ( $summary_file ) { + $link_line = isset( $response['link'] ) ? '| **Results** | [View on WordPress.org](' . $response['link'] . ") |\n" : ''; + file_put_contents( $summary_file, $link_line, FILE_APPEND ); + } } else { - - // Construct and log an error message with additional details if provided in the response - $message = 'Error uploading results'; - $message .= isset( $response['message'] ) ? ': ' . $response['message'] : ''; - $message .= ' (HTTP status ' . (int) $http_status . ')'; - error_message( $message ); - + $err = 'Error uploading results'; + $err .= isset( $response['message'] ) ? ': ' . $response['message'] : ''; + $err .= ' (HTTP ' . (int) $http_status . ')'; + error_message( $err ); } } else { - - // Log the test results and environment details locally if no API key is provided - log_message( '[+] TEST RESULTS' . "\n\n" . $results. "\n\n" ); + log_message( 'No API key — logging results locally only' ); + log_message( '[+] TEST RESULTS' . "\n\n" . $results . "\n\n" ); log_message( '[+] ENVIRONMENT' . "\n\n" . $env . "\n\n" ); - } diff --git a/test.php b/test.php index 67cf058..0dc620c 100644 --- a/test.php +++ b/test.php @@ -1,34 +1,29 @@