Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
362 changes: 362 additions & 0 deletions .github/workflows/reusable-wp-cli-tests-v1.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,362 @@
##
# A reusable workflow that runs the WP-CLI functional test suites against a WordPress build.
#
# The jobs live here rather than in wp-cli-tests.yml so that the run view shows them nested under
# a single entry for that workflow's one calling job, instead of as a flat list of a dozen or more
# top-level jobs. See wp-cli-tests.yml for what the workflow is for.
##
name: WP-CLI tests

on:
workflow_call:
inputs:
run-id:
description: 'The ID of a "Test Build Processes" run whose WordPress build should be tested. Empty to build the calling branch instead.'
type: string
default: ''
baseline-ref:
description: 'The branch of WordPress/wordpress-develop to compare the results against. Empty for trunk.'
type: string
default: ''
php-version:
description: 'The version of PHP to test with. Empty for the default.'
type: string
default: ''
packages:
description: 'A comma separated list of the WP-CLI packages to test. Empty for the default ones.'
type: string
default: ''

env:
# Inputs are passed through from the calling workflow, where they are empty for every event but
# a manual dispatch, so the defaults are applied here rather than as input defaults.
DEFAULT_PACKAGES: 'wp-cli-bundle,ability-command,ai-command,config-command,core-command,cron-command,db-command,entity-command,export-command,extension-command,import-command,media-command,rewrite-command,role-command,search-replace-command,site-health-command'
DEFAULT_PHP_VERSION: '8.5'

# Disable permissions for all available scopes by default.
# Any needed permissions should be configured at the job level.
permissions: {}

jobs:
# Builds and packages WordPress from the selected branch.
#
# Skipped when a run ID is given, as that run already produced a build to test.
build:
name: Build
uses: ./.github/workflows/reusable-build-package.yml
permissions:
contents: read
if: ${{ inputs.run-id == '' }}

# Builds and packages trunk, to compare the results against.
#
# Only used when the tests fail, but built up front and in parallel, so that comparing does not
# have to wait for a build.
build-baseline:
name: Build baseline
runs-on: ubuntu-24.04
permissions:
contents: read
timeout-minutes: 20

steps:
- name: Check out ${{ inputs.baseline-ref || 'trunk' }}
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
repository: WordPress/wordpress-develop
ref: ${{ inputs.baseline-ref || 'trunk' }}
show-progress: ${{ runner.debug == '1' && 'true' || 'false' }}
persist-credentials: false

- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version-file: '.nvmrc'
cache: npm

- name: Install npm Dependencies
run: npm ci

- name: Build WordPress
run: npm run build

- name: Create ZIP of built files
run: mv build wordpress && zip -q -r baseline.zip wordpress/.

- name: Upload ZIP as a GitHub Actions artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: wordpress-baseline
path: baseline.zip
if-no-files-found: error

# Turns the list of packages into a matrix.
prepare-matrix:
name: Prepare package matrix
runs-on: ubuntu-24.04
permissions: {}
timeout-minutes: 5
outputs:
packages: ${{ steps.packages.outputs.packages }}

steps:
- name: Build the list of packages to test
id: packages
env:
PACKAGES: ${{ inputs.packages || env.DEFAULT_PACKAGES }}
run: |
PACKAGE_JSON="$( jq -Rc 'split(",") | map(sub("^\\s+";"") | sub("\\s+$";"")) | map(select(length > 0))' <<< "${PACKAGES}" )"

if [ "${PACKAGE_JSON}" = '[]' ]; then
echo "::error::No packages to test."
exit 1
fi

echo "packages=${PACKAGE_JSON}" >> "${GITHUB_OUTPUT}"

# Runs the functional tests of a single WP-CLI package against the WordPress build.
#
# Performs the following steps:
# - Checks out the WP-CLI test suites.
# - Sets up PHP and the extensions the test suites need.
# - Installs the test suites.
# - Prepares the test database on the MySQL service container.
# - Downloads the WordPress build to test.
# - Runs the functional tests of the package against that build.
# - If any fail, runs them against the baseline build as well, and compares the results.
test:
name: ${{ matrix.package }}
runs-on: ubuntu-24.04
permissions:
contents: read
# Downloading the build of another workflow run requires reading that run.
actions: read
# The larger suites, such as those of `entity-command` and `wp-cli-bundle`, are slow.
timeout-minutes: 45
needs: [ build, build-baseline, prepare-matrix ]
if: |
always() &&
needs.prepare-matrix.result == 'success' &&
needs.build-baseline.result == 'success' &&
( needs.build.result == 'success' || needs.build.result == 'skipped' )

strategy:
fail-fast: false
matrix:
package: ${{ fromJSON( needs.prepare-matrix.outputs.packages ) }}

env:
WP_CLI_TEST_DBROOTUSER: root
WP_CLI_TEST_DBROOTPASS: root
WP_CLI_TEST_DBNAME: wp_cli_test
WP_CLI_TEST_DBUSER: wp_cli_test
WP_CLI_TEST_DBPASS: password1
WP_CLI_TEST_DBHOST: 127.0.0.1:3306
# wp-cli-tests fills the {MYSQL_HOST} and {MYSQL_PORT} placeholders from these, for
# scenarios that call the mysql client directly. Unset, the client falls back to a local socket.
MYSQL_HOST: 127.0.0.1
MYSQL_TCP_PORT: 3306

services:
# Unlike the other workflows in this repository, the port is published on a fixed number rather
# than a random one, because the test framework reads the host and port from a single
# `WP_CLI_TEST_DBHOST` environment variable that several of its scripts consume.
database:
image: mysql:8.0
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping"
--health-interval="30s"
--health-timeout="10s"
--health-retries="5"
-e MYSQL_ROOT_PASSWORD="root"

steps:
# This checkout replaces the contents of the workspace, so every `composer` invocation below
# runs against wp-cli/automated-tests rather than against this repository. None of the files of
# this repository are needed here: the WordPress being tested arrives as the build downloaded
# further down. The `behat`, `prepare-tests` and `test` scripts used below are the ones defined
# by that repository.
- name: Check out the WP-CLI test suites
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
repository: wp-cli/automated-tests
ref: main
show-progress: ${{ runner.debug == '1' && 'true' || 'false' }}
persist-credentials: false

- name: Set up PHP ${{ inputs.php-version || env.DEFAULT_PHP_VERSION }}
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # 2.37.2
with:
php-version: '${{ inputs.php-version || env.DEFAULT_PHP_VERSION }}'
extensions: gd, imagick, mysql, zip, pdo_sqlite, exif, fileinfo
coverage: none
tools: composer

# Ghostscript is needed by the tests of `media-command`, and the MySQL client by the test
# framework itself, which shells out to it to create the test database and to detect the
# version of the database server.
- name: Install Ghostscript and the MySQL client
run: |
sudo apt-get update
sudo apt-get install ghostscript mysql-client -y

- name: Change ImageMagick policy to allow pdf->png conversion
run: sudo sed -i 's/^.*policy.*coder.*none.*PDF.*//' /etc/ImageMagick-6/policy.xml

# Installing `wp-cli/wp-cli-tests` from its main branch pulls in `WP_CLI_TEST_CORE_ZIP`, which
# is what lets the test suites install WordPress from the build instead of from WordPress.org.
#
# TODO: Drop the constraint once wp-cli/wp-cli-tests 5.2.3 is released.
- name: Install the WP-CLI test suites
env:
COMPOSER_ROOT_VERSION: dev-main
run: composer require --no-interaction --no-progress "wp-cli/wp-cli-tests:dev-main"

- name: Prepare the test database
run: composer prepare-tests

# Without a run ID this is the ZIP built by the `build` job, which wraps WordPress in a
# `wordpress/` folder. With one it is the ZIP built for WordPress Playground, which wraps it in
# a `build/` folder instead. The test suites handle both.
- name: Download the WordPress build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: ${{ inputs.run-id != '' && 'wordpress-build-*' || 'wordpress-develop' }}
merge-multiple: true
path: ${{ runner.temp }}/wordpress-build
run-id: ${{ inputs.run-id || github.run_id }}
github-token: ${{ github.token }}

- name: Locate the WordPress build
id: build
run: |
ARCHIVE="$( find "${RUNNER_TEMP}/wordpress-build" -maxdepth 1 -name '*.zip' | head -n 1 )"

if [ -z "${ARCHIVE}" ]; then
echo "::error::No WordPress archive found in the downloaded artifact."
exit 1
fi

echo "archive=${ARCHIVE}" >> "${GITHUB_OUTPUT}"

- name: Download the baseline build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: wordpress-baseline
path: ${{ runner.temp }}/wordpress-baseline

- name: Check the test environment
env:
TEST_PACKAGE: 'wp-cli/${{ matrix.package }}'
WP_VERSION: trunk
WP_CLI_TEST_CORE_ZIP: ${{ steps.build.outputs.archive }}
WP_CLI_TEST_DEBUG_BEHAT_ENV: 1
run: composer behat

# `WP_VERSION` still decides which version specific tags, such as `@require-wp-6.9`, are
# filtered out. A development build cannot be compared against those, so it is reported as
# `trunk`, which runs every scenario. Leaving it unset would resolve it to the current release
# and silently skip the scenarios that only apply to newer versions of WordPress.
#
# A failure here does not fail the job by itself: whether it counts is decided by comparing
# against the baseline below.
- name: Run the ${{ matrix.package }} tests
id: tests
continue-on-error: true
env:
TEST_PACKAGE: 'wp-cli/${{ matrix.package }}'
WP_VERSION: trunk
WP_CLI_TEST_CORE_ZIP: ${{ steps.build.outputs.archive }}
WP_CLI_TEST_JUNIT_DIR: ${{ runner.temp }}/junit/build
run: composer test

- name: Run the ${{ matrix.package }} tests against the baseline
if: ${{ steps.tests.outcome == 'failure' }}
continue-on-error: true
env:
TEST_PACKAGE: 'wp-cli/${{ matrix.package }}'
WP_VERSION: trunk
WP_CLI_TEST_CORE_ZIP: ${{ runner.temp }}/wordpress-baseline/baseline.zip
WP_CLI_TEST_JUNIT_DIR: ${{ runner.temp }}/junit/baseline
run: composer test

# Reads the JUnit reports of both runs. Behat sets a test case's `line` to that of its last step,
# which every example of a scenario outline shares, so a scenario identifies by its file, that
# line and its name, which carries the example number. All are stable here because both runs use
# the same version of WP-CLI. A scenario fails if its status says so or if Behat attached a
# `<failure>` to it, which is how a failing hook such as a scenario teardown is reported while
# the status stays `passed`. The rerun reports have the final say, so that a scenario which
# failed and then passed counts as flaky.
- name: Compare the results against the baseline
if: ${{ steps.tests.outcome == 'failure' }}
env:
BUILD_REPORTS: ${{ runner.temp }}/junit/build
BASELINE_REPORTS: ${{ runner.temp }}/junit/baseline
run: |
python3 -I - "${BUILD_REPORTS}" "${BASELINE_REPORTS}" <<'PY'
import glob, os, sys
import xml.etree.ElementTree as ET

FAILED = ('failed', 'undefined')

def load(path, into):
root = ET.parse(path).getroot()
for case in root.iter('testcase'):
key = case.get('file') + ':' + case.get('line')
failed = case.get('status') in FAILED or case.find('failure') is not None
into[(key, case.get('name') or '')] = {'suite': root.get('name'), 'name': case.get('name'), 'key': key, 'failed': failed}

def read_run(directory):
scenarios, flaky, rerun = {}, set(), {}
for path in sorted(glob.glob(os.path.join(directory, '*.xml'))):
load(path, scenarios)
for path in sorted(glob.glob(os.path.join(directory, 'rerun', '*.xml'))):
load(path, rerun)
# The rerun has the final say: failing and then passing is flaky, not failing.
for key, scenario in rerun.items():
if key in scenarios and scenarios[key]['failed'] and not scenario['failed']:
flaky.add(key)
scenarios[key] = scenario
return scenarios, flaky

def failing(scenarios):
return {key for key, scenario in scenarios.items() if scenario['failed']}

candidate, flaky = read_run(sys.argv[1])
baseline, _ = read_run(sys.argv[2])

if not candidate:
print('::error::The run against the build being tested produced no results.')
sys.exit(1)

broken = sorted(failing(candidate) - failing(baseline))
known = sorted(failing(candidate) & failing(baseline))

lines = []
if broken:
lines += ['### %d scenario(s) fail only with this build' % len(broken), '', '| Scenario | Location |', '| --- | --- |']
lines += ['| %s | `%s` |' % (candidate[key]['name'], candidate[key]['key']) for key in broken]
for key in broken:
print('::error title=Fails only with this build::%s (%s)' % (candidate[key]['name'], candidate[key]['key']))
else:
lines.append('### No new failures')
if known:
lines += ['', '%d scenario(s) also fail against the baseline build, so this build did not cause them:' % len(known), '']
lines += ['- %s (`%s`)' % (candidate[key]['name'], candidate[key]['key']) for key in known]
if flaky:
lines += ['', '%d scenario(s) failed and then passed on the rerun, and were treated as flaky.' % len(flaky)]

summary = '\n'.join(lines) + '\n'
print(summary)
if os.environ.get('GITHUB_STEP_SUMMARY'):
with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as handle:
handle.write(summary)

sys.exit(1 if broken else 0)
PY

- name: Report a clean run
if: ${{ steps.tests.outcome == 'success' }}
run: echo '### All scenarios passed' >> "${GITHUB_STEP_SUMMARY}"
Loading
Loading