diff --git a/.env.default b/.env.default index 84de84c..991aceb 100644 --- a/.env.default +++ b/.env.default @@ -11,55 +11,69 @@ # $ source .env ### -# Path to the directory where files can be prepared before being delivered to the environment. -export WPT_PREPARE_DIR=/tmp/wp-test-runner +# Label for the environment. Can be empty (default) or be like "shared", "vps", +# "cloud" or similar. Please use only alphanumeric keywords, and try to be +# descriptive +export WPT_LABEL="" -# 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=wp-test-runner +# Path to the directory where files can be prepared before being delivered to +# the environment. +export WPT_PREPARE_DIR="/tmp/wp-test-runner" -# API key to authenticate with the reporting service in 'username:password' format. -export WPT_REPORT_API_KEY= +# 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" + +# API key to authenticate with the reporting service in 'username:password' +# format. +export WPT_REPORT_API_KEY="" # (Optionally) define an alternate reporting URL -export WPT_REPORT_URL= +export WPT_REPORT_URL="" # 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= - -# (Optionally) set a custom table prefix to permit concurrency against the same database. +# 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="" + +# (Optionally) set a custom table prefix to permit concurrency against the same +# database. export WPT_TABLE_PREFIX=${WPT_TABLE_PREFIX-wptests_} # (Optionally) define the PHP executable to be called export WPT_PHP_EXECUTABLE=${WPT_PHP_EXECUTABLE-php} +# (Optionally) array of versions +# like: "8.1=/bin/php8.1;8.2=/bin/php8.2;8.3=/bin/php8.3" +export WPT_PHP_EXECUTABLE_MULTI="" + # (Optionally) define the PHPUnit command execution call. # Use if `php phpunit.phar` can't be called directly for some reason. -export WPT_PHPUNIT_CMD= +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= +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= +export WPT_SSH_CONNECT="" # Any options to be passed to the SSH connection # Defaults to '-o StrictHostKeyChecking=no' -export WPT_SSH_OPTIONS= +export WPT_SSH_OPTIONS="" # SSH private key, base64 encoded. -export WPT_SSH_PRIVATE_KEY_BASE64= +export WPT_SSH_PRIVATE_KEY_BASE64="" # Output logging # Use 'verbose' to increase verbosity -export WPT_DEBUG= +export WPT_DEBUG="" # Certificate validation # Use 1 to validate, and 0 to not validate @@ -68,7 +82,7 @@ export WPT_CERTIFICATE_VALIDATION=1 # WordPress flavor # 0 = WordPress (simple version) # 1 = WordPress Multisite -export WPT_FLAVOR=1 +export WPT_FLAVOR=0 # Extra tests (groups) # 0 = none @@ -76,3 +90,8 @@ export WPT_FLAVOR=1 # 2 = ms-files # 3 = external-http export WPT_EXTRATESTS=0 + +# Check all commits +# 0 = latest +# 1 = all +export WPT_COMMITS=0 diff --git a/README.md b/README.md index 046dfad..815d6d0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,21 @@ +# About the PHPUnit Test Runner + +Hosting companies can have several to millions of websites hosted with WordPress, so it's important to make sure their configuration is as compatible as possible with the software. + +To verify this compatibility, the WordPress Community provides a series of PHPUnit tests with which to check the operation of WordPress in any environment. + +The Runner tests generates a report with the test results related to a bot user (a hosting company), and this captures and displays those test results at the [Host Test Result](https://make.wordpress.org/hosting/test-results/) page. + +## What's the phpunit-test-runner + +The [phpunit-test-runner](https://github.com/WordPress/phpunit-test-runner) is a tool designed to make it easier for hosting companies to run the WordPress project’s automated tests. + +There is a [whole documentation about this tool](https://make.wordpress.org/hosting/test-results-getting-started/). Also, if you want, you can make your test results appear in the [Host Test Results](https://make.wordpress.org/hosting/test-results/) page of WordPress. + +The tool can be run manually or through an automated system like Travis. To see how it works and the purpose of this document, will be shown how to run the tests manually. + +--- + # PHPUnit Test Runner Thanks for running the WordPress PHPUnit test suite on your infrastructure. We appreciate you helping to ensure WordPress’s compatibility for your users. @@ -13,7 +31,7 @@ At a high level, the test suite runner: 3. Reports the PHPUnit test results to WordPress.org 4. Cleans up the test suite environment. -## Setup +## Quick setup The test suite runner can be used in one of two ways: @@ -27,8 +45,10 @@ With a direct Git clone, you can: ```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 ``` @@ -47,8 +67,10 @@ Connect to a remote environment over SSH by having the CI job provision the SSH ```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 ``` @@ -61,21 +83,18 @@ 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 +## Requirements -To use the Runner, the following is required (testing WordPress 6.5): +To use the Runner, the following is required (testing WordPress 6.7-alpha): - 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.0+ (view ) +- PHP 7.2+ - MySQL 5.5+ / MariaDB 10.0+ - NodeJS 20.x / npm 10.x / grunt - PHP Composer @@ -86,9 +105,9 @@ 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 +### Database creation -_This is an example for MySQL / MariaDB._ +_This is a simple example for MySQL / MariaDB._ ```sql CREATE DATABASE wordpressdatabase CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci; @@ -97,9 +116,9 @@ GRANT ALL ON wordpressdatabase.* TO 'wordpressusername'@'127.0.0.1' IDENTIFIED B FLUSH PRIVILEGES; ``` -#### NodeJS installation +### NodeJS installation -_This is an example for Debian / Ubuntu._ +_This is a simple example for Debian / Ubuntu._ ```bash curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - @@ -109,9 +128,9 @@ nodejs --version npm --version ``` -#### PHP Composer +### PHP Composer -_This is an example for Debian / Ubuntu._ +_This is a simple example for Debian / Ubuntu._ ```bash curl -sS https://getcomposer.org/installer -o composer-setup.php @@ -119,35 +138,37 @@ php composer-setup.php --install-dir=/usr/local/bin --filename=composer composer --version ``` -#### Git +### Git -_This is an example for Debian / Ubuntu._ +_This is a simple example for Debian / Ubuntu._ ```bash apt -y install git git --version ``` -### Installing the Test Runner +## Installing the Runner -First, download the software. This example uses `/home/wptestrunner/` folder, but set the best for this environment. +First, download the software. This example use `/home/wptestrunner/` folder, but set the best for this environment. -```bash +``` cd /home/wptestrunner/ git clone https://github.com/WordPress/phpunit-test-runner.git cd phpunit-test-runner/ ``` +## Configuring the 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 ``` -The content (in summary form) can be something like this: +This is the default configuraton file: -```bash +``` ### # Configuration environment variables used by the test runner # @@ -161,55 +182,69 @@ The content (in summary form) can be something like this: # $ source .env ### -# Path to the directory where files can be prepared before being delivered to the environment. -export WPT_PREPARE_DIR=/tmp/wp-test-runner +# Label for the environment. Can be empty (default) or be like "shared", "vps", +# "cloud" or similar. Please use only alphanumeric keywords, and try to be +# descriptive +export WPT_LABEL="" + +# Path to the directory where files can be prepared before being delivered to +# the environment. +export WPT_PREPARE_DIR="/tmp/wp-test-runner" -# 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 +# 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" -# API key to authenticate with the reporting service in 'username:password' format. -export WPT_REPORT_API_KEY= +# API key to authenticate with the reporting service in 'username:password' +# format. +export WPT_REPORT_API_KEY="" # (Optionally) define an alternate reporting URL -export WPT_REPORT_URL= +export WPT_REPORT_URL="" # 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= - -# (Optionally) set a custom table prefix to permit concurrency against the same database. +# 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="" + +# (Optionally) set a custom table prefix to permit concurrency against the same +# database. export WPT_TABLE_PREFIX=${WPT_TABLE_PREFIX-wptests_} # (Optionally) define the PHP executable to be called export WPT_PHP_EXECUTABLE=${WPT_PHP_EXECUTABLE-php} +# (Optionally) array of versions +# like: "8.1=/bin/php8.1;8.2=/bin/php8.2;8.3=/bin/php8.3" +export WPT_PHP_EXECUTABLE_MULTI="" + # (Optionally) define the PHPUnit command execution call. # Use if `php phpunit.phar` can't be called directly for some reason. -export WPT_PHPUNIT_CMD= +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= +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= +export WPT_SSH_CONNECT="" # Any options to be passed to the SSH connection # Defaults to '-o StrictHostKeyChecking=no' -export WPT_SSH_OPTIONS= +export WPT_SSH_OPTIONS="" # SSH private key, base64 encoded. -export WPT_SSH_PRIVATE_KEY_BASE64= +export WPT_SSH_PRIVATE_KEY_BASE64="" # Output logging # Use 'verbose' to increase verbosity -export WPT_DEBUG= +export WPT_DEBUG="" # Certificate validation # Use 1 to validate, and 0 to not validate @@ -218,7 +253,7 @@ export WPT_CERTIFICATE_VALIDATION=1 # WordPress flavor # 0 = WordPress (simple version) # 1 = WordPress Multisite -export WPT_FLAVOR=1 +export WPT_FLAVOR=0 # Extra tests (groups) # 0 = none @@ -226,15 +261,210 @@ export WPT_FLAVOR=1 # 2 = ms-files # 3 = external-http export WPT_EXTRATESTS=0 + +# Check all commits +# 0 = latest +# 1 = all +export WPT_COMMITS=0 + +```` + +### Configuration file + +And this could be an example of each part: + +**Label** + +Label for the environment. Can be empty (default) or be like "shared", "vps", "cloud" or similar. Please use only alphanumeric keywords, and try to be descriptive + +``` +export WPT_LABEL="shared" +``` + +**Preparation directory** + +Path to the directory where files can be prepared before being delivered to the environment. + +Usually can be a /tmp/ folder so it does everything temporary. + +``` +export WPT_PREPARE_DIR="/tmp/wp-test-runner" +``` + +**Test directory** + +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 equally. + + +``` +export WPT_TEST_DIR="/tmp/wp-test-runner" +``` + +**API KEY** + +API key to authenticate with the reporting service in 'username:password' format. This is only needed if you want to publish your results in the WordPress site, so data can help developers to improve WordPress. + +Read: [How to report: Creating your bot for WordPress.org](https://make.wordpress.org/hosting/handbook/tests/#how-to-report-creating-your-bot-for-wordpress-org) + +``` +export WPT_REPORT_API_KEY="userbot:12345ABCDE67890F" +``` + +**Reporting URL** + +(Optionally) Define an alternate reporting URL, if you are running your own website. + +It should look like: +`https://reporter.example.com/wp-json/wp-unit-test-api/v1/results` + +``` +export WPT_REPORT_URL="https://reporter.example.com/wp-json/wp-unit-test-api/v1/results" +``` + +**Database credentials** + +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="testbot" +export WPT_DB_USER="wpuser" +export WPT_DB_PASSWORD="wppassword" +export WPT_DB_HOST="localhost" +``` + +**Tables Custom prefix** + +(Optionally) Set a custom table prefix to allow concurrency against the same database. This is very useful if you activate the multi-php or multi-environment part. + +``` +export WPT_TABLE_PREFIX=${WPT_TABLE_PREFIX-wptests_} +``` + +**PHP versions** + +_There are two options for backward compatibility._ + +The first one is the binary file / path for the default PHP. If it's empty it will use "php" as the command. + +``` +export WPT_PHP_EXECUTABLE=${WPT_PHP_EXECUTABLE-php} +``` + +The second one is the optional part. This allow to test more than one PHP versions. The format to use is: + +_majorversion1=binary_path1;majorversion2=binary_path2_ + +or, something like: + +`8.1=/bin/php8.1;8.2=/bin/php8.2;8.3=/bin/php8.3` + +Use as much versions as you want, but it will take more time. The idea is to put all the versions offered to users. + +``` +export WPT_PHP_EXECUTABLE_MULTI="7.4=/bin/php7.4;8.3=/bin/php8.3" +``` + +**PHPUnit execution call** + +(Optionally) define the PHPUnit command execution call. Use if `php phpunit.phar` can't be called directly for some reason. + +``` +export WPT_PHPUNIT_CMD="" +``` + +**Remove directory command** + +(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** + +SSH connection string (can also be an alias). Leave empty if tests are meant to run in the same environment. + +``` +export WPT_SSH_CONNECT="" +``` + +**SSH connection options** + +Any options to be passed to the SSH connection. Defaults to `-o StrictHostKeyChecking=no`. + +``` +export WPT_SSH_OPTIONS="" +``` + +**SSH private key** + +SSH private key, base64 encoded. + +``` +export WPT_SSH_PRIVATE_KEY_BASE64="" +``` + +**Output logging** + +Output logging. Use 'verbose' to increase verbosity. + +``` +export WPT_DEBUG="" +``` + +**Certificate validation** + +TLS Certificate validation. Use `1` to validate, and `0` to not validate. + +This may be useful in some environments with OpenSSL limitations (usually local environments). + +``` +export WPT_CERTIFICATE_VALIDATION=0 +``` + +**WordPress flavor** + +tests can check a simple WordPress installation or a WordPress Multisite installation. Pick your favor: + +Use `0` for a simple WordPress or `1` for a WordPress Multisite. + +``` +export WPT_FLAVOR=0 +``` + +**Extra tests (groups)** + +- `0` = none +- `1` = ajax +- `2` = ms-files +- `3` = external-http + +``` +export WPT_EXTRATESTS=0 +``` + +**Commits** + +Check all commits or only the latest. testing only the latest may cause a gap on tests, because, some times, there are more than two tests in a few minutes (and the software is not so quick). + +By default, use `0` to check the latest, or `1` to test all the commits (the latest 10 commits). + +``` +export WPT_COMMITS=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 +## 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. -```bash +``` cd /home/wptestrunner/phpunit-test-runner/ git pull source .env @@ -255,7 +485,7 @@ Now there is the environment ready, run the test preparation. 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: +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. @@ -263,7 +493,7 @@ 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 +## Running the test Now that the environment is ready, let’s run the tests. To do this, execute the file that will perform it. @@ -285,14 +515,16 @@ What do the symbols mean? 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 +## 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 +cat /tmp/wp-test-runner-(hash)/tests/phpunit/build/logs/env.json ``` +_The hash (a CRC32) will depend on the PHP version you are using._ + The content of this file is somewhat similar to this: ```bash @@ -325,19 +557,21 @@ The content of this file is somewhat similar to this: } ``` -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… +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 20,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 +cat /tmp/wp-test-runner-(hash)/tests/phpunit/build/logs/junit.xml ``` +_The hash (a CRC32) will depend on the PHP version you are using._ + 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 +## 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: @@ -345,24 +579,64 @@ Having the tests working, all that remains is to delete all the files that have php cleanup.php ``` -### Automatic running +## Automatic running + +There are many ways to execute tests automatically. In many cases, it will depend on what you want to do and test. + +Keep in mind some aspects: + +- Tests usually take several minutes, but the system includes a mechanism to avoid repeating them. This can result in durations ranging from hours to seconds. +- When configuring the system, ensure that tests do not overlap by implementing a system that prevents a test from being re-executed if it is already running. +- Tests update their software. The configuration file is typically compatible with previous versions. + +Some suggestions: + +- Create a script (for example, in Bash) that includes all the steps to execute, including: + - Updating the Git branch + - Loading the configuration file + - Executing the 4 steps / PHP files. +- Use a task scheduling system: + - Using cron + - Using systemd.timer + +### Script en Bash + +This is a simple example of a Bash script that could be placed in the directory above the software. For example, at `/home/wptestrunner/`. + +```bash +cat > /home/wptestrunner/testrunner.sh << EOF +cd /home/wptestrunner/phpunit-test-runner/ +git pull +git checkout master +source .env +php prepare.php +php test.php +php report.php +php cleanup.php +EOF +chmod +x /home/wptestrunner/testrunner.sh +``` + +From this moment on, if you run `bash /home/wptestrunner/testrunner.sh`, the test will execute once. + +### systemd timer -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. +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 and the bash script. ```bash -cat > /etc/systemd/system/wordpressphpunittestrunner.service << EOF +cat > /etc/systemd/system/testrunner.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 +ExecStart=bash /home/wptestrunner/testrunner.sh User=wptestrunner Group=wptestrunner EOF ``` ```bash -cat > /etc/systemd/system/wordpressphpunittestrunner.timer << EOF +cat > /etc/systemd/system/testrunner.timer << EOF [Unit] Description=WordPress PHPUnit Test Runner [Timer] @@ -375,16 +649,16 @@ EOF ```bash systemctl daemon-reload -systemctl enable wordpressphpunittestrunner.timer -systemctl start wordpressphpunittestrunner.timer -systemctl status wordpressphpunittestrunner.timer +systemctl enable testrunner.timer +systemctl start testrunner.timer +systemctl status testrunner.timer ``` If you want to check how is everything working... ```bash -journalctl -u wordpressphpunittestrunner.timer -journalctl -n 120 -u wordpressphpunittestrunner.service +journalctl -u testrunner.timer +journalctl -n 120 -u testrunner.service ``` ## Contributing diff --git a/cleanup.php b/cleanup.php index e584c6c..11e898c 100644 --- a/cleanup.php +++ b/cleanup.php @@ -1,53 +1,97 @@ $version, + 'bin' => $bin + ]; + } + } +} + +// Prepare an array of PHP executables. If multi-PHP is configured, use the multi-array; otherwise, use a single executable. +$php_executables = ! empty( $WPT_PHP_EXECUTABLE_MULTI_ARRAY ) ? $WPT_PHP_EXECUTABLE_MULTI_ARRAY : [ + [ + 'version' => 'default', + 'bin' => $WPT_PHP_EXECUTABLE, // Ensure this variable is defined for the single PHP executable case. + ] +]; /** - * Cleans up the test directory on a remote server. - * This conditional block checks if an SSH connection string is provided and is not empty. - * If a connection string is present, it triggers a cleanup operation on the remote environment. - * The cleanup operation is executed by the `perform_operations` function which takes an array - * of shell commands as its input. + * Performs a series of operations to clean up the test environment. + * This includes deleting specific directories and, if provided, cleaning up + * remote directories via SSH. */ -if ( ! empty( $WPT_SSH_CONNECT ) ) { - perform_operations( array( - 'ssh ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' ' . escapeshellarg( $WPT_RM_TEST_DIR_CMD ), - ) ); +foreach ( $php_executables as $php_multi ) { + // Generate unique directory names based on the PHP version. + $WPT_PREPARE_DIR_MULTI = $WPT_PREPARE_DIR . '-' . crc32( $php_multi['version'] ); + $WPT_TEST_DIR_MULTI = $WPT_TEST_DIR . '-' . crc32( $php_multi['version'] ); + + // Determines the command to remove the test directory, based on an environment variable or a default value. + $WPT_RM_TEST_DIR_CMD = trim( getenv( 'WPT_RM_TEST_DIR_CMD' ) ) ?: 'rm -r ' . $WPT_TEST_DIR_MULTI; + + /** + * Forcibly removes only the .git directory and the node_modules cache. + * Then, remove the entire staging directory to ensure a clean state for the next test run. + */ + perform_operations([ + 'rm -rf ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/.git' ), + 'rm -rf ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/node_modules/.cache' ), + 'rm -r ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ), + ]); + + /** + * Clears the test directory on a remote server if an SSH connection string is provided. + * This conditional block checks if the WPT_SSH_CONNECT environment variable is set. + * If so, it executes the remote cleanup command using SSH. + */ + if ( ! empty( $WPT_SSH_CONNECT ) ) { + perform_operations([ + 'ssh ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' ' . escapeshellarg( $WPT_RM_TEST_DIR_CMD ), + ]); + } } diff --git a/commits.json b/commits.json new file mode 100644 index 0000000..b1a5a97 --- /dev/null +++ b/commits.json @@ -0,0 +1,5 @@ +{ + "executed_commits": [], + "pending_commits": [], + "testing_commit": [] +} diff --git a/commits.json.example b/commits.json.example new file mode 100644 index 0000000..506ac11 --- /dev/null +++ b/commits.json.example @@ -0,0 +1,5 @@ +{ + "executed_commits": ["hash3"], + "pending_commits": ["hash1", "hash2", ..., "hash10"], + "testing_commit": ["hash4"] +} diff --git a/functions.php b/functions.php index f7d5981..f78f561 100644 --- a/functions.php +++ b/functions.php @@ -1,33 +1,39 @@ testsuite; - $results = array(); + $xml = simplexml_load_string( $xml_string ); // Parse the XML string. + $results = []; - $results = array( + $project = $xml->testsuite; + $results = [ 'tests' => (string) $project['tests'], 'failures' => (string) $project['failures'], 'errors' => (string) $project['errors'], 'time' => (string) $project['time'], - ); + ]; - $results['testsuites'] = array(); + $results['testsuites'] = []; + // XPath query to find test suites with failures or errors. $testsuites = $xml->xpath( '//testsuites//testsuite[ ( count( testcase ) > 0 ) and ( @errors > 0 or @failures > 0 ) ]' ); foreach ( $testsuites as $testsuite ) { - $result = array( + $result = [ 'name' => (string) $testsuite['name'], 'tests' => (string) $testsuite['tests'], 'failures' => (string) $testsuite['failures'], 'errors' => (string) $testsuite['errors'] - ); + ]; + + // Only include suites with failures or errors. if ( empty( $result['failures'] ) && empty( $result['errors'] ) ) { - continue; + continue; } - $failures = array(); + + $failures = []; foreach ( $testsuite->testcase as $testcase ) { // Capture both failure and error children. - foreach ( array( 'failure', 'error') as $key ) { + foreach ( [ 'failure', 'error' ] as $key ) { if ( isset( $testcase->{$key} ) ) { - $failures[ (string) $testcase['name'] ] = array( - 'name' => (string) $testcase['name'], - $key => (string) $testcase->{$key}, - ); - } + $failures[ (string) $testcase['name'] ] = [ + 'name' => (string) $testcase['name'], + $key => (string) $testcase->{$key}, + ]; } } } + if ( $failures ) { $results['testsuites'][ (string) $testsuite['name'] ] = $result; $results['testsuites'][ (string) $testsuite['name'] ]['testcases'] = $failures; } } - return json_encode( $results ); + return json_encode( $results ); // Return the results as a JSON encoded string. } /** - * Submits test results along with associated metadata to a specified reporting API. The function constructs - * a POST request containing the test results, SVN revision, SVN message, environment data, and uses an API key - * for authentication. The reporting API's URL is retrieved from an environment variable; if not found, a default - * URL is used. This function is typically used to automate the reporting of test outcomes to a centralized system - * for analysis, tracking, and historical record-keeping. - * - * @param string $results The test results in a processed format (e.g., JSON) ready for submission to the reporting API. - * @param string $rev The SVN revision associated with the test results. This often corresponds to a specific code - * commit or build identifier. - * @param string $message The SVN commit message associated with the revision, providing context or notes about the changes. - * @param string $env The environment data in JSON format, detailing the conditions under which the tests were run, - * such as operating system, PHP version, etc. - * @param string $api_key The API key for authenticating with the reporting API, ensuring secure and authorized access. - * - * @return array An array containing two elements: the HTTP status code of the response (int) and the body of the response - * (string) from the reporting API. This can be used to verify successful submission or to handle errors. - * - * @uses curl_init(), curl_setopt(), and curl_exec() to perform the HTTP POST request to the reporting API. - * @uses json_encode() to encode the data payload as a JSON string for submission. - * @uses base64_encode() to encode the API key for HTTP Basic Authentication in the Authorization header. + * Submits test results along with associated metadata to a specified reporting + * API. The function constructs a POST request containing the test results, SVN + * revision, SVN message, environment data, and uses an API key for + * authentication. The reporting API's URL is retrieved from an environment + * variable; if not found, a default URL is used. This function is typically + * used to automate the reporting of test outcomes to a centralized system for + * analysis, tracking, and historical record-keeping. + * + * @param string $results The test results in a processed format (e.g., JSON) + * ready for submission to the reporting API. + * + * @param string $rev The SVN revision associated with the test results. This + * often corresponds to a specific code commit or build identifier. + * + * @param string $message The SVN commit message associated with the revision, + * providing context or notes about the changes. + * + * @param string $env The environment data in JSON format, detailing the + * conditions under which the tests were run, such as operating system, PHP + * version, etc. + * + * @param string $api_key The API key for authenticating with the reporting API, + * ensuring secure and authorized access. + * + * @return array An array containing two elements: the HTTP status code of the + * response (int) and the body of the response (string) from the reporting API. + * This can be used to verify successful submission or to handle errors. + * + * @uses curl_init(), curl_setopt(), and curl_exec() to perform the HTTP POST + * request to the reporting API. + * + * @uses json_encode() to encode the data payload as a JSON string for + * submission. + * + * @uses base64_encode() to encode the API key for HTTP Basic Authentication in + * the Authorization header. */ function upload_results( $results, $rev, $message, $env, $api_key ) { $WPT_REPORT_URL = getenv( 'WPT_REPORT_URL' ); if ( ! $WPT_REPORT_URL ) { - $WPT_REPORT_URL = 'https://make.wordpress.org/hosting/wp-json/wp-unit-test-api/v1/results'; + $WPT_REPORT_URL = 'https://make.wordpress.org/hosting/wp-json/wp-unit-test-api/v1/results'; // Default URL. } - $process = curl_init( $WPT_REPORT_URL ); - $access_token = base64_encode( $api_key ); - $data = array( + + $process = curl_init( $WPT_REPORT_URL ); // Initialize CURL. + $access_token = base64_encode( $api_key ); // Encode API key for Basic Auth. + + $data = [ 'results' => $results, 'commit' => $rev, 'message' => $message, 'env' => $env, - ); - $data_string = json_encode( $data ); + ]; + $data_string = json_encode( $data ); // Convert data to JSON format. + + // Set CURL options. curl_setopt( $process, CURLOPT_TIMEOUT, 30 ); curl_setopt( $process, CURLOPT_POST, 1 ); curl_setopt( $process, CURLOPT_CUSTOMREQUEST, 'POST' ); curl_setopt( $process, CURLOPT_POSTFIELDS, $data_string ); curl_setopt( $process, CURLOPT_RETURNTRANSFER, true ); - curl_setopt( $process, CURLOPT_HTTPHEADER, array( - "Authorization: Basic $access_token", - 'Content-Type: application/json', - 'Content-Length: ' . strlen( $data_string ) - )); + curl_setopt( $process, CURLOPT_HTTPHEADER, [ + "Authorization: Basic $access_token", // Set Authorization header. + 'Content-Type: application/json', // Specify content type. + 'Content-Length: ' . strlen( $data_string ) // Set content length. + ]); - $return = curl_exec( $process ); - $status_code = curl_getinfo( $process, CURLINFO_HTTP_CODE ); - curl_close( $process ); + $return = curl_exec( $process ); // Execute the request. + $status_code = curl_getinfo( $process, CURLINFO_HTTP_CODE ); // Get the HTTP status code. + curl_close( $process ); // Close CURL session. - return array( $status_code, $return ); + return [ $status_code, $return ]; // Return status code and response. } /** - * Collects and returns an array of key environment details relevant to the application's context. This includes - * the PHP version, installed PHP modules with their versions, system utilities like curl and OpenSSL versions, - * MySQL version, and operating system details. This function is useful for diagnostic purposes, ensuring - * compatibility, or for reporting system configurations in debugging or error logs. - * - * The function checks for the availability of specific PHP modules and system utilities and captures their versions. - * It uses shell commands to retrieve system information, which requires the PHP environment to have access to these - * commands and appropriate permissions. + * Collects and returns an array of key environment details relevant to the + * application's context. This includes the PHP version, installed PHP modules + * with their versions, system utilities like curl and OpenSSL versions, MySQL + * version, and operating system details. This function is useful for diagnostic + * purposes, ensuring compatibility, or for reporting system configurations in + * debugging or error logs. + * The function checks for the availability of specific PHP modules and system + * utilities and captures their versions. It uses shell commands to retrieve + * system information, which requires the PHP environment to have access to + * these commands and appropriate permissions. * * @return array An associative array containing detailed environment information. The array includes: - * - 'php_version': The current PHP version. - * - 'php_modules': An associative array of selected PHP modules and their versions. - * - 'system_utils': Versions of certain system utilities such as 'curl', 'imagemagick', 'graphicsmagick', and 'openssl'. - * - 'mysql_version': The version of MySQL installed. - * - 'os_name': The name of the operating system. - * - 'os_version': The version of the operating system. + * - 'php_version': The current PHP version. + * - 'php_modules': An associative array of selected PHP modules and their versions. + * - 'system_utils': Versions of certain system utilities such as 'curl', 'imagemagick', 'graphicsmagick', and 'openssl'. + * - 'mysql_version': The version of MySQL installed. + * - 'os_name': The name of the operating system. + * - 'os_version': The version of the operating system. * * @uses phpversion() to get the PHP version and module versions. + * * @uses shell_exec() to execute system commands for retrieving MySQL version, OS details, and versions of utilities like curl and OpenSSL. + * * @uses class_exists() to check for the availability of the Imagick and Gmagick classes for version detection. */ function get_env_details() { - - $gd_info = array(); - if( extension_loaded( 'gd' ) ) { - $gd_info = gd_info(); - } - $imagick_info = array(); - if( extension_loaded( 'imagick' ) ) { - $imagick_info = Imagick::queryFormats(); + $gd_info = []; + if ( extension_loaded( 'gd' ) ) { + $gd_info = gd_info(); // Get GD info if the GD extension is loaded. } - $env = array( - 'php_version' => phpversion(), - 'php_modules' => array(), - 'gd_info' => $gd_info, - 'imagick_info' => $imagick_info, - 'mysql_version' => trim( shell_exec( 'mysql --version' ) ), - 'system_utils' => array(), - 'os_name' => trim( shell_exec( 'uname -s' ) ), - 'os_version' => trim( shell_exec( 'uname -r' ) ), - ); - unset( $gd_info, $imagick_info ); - - $php_modules = array( - 'bcmath', - 'ctype', - 'curl', - 'date', - 'dom', - 'exif', - 'fileinfo', - 'filter', - 'ftp', - 'gd', - 'gettext', - 'gmagick', - 'hash', - 'iconv', - 'imagick', - 'imap', - 'intl', - 'json', - 'libsodium', - 'libxml', - 'mbstring', - 'mcrypt', - 'mod_xml', - 'mysqli', - 'mysqlnd', - 'openssl', - 'pcre', - 'pdo_mysql', - 'soap', - 'sockets', - 'sodium', - 'xml', - 'xmlreader', - 'zip', - 'zlib', - ); - foreach( $php_modules as $php_module ) { - $env['php_modules'][ $php_module ] = phpversion( $php_module ); + $imagick_info = []; + if ( extension_loaded( 'imagick' ) ) { + $imagick_info = Imagick::queryFormats(); // Get Imagick info if the Imagick extension is loaded. } - function curl_selected_bits($k) { return in_array($k, array('version', 'ssl_version', 'libz_version')); } - $curl_bits = curl_version(); - $env['system_utils']['curl'] = implode(' ',array_values(array_filter($curl_bits, 'curl_selected_bits',ARRAY_FILTER_USE_KEY) )); + $env = [ + 'php_version' => phpversion(), // Current PHP version. + 'php_modules' => array(), + 'gd_info' => $gd_info, + 'imagick_info' => $imagick_info, + 'mysql_version' => '', // Will be set later if MySQL is available. + 'system_utils' => array(), + 'os_name' => trim( shell_exec( 'uname -s' ) ), // OS name. + 'os_version' => trim( shell_exec( 'uname -r' ) ), // OS version. + ]; + + $php_modules = [ + 'bcmath', 'ctype', 'curl', 'date', 'dom', 'exif', 'fileinfo', 'filter', + 'ftp', 'gd', 'gettext', 'gmagick', 'hash', 'iconv', 'imagick', 'imap', + 'intl', 'json', 'libsodium', 'libxml', 'mbstring', 'mcrypt', 'mod_xml', + 'mysqli', 'mysqlnd', 'openssl', 'pcre', 'pdo_mysql', 'soap', 'sockets', + 'sodium', 'xml', 'xmlreader', 'zip', 'zlib', + ]; - $WPT_DB_HOST = trim( getenv( 'WPT_DB_HOST' ) ); - if( ! $WPT_DB_HOST ) { - $WPT_DB_HOST = 'localhost'; + foreach ( $php_modules as $php_module ) { + $env['php_modules'][ $php_module ] = phpversion( $php_module ); // Get version for each PHP module. } - $WPT_DB_USER = trim( getenv( 'WPT_DB_USER' ) ); - $WPT_DB_PASSWORD = trim( getenv( 'WPT_DB_PASSWORD' ) ); - $WPT_DB_NAME = trim( getenv( 'WPT_DB_NAME' ) ); - //$mysqli = new mysqli( $WPT_DB_HOST, $WPT_DB_USER, $WPT_DB_PASSWORD, $WPT_DB_NAME ); - //$env['mysql_version'] = $mysqli->query("SELECT VERSION()")->fetch_row()[0]; - //$mysqli->close(); + $curl_bits = curl_version(); // Get CURL version info. + $env['system_utils']['curl'] = implode( ' ', array_values( array_filter( $curl_bits, function( $k ) { + return in_array( $k, [ 'version', 'ssl_version', 'libz_version'] ); // Filter curl version info. + }, ARRAY_FILTER_USE_KEY))); + + // Check for MySQL version if connection details are available. + $WPT_DB_HOST = trim( getenv( 'WPT_DB_HOST' ) ?: 'localhost' ); // Default to localhost if not set. + $WPT_DB_USER = trim( getenv( 'WPT_DB_USER' ) ); + $WPT_DB_PASSWORD = trim( getenv( 'WPT_DB_PASSWORD' ) ); + $WPT_DB_NAME = trim( getenv( 'WPT_DB_NAME' ) ); + + if ( class_exists( 'mysqli' ) ) { + $mysqli = new mysqli( $WPT_DB_HOST, $WPT_DB_USER, $WPT_DB_PASSWORD, $WPT_DB_NAME ); + if ( ! $mysqli->connect_error ) { + $env['mysql_version'] = $mysqli->query("SELECT VERSION()")->fetch_row()[0]; // Get MySQL version. + $mysqli->close(); + } + } if ( class_exists( 'Imagick' ) ) { $imagick = new Imagick(); $version = $imagick->getVersion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['imagemagick'] = $version[1]; + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $matches ); + $env['system_utils']['imagemagick'] = $matches[1]; // Get Imagick version. } elseif ( class_exists( 'Gmagick' ) ) { $gmagick = new Gmagick(); $version = $gmagick->getversion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['graphicsmagick'] = $version[1]; + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $matches ); + $env['system_utils']['graphicsmagick'] = $matches[1]; // Get GraphicsMagick version. } - $env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); + $env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); // Get OpenSSL version. - return $env; + return $env; // Return the collected environment details. } diff --git a/ignore.json b/ignore.json new file mode 100644 index 0000000..557a88e --- /dev/null +++ b/ignore.json @@ -0,0 +1,6 @@ +{ + "commits_ignore": [ + "Tests_Filesystem_WpFilesystemDirect_Mkdir::test_should_set_owner", + "Tests_Filesystem_WpFilesystemDirect_Mkdir::test_should_set_group" + ] +} diff --git a/ignore.json.example b/ignore.json.example new file mode 100644 index 0000000..557a88e --- /dev/null +++ b/ignore.json.example @@ -0,0 +1,6 @@ +{ + "commits_ignore": [ + "Tests_Filesystem_WpFilesystemDirect_Mkdir::test_should_set_owner", + "Tests_Filesystem_WpFilesystemDirect_Mkdir::test_should_set_group" + ] +} diff --git a/prepare.php b/prepare.php index 2948b70..6e91851 100644 --- a/prepare.php +++ b/prepare.php @@ -1,144 +1,220 @@ $executed_commits, + 'pending_commits' => $pending_commits, + 'testing_commit' => $testing_commit, + ]; - // Write the decoded private key into the id_rsa file within the .ssh directory. - file_put_contents( getenv( 'HOME' ) . '/.ssh/id_rsa', base64_decode( $WPT_SSH_PRIVATE_KEY_BASE64 ) ); - - // Define the array of operations to perform, depending on the SSH connection availability. - // If no SSH connection string is provided, add a local operation to the array. - // If an SSH connection string is provided, add a remote operation to the array. - // Execute the operations defined in the operations array. - if( empty( $WPT_SSH_CONNECT ) ) { - perform_operations( array( - 'chmod 600 ~/.ssh/id_rsa', - 'wp cli info' - ) ); } else { - perform_operations( array( - 'chmod 600 ~/.ssh/id_rsa', - 'ssh -q ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' wp cli info' - ) ); + + // If the JSON file does not exist, initialize the default values. + $c = [ + 'executed_commits' => [], + 'pending_commits' => $WPT_COMMIT, + 'testing_commit' => null, + ]; } + // Encodes the array to JSON and saves it to the file + file_put_contents( $commitsFile, json_encode( $c, JSON_PRETTY_PRINT ) ); } /** - * Don't validate the TLS certificate - * Useful for local environments + * Parses the multi PHP executable versions and populates the + * WPT_PHP_EXECUTABLE_MULTI_ARRAY. */ -$certificate_validation = ''; -if( ! $WPT_CERTIFICATE_VALIDATION ) { - $certificate_validation .= ' --no-check-certificate'; +$WPT_PHP_EXECUTABLE_MULTI_ARRAY = []; +if ( ! empty( $WPT_PHP_EXECUTABLE_MULTI ) ) { + + // Divide the version string by semicolon + $php_multi_versions = explode( ';', $WPT_PHP_EXECUTABLE_MULTI ); + + foreach ( $php_multi_versions as $php_multi_version ) { + // Divide each version by the equals sign and apply trim to each part + $parts = array_map( 'trim', explode( '=', $php_multi_version, 2 ) ); + + // Ensures that both parts exist and are not empty. + if ( 2 === count( $parts ) && '' !== $parts[0] && '' !== $parts[1] ) { + [ $version, $bin ] = $parts; + $WPT_PHP_EXECUTABLE_MULTI_ARRAY[] = [ + 'version' => $version, + 'bin' => $bin + ]; + } + } } /** - * Performs a series of operations to set up the test environment. This includes creating a preparation directory, - * cloning the WordPress development repository, downloading the WordPress importer plugin, and preparing the environment with npm. + * Sets up the SSH private key for use in the test environment if provided. */ -// Prepare an array of shell commands to set up the testing environment. -perform_operations( array( +$WPT_SSH_PRIVATE_KEY_BASE64 = trim( getenv( 'WPT_SSH_PRIVATE_KEY_BASE64' ) ); - // Create the preparation directory if it doesn't exist. The '-p' flag creates intermediate directories as required. - 'mkdir -p ' . escapeshellarg( $WPT_PREPARE_DIR ), +// Check if the private key variable is not empty +if ( ! empty( $WPT_SSH_PRIVATE_KEY_BASE64 ) ) { - // 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( $WPT_PREPARE_DIR ), + // Log the action of securely extracting the private key + log_message( 'Securely extracting WPT_SSH_PRIVATE_KEY_BASE64 into ~/.ssh/id_rsa' ); - // Download the WordPress importer plugin zip file to the specified plugins directory. - 'wget -O ' . escapeshellarg( $WPT_PREPARE_DIR . '/tests/phpunit/data/plugins/wordpress-importer.zip' ) . ' https://downloads.wordpress.org/plugin/wordpress-importer.zip' . $certificate_validation, + // Define the .ssh directory path + $SSHDIR = getenv('HOME') . '/.ssh'; - // Change directory to the plugin directory, unzip the WordPress importer plugin, and remove the zip file. - 'cd ' . escapeshellarg( $WPT_PREPARE_DIR . '/tests/phpunit/data/plugins/' ) . '; unzip wordpress-importer.zip; rm wordpress-importer.zip', + // Check if the .ssh directory exists, create it if it does not + if ( ! is_dir( $SSHDIR ) ) { + mkdir( $SSHDIR, 0777, true ); + } - // Change directory to the preparation directory, install npm dependencies, and build the project. - 'cd ' . escapeshellarg( $WPT_PREPARE_DIR ) . '; npm install && npm run build' + // Decode the base64-encoded private key and write it to the id_rsa file + file_put_contents( $SSHDIR . '/id_rsa', base64_decode( $WPT_SSH_PRIVATE_KEY_BASE64 ) ); -) ); + // Define the array of operations to perform + $operations = [ + 'chmod 600 ~/.ssh/id_rsa' + ]; -// Log a message indicating the start of the variable replacement process for configuration. -log_message( 'Replacing variables in wp-tests-config.php' ); + if ( empty( $WPT_SSH_CONNECT ) ) { + // Add local operation if no SSH connection string is provided + $operations[] = 'wp cli info'; + } else { + // Add remote operation if SSH connection string is provided + $operations[] = 'ssh -q ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' wp cli info'; + } + + // Execute the defined operations + perform_operations( $operations ); +} /** - * 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. + * Don't validate the TLS certificate. Useful for local environments. */ -$contents = file_get_contents( $WPT_PREPARE_DIR . '/wp-tests-config-sample.php' ); +// Initialize the certificate validation flag +$certificate_validation = ''; +// Append the no-check-certificate option if certificate validation is disabled +if ( ! $WPT_CERTIFICATE_VALIDATION ) { + $certificate_validation = ' --no-check-certificate'; +} /** * Prepares a script to log system information relevant to the testing environment. @@ -151,90 +227,68 @@ */ $system_logger = << '{$WPT_LABEL}', 'php_version' => phpversion(), - 'php_modules' => array(), + 'php_modules' => [], 'gd_info' => \$gd_info, 'imagick_info' => \$imagick_info, - 'mysql_version' => trim( shell_exec( 'mysql --version' ) ), - 'system_utils' => array(), - 'os_name' => trim( shell_exec( 'uname -s' ) ), - 'os_version' => trim( shell_exec( 'uname -r' ) ), -); -\$php_modules = array( - 'bcmath', - 'ctype', - 'curl', - 'date', - 'dom', - 'exif', - 'fileinfo', - 'filter', - 'ftp', - 'gd', - 'gettext', - 'gmagick', - 'hash', - 'iconv', - 'imagick', - 'imap', - 'intl', - 'json', - 'libsodium', - 'libxml', - 'mbstring', - 'mcrypt', - 'mod_xml', - 'mysqli', - 'mysqlnd', - 'openssl', - 'pcre', - 'pdo_mysql', - 'soap', - 'sockets', - 'sodium', - 'xml', - 'xmlreader', - 'zip', - 'zlib', -); -foreach( \$php_modules as \$php_module ) { - \$env['php_modules'][ \$php_module ] = phpversion( \$php_module ); + 'mysql_version' => trim(shell_exec('mysql --version')), + 'system_utils' => [], + 'os_name' => trim(shell_exec('uname -s')), + 'os_version' => trim(shell_exec('uname -r')), +]; +// List of PHP modules to check +\$php_modules = [ + 'bcmath', 'ctype', 'curl', 'date', 'dom', 'exif', 'fileinfo', 'filter', + 'ftp', 'gd', 'gettext', 'gmagick', 'hash', 'iconv', 'imagick', 'imap', + 'intl', 'json', 'libsodium', 'libxml', 'mbstring', 'mcrypt', 'mod_xml', + 'mysqli', 'mysqlnd', 'openssl', 'pcre', 'pdo_mysql', 'soap', 'sockets', + 'sodium', 'xml', 'xmlreader', 'zip', 'zlib', +]; +// Populate PHP modules versions +foreach (\$php_modules as \$php_module) { + \$env['php_modules'][\$php_module] = phpversion(\$php_module); +} +// Helper function to filter cURL bits +function curl_selected_bits(\$key) { + return in_array(\$key, ['version', 'ssl_version', 'libz_version']); } -function curl_selected_bits(\$k) { return in_array(\$k, array('version', 'ssl_version', 'libz_version')); } +// Collect cURL version info \$curl_bits = curl_version(); -\$env['system_utils']['curl'] = implode(' ',array_values(array_filter(\$curl_bits, 'curl_selected_bits',ARRAY_FILTER_USE_KEY) )); -if ( class_exists( 'Imagick' ) ) { +\$env['system_utils']['curl'] = implode(' ', array_values(array_filter(\$curl_bits, 'curl_selected_bits', ARRAY_FILTER_USE_KEY))); +// Collect Imagick or Gmagick version info +if (class_exists('Imagick')) { \$imagick = new Imagick(); \$version = \$imagick->getVersion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', \$version['versionString'], \$version ); - \$env['system_utils']['imagemagick'] = \$version[1]; -} elseif ( class_exists( 'Gmagick' ) ) { + preg_match('/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', \$version['versionString'], \$matches); + \$env['system_utils']['imagemagick'] = \$matches[1] ?? 'Unknown'; +} elseif (class_exists('Gmagick')) { \$gmagick = new Gmagick(); - \$version = \$gmagick->getversion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', \$version['versionString'], \$version ); - \$env['system_utils']['graphicsmagick'] = \$version[1]; + \$version = \$gmagick->getVersion(); + preg_match('/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', \$version['versionString'], \$matches); + \$env['system_utils']['graphicsmagick'] = \$matches[1] ?? 'Unknown'; } -\$env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); -//\$mysqli = new mysqli( WPT_DB_HOST, WPT_DB_USER, WPT_DB_PASSWORD, WPT_DB_NAME ); -//\$env['mysql_version'] = \$mysqli->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 ) { +// Collect OpenSSL version +\$env['system_utils']['openssl'] = str_replace('OpenSSL ', '', trim(shell_exec('openssl version'))); +// Optional: Collect MySQL version using mysqli (currently commented out) +// \$mysqli = new mysqli(WPT_DB_HOST, WPT_DB_USER, WPT_DB_PASSWORD, WPT_DB_NAME); +// \$env['mysql_version'] = \$mysqli->query("SELECT VERSION()")->fetch_row()[0]; +// \$mysqli->close(); +// Write environment info to JSON file +file_put_contents(\$logDir . 'env.json', json_encode(\$env, JSON_PRETTY_PRINT)); +// If running from CLI during WP installation, output PHP version and executable path +if ('cli' === php_sapi_name() && defined('WP_INSTALLING') && WP_INSTALLING) { echo PHP_EOL; - echo 'PHP version: ' . phpversion() . ' (' . realpath( \$_SERVER['_'] ) . ')' . PHP_EOL; + echo 'PHP version: ' . phpversion() . ' (' . realpath(\$_SERVER['_']) . ')' . PHP_EOL; echo PHP_EOL; } EOT; @@ -245,128 +299,186 @@ function curl_selected_bits(\$k) { return in_array(\$k, array('version', 'ssl_ve // 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\', \''. $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, - $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( $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 = $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( $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 ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $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. + * 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. */ -$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 ); +// Prepare an array of PHP executables. If multi-PHP is configured, use the multi-array; otherwise, use a single executable. +$php_executables = ! empty( $WPT_PHP_EXECUTABLE_MULTI_ARRAY ) ? $WPT_PHP_EXECUTABLE_MULTI_ARRAY : [ + [ + 'version' => 'default', + 'bin' => $WPT_PHP_EXECUTABLE, // Ensure this variable is defined for the single PHP executable case. + ] +]; /** - * Checks if the detected PHP version is below 7.0. - * The test runner requires PHP version 7.0 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.0', '<' ) ) { - // Logs an error message indicating the test runner's incompatibility with PHP versions below 7.0. - error_message( 'The test runner is not compatible with PHP < 7.0.' ); -} - -/** - * Use Composer to manage PHPUnit and its dependencies. - * This allows for better dependency management and compatibility. + * Performs a series of operations to set up the test environment. This includes creating a preparation directory, + * cloning the WordPress development repository, downloading the WordPress importer plugin, and preparing the environment with npm. */ +foreach ( $php_executables as $php_multi ) { + + // Generate unique directory names based on the PHP version. + $version_hash = crc32( $php_multi['version'] ); + $WPT_PREPARE_DIR_MULTI = $WPT_PREPARE_DIR . '-' . $version_hash; + $WPT_TEST_DIR_MULTI = $WPT_TEST_DIR . '-' . $version_hash; + + // Create the preparation directory and clone the WordPress develop repository. + perform_operations([ + 'mkdir -p ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ), + 'git clone --depth=10 https://github.com/WordPress/wordpress-develop.git ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ), + 'git config --add safe.directory ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ), + ]); + + // Handle commit SHA if $WPT_COMMITS is enabled. + if ( $WPT_COMMITS ) { + $commit_sha = null; + $commits_file = __DIR__ . '/commits.json'; + + if ( file_exists( $commits_file ) ) { + $c_array = json_decode( file_get_contents( $commits_file ), true ); + + if ( isset( $c_array['testing_commit'] ) && count( $c_array['testing_commit'] ) ) { + $commit_sha = $c_array['testing_commit'][0]; + } else { + $commit_sha = array_pop( $c_array['pending_commits'] ); + $c_array['testing_commit'][0] = $commit_sha; + } + + file_put_contents( $commits_file, json_encode( $c_array ) ); + } + + if ( ! is_null( $commit_sha ) ) { + perform_operations([ + 'cd ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ) . ' && git checkout ' . $commit_sha, + ]); + } + } -// Check if Composer is installed and available in the PATH. -$composer_cmd = 'cd ' . escapeshellarg( $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 . ' '; + // Download the WordPress importer plugin, unzip it, and build the project with npm. + perform_operations([ + 'wget -O ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/tests/phpunit/data/plugins/wordpress-importer.zip' ) . ' https://downloads.wordpress.org/plugin/wordpress-importer.zip' . $certificate_validation, + 'cd ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/tests/phpunit/data/plugins/' ) . '; unzip wordpress-importer.zip; rm wordpress-importer.zip', + 'cd ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ) . '; npm install && npm run build', + ]); + + // Log the start of the variable replacement process for the specific PHP version. + log_message( 'Replacing variables in ' . $php_multi['version'] . ' wp-tests-config.php' ); + + // Read the contents of the wp-tests-config-sample.php file. + $config_sample_path = $WPT_PREPARE_DIR_MULTI . '/wp-tests-config-sample.php'; + $contents = file_get_contents( $config_sample_path ); + + // Define the PHP binary string for the specific PHP executable. + $php_binary_string = 'define( \'WP_PHP_BINARY\', \'' . $php_multi['bin'] . '\' );'; + + // Generate a unique table prefix based on environment variables and PHP version. + $wptests_tableprefix = trim( getenv( 'WPT_TABLE_PREFIX' ) ) ?: 'wptests_'; + $wptests_tableprefix .= crc32( $php_multi['version'] ); + + // Create an associative array for search and replace in the configuration file. + $search_replace = [ + 'wptests_' => $wptests_tableprefix, + '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, + $logger_replace_string => $system_logger, + ]; + + // Replace placeholders in the configuration sample with actual values. + $contents = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $contents ); + + // Write the modified content to wp-tests-config.php. + $config_path = $WPT_PREPARE_DIR_MULTI . '/wp-tests-config.php'; + file_put_contents( $config_path, $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 = $php_multi['bin'] . " -r \"print PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;\""; + + // Modify the command to execute remotely via SSH if an SSH connection is provided. + if ( ! empty( $WPT_SSH_CONNECT ) ) { + $php_version_cmd = 'ssh ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' ' . escapeshellarg( $php_version_cmd ); + } -} else { + // Execute the command to retrieve the PHP version. + $retval = 0; + $env_php_version = exec( $php_version_cmd, $output, $retval ); - // If Composer is not available, download the Composer phar file. - log_message( 'Local Composer not found. Downloading latest stable ...' ); + // Log an error if the PHP version retrieval failed. + if ( 0 !== $retval ) { + error_message( 'Could not retrieve the environment PHP Version for ' . $php_multi['version'] . '.' ); + } - perform_operations( array( - 'wget -O ' . escapeshellarg( $WPT_PREPARE_DIR . '/composer.phar' ) . ' https://getcomposer.org/composer-stable.phar', - ) ); + // Log the obtained PHP version. + log_message( 'Environment PHP Version: ' . $env_php_version ); - // Update the command to use the downloaded Composer phar file. - $composer_cmd .= 'php composer.phar '; -} + /** + * 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. + */ + if ( version_compare( $env_php_version, '7.2', '<' ) ) { + error_message( 'The test runner is not compatible with PHP < 7.2.' ); + } -// Set the PHP version for Composer to ensure compatibility and update dependencies. -perform_operations( array( - $composer_cmd . 'config platform.php ' . escapeshellarg( $env_php_version ), - $composer_cmd . 'update', -) ); + /** + * Use Composer to manage PHPUnit and its dependencies. + * This allows for better dependency management and compatibility. + */ -/** - * 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. - */ -if ( ! empty( $WPT_SSH_CONNECT ) ) { - // Initialize rsync options with recursive copying. - $rsync_options = '-r'; + // Define the Composer command based on its availability. + $composer_cmd = 'cd ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ) . ' && '; + $composer_path = system( 'which composer', $retval ); + $composer_path = escapeshellarg( trim( $composer_path ) ); - // If debug mode is set to verbose, append 'v' to rsync options for verbose output. - if ( 'verbose' === $WPT_DEBUG ) { - $rsync_options = $rsync_options . 'v'; + if ( 0 === $retval && ! empty( $composer_path ) ) { + // If Composer is available, 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([ + 'wget -O ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/composer.phar' ) . ' https://getcomposer.org/composer-stable.phar' . $certificate_validation, + ]); + // Use the downloaded Composer phar file. + $composer_cmd .= $php_multi['bin'] . ' composer.phar '; } - // 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" -e "ssh ' . $WPT_SSH_OPTIONS . '" ' . escapeshellarg( trailingslashit( $WPT_PREPARE_DIR ) ) . ' ' . escapeshellarg( $WPT_SSH_CONNECT . ':' . $WPT_TEST_DIR ), - ) ); + // Set the PHP version for Composer and update dependencies. + perform_operations([ + $composer_cmd . 'config platform.php ' . escapeshellarg( $env_php_version ), + $composer_cmd . 'update', + ]); + + /** + * 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. + */ + if ( ! empty( $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 ( 'verbose' === $WPT_DEBUG ) { + $rsync_options .= 'v'; + } + + // Perform the rsync operation with the configured options and exclude patterns. + perform_operations([ + 'rsync ' . $rsync_options . ' --exclude=".git/" --exclude="node_modules/" --exclude="composer.phar" -e "ssh ' . $WPT_SSH_OPTIONS . '" ' . escapeshellarg( rtrim( $WPT_PREPARE_DIR_MULTI, '/' ) ) . '/ ' . escapeshellarg( $WPT_SSH_CONNECT . ':' . $WPT_TEST_DIR ), + ]); + } } // Log a success message indicating that the environment has been prepared. diff --git a/report.php b/report.php index b690f76..5ff8ee5 100644 --- a/report.php +++ b/report.php @@ -1,179 +1,214 @@ $version, + 'bin' => $bin + ]; + } + } } -/** - * Constructs the rsync command for executing the synchronization of junit.xml files. - * Concatenates the rsync command with the previously defined options and the source and - * destination paths. The destination path is sanitized for shell execution. This command is - * then passed to the `perform_operations` function, which executes the command to synchronize - * the junit.xml files from the source to the destination directory. - */ -$junit_exec = 'rsync ' . $rsync_options . ' ' . $junit_location . ' ' . escapeshellarg( $WPT_PREPARE_DIR ); -perform_operations( array( - $junit_exec, -) ); - -/** - * 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. - */ -log_message( 'Processing and uploading junit.xml' ); -$xml = file_get_contents( $WPT_PREPARE_DIR . '/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( $WPT_PREPARE_DIR . '/env.json' ) ) { - $env = file_get_contents( $WPT_PREPARE_DIR . '/env.json' ); -} elseif ( $WPT_PREPARE_DIR === $WPT_TEST_DIR ) { - $env = json_encode( get_env_details(), JSON_PRETTY_PRINT ); -} +// Prepare an array of PHP executables. If multi-PHP is configured, use the multi-array; otherwise, use a single executable. +$php_executables = ! empty( $WPT_PHP_EXECUTABLE_MULTI_ARRAY ) ? $WPT_PHP_EXECUTABLE_MULTI_ARRAY : [ + [ + 'version' => 'default', + 'bin' => $WPT_PHP_EXECUTABLE, // Ensure this variable is defined for the single PHP executable case. + ] +]; /** - * 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. + * Performs a series of operations to set up the test environment. + * This includes handling commits, retrieving SVN revisions, copying results, processing junit.xml, + * and uploading test results. */ -if( ! empty( $WPT_REPORT_API_KEY ) ) { +foreach ( $php_executables as $php_multi ) { + // Generate unique directory names based on the PHP version. + $WPT_PREPARE_DIR_MULTI = $WPT_PREPARE_DIR . '-' . crc32( $php_multi['version'] ); + $WPT_TEST_DIR_MULTI = $WPT_TEST_DIR . '-' . crc32( $php_multi['version'] ); + + /** + * Handle commits if $WPT_COMMITS is enabled. + */ + if ( $WPT_COMMITS ) { + $commits_file = __DIR__ . '/commits.json'; + if ( file_exists( $commits_file ) ) { + $c_array = json_decode( file_get_contents( $commits_file ), true ); + + if ( isset( $c_array['testing_commit'] ) && count( $c_array['testing_commit'] ) ) { + // Move the current testing commit to executed_commits + $c_array['executed_commits'][] = $c_array['testing_commit'][0]; + unset( $c_array['testing_commit'][0] ); + } + + file_put_contents( $commits_file, json_encode( $c_array ) ); + } + } - // Upload the results and capture the HTTP status and response body - list( $http_status, $response_body ) = upload_results( $results, $rev, $message, $env, $WPT_REPORT_API_KEY ); + /** + * Retrieve the SVN revision number from the git repository log. + */ + log_message( 'Getting SVN Revision' ); + $rev = exec( 'git --git-dir=' . escapeshellarg( $WPT_PREPARE_DIR_MULTI . '/.git' ) . ' log -1 --pretty=%B | grep "git-svn-id:" | cut -d " " -f 2 | cut -d "@" -f 2' ); + + /** + * Retrieve the latest SVN commit message from the git repository log. + */ + log_message( 'Getting SVN message' ); + $message = trim( exec( 'git --git-dir=' . escapeshellarg($WPT_PREPARE_DIR_MULTI . '/.git') . ' log -1 --pretty=%B | head -1' ) ); + + /** + * Copy the junit.xml results. + */ + log_message( 'Copying junit.xml results' ); + $junit_location = escapeshellarg( $WPT_TEST_DIR_MULTI ) . '/tests/phpunit/build/logs/*'; + + if ( ! empty( $WPT_SSH_CONNECT ) ) { + $junit_location = '-e "ssh ' . $WPT_SSH_OPTIONS . '" ' . escapeshellarg( $WPT_SSH_CONNECT . ':' . $junit_location ); + } - // Decode the JSON response body - $response = json_decode( $response_body, true ); - if ( 20 == substr( $http_status, 0, 2 ) ) { + /** + * Set rsync options based on the debug mode. + */ + $rsync_options = '-r'; + if ( 'verbose' === $WPT_DEBUG ) { + $rsync_options .= 'v'; + } - // 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 ); + /** + * Construct and execute the rsync command. + */ + $junit_exec = 'rsync ' . $rsync_options . ' ' . $junit_location . ' ' . escapeshellarg( $WPT_PREPARE_DIR_MULTI ); + perform_operations([ + $junit_exec, + ]); + + /** + * Process and upload the junit.xml file. + */ + log_message( 'Processing and uploading junit.xml' ); + $xml = file_get_contents( $WPT_PREPARE_DIR_MULTI . '/junit.xml' ); + $results = process_junit_xml( $xml ); + + /** + * Retrieve environment details from a JSON file or generate them if not available. + */ + $env = ''; + $env_json_path = $WPT_PREPARE_DIR_MULTI . '/env.json'; + if ( file_exists( $env_json_path ) ) { + $env = file_get_contents( $env_json_path ); + } elseif ( $WPT_PREPARE_DIR_MULTI === $WPT_TEST_DIR_MULTI ) { + $env = json_encode( get_env_details(), JSON_PRETTY_PRINT ); + } + /** + * Attempt to upload test results if an API key is available; otherwise, log the results locally. + */ + if ( ! empty( $WPT_REPORT_API_KEY ) ) { + // Upload the results and capture the HTTP status and response body + list( $http_status, $response_body ) = upload_results( $results, $rev, $message, $env, $WPT_REPORT_API_KEY ); + + // Decode the JSON response body + $response = json_decode( $response_body, true ); + if ( strpos( $http_status, '20' ) === 0 ) { // Check if status code starts with '20' + // Construct and log a success message with a link if provided in the response + $success_message = 'Results successfully uploaded'; + if ( isset( $response['link'] ) ) { + $success_message .= ': ' . $response['link']; + } + log_message( $success_message ); + } else { + // Construct and log an error message with additional details if provided in the response + $error_message = 'Error uploading results'; + if ( isset( $response['message'] ) ) { + $error_message .= ': ' . $response['message']; + } + $error_message .= ' (HTTP status ' . (int)$http_status . ')'; + error_message( $error_message ); + } } 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 ); - + // 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( '[+] ENVIRONMENT' . "\n\n" . $env . "\n\n" ); } - -} 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( '[+] ENVIRONMENT' . "\n\n" . $env . "\n\n" ); - } diff --git a/test.php b/test.php index 18b3f4f..11bb9c9 100644 --- a/test.php +++ b/test.php @@ -1,50 +1,52 @@ $version, + 'bin' => $bin + ]; + } + } } -// Execute the PHPUnit command. -perform_operations( array( - $WPT_PHPUNIT_CMD -) ); +// Prepare an array of PHP executables. If multi-PHP is configured, use the multi-array; otherwise, use a single executable. +$php_executables = ! empty( $WPT_PHP_EXECUTABLE_MULTI_ARRAY ) ? $WPT_PHP_EXECUTABLE_MULTI_ARRAY : [ + [ + 'version' => 'default', + 'bin' => $WPT_PHP_EXECUTABLE, // Ensure this variable is defined for the single PHP executable case. + ] +]; + +/** + * Performs a series of operations to set up the test environment. This includes setting up PHPUnit commands + * and executing them, potentially over SSH if a connection string is provided. + */ +foreach ( $php_executables as $php_multi ) { + // Generate a unique test directory name based on the PHP version. + $WPT_TEST_DIR_MULTI = $WPT_TEST_DIR . '-' . crc32( $php_multi['version'] ); + + /** + * Determines the PHPUnit command to execute the test suite. + * Retrieves the PHPUnit command from the environment variable 'WPT_PHPUNIT_CMD'. If the environment + * variable is not set or is empty, it constructs a default command using the PHP executable path and + * the test directory path from environment variables, appending parameters to the PHPUnit call to + * avoid reporting useless tests. + */ + $WPT_PHPUNIT_CMD = trim( getenv( 'WPT_PHPUNIT_CMD' ) ); + if ( empty( $WPT_PHPUNIT_CMD ) ) { + $WPT_PHPUNIT_CMD = 'cd ' . escapeshellarg( $WPT_TEST_DIR_MULTI ) . ' && ' . $php_multi['bin'] . ' ./vendor/phpunit/phpunit/phpunit --dont-report-useless-tests' . $WPT_FLAVOR_TXT . $WPT_EXTRATESTS_TXT; + } + + // If an SSH connection string is provided, prepend the SSH command to the PHPUnit execution command. + if ( ! empty( $WPT_SSH_CONNECT ) ) { + $WPT_PHPUNIT_CMD = 'ssh ' . $WPT_SSH_OPTIONS . ' ' . escapeshellarg( $WPT_SSH_CONNECT ) . ' ' . escapeshellarg( $WPT_PHPUNIT_CMD ); + } + + // Execute the PHPUnit command. + perform_operations([ + $WPT_PHPUNIT_CMD + ]); +}