From f0cbb65e77e4681be975c71c47250ac7d90a4103 Mon Sep 17 00:00:00 2001 From: Marcel Martinez Date: Wed, 4 Nov 2026 22:19:11 -0600 Subject: [PATCH 01/42] feat(warden): serve the environment for browser-based tests The Warden environment already brings up nginx, Varnish and Traefik, but nothing installed into it is reachable from the runner itself. Integration tests never noticed, because they drive Magento's own bootstrap rather than making HTTP requests. Three things have to be true before a browser can reach the storefront, and each is added here behind a default that preserves current behaviour: - setup:install needs --base-url, or Magento redirects to its default base URL regardless of where the environment is served - the Traefik hostname needs resolving on the runner, which has no dnsmasq - static content needs deploying, or the storefront returns 200 and renders nothing Also exposes the served URL as an output, so a caller does not have to reconstruct it, and makes the admin frontName and the Warden environment naming configurable rather than hardcoded -- a predictable admin URL is a prerequisite for testing the admin at all. Existing callers pass none of the new inputs and are unaffected. --- warden/setup-environment/README.md | 84 +++++++++++++++++++++ warden/setup-environment/action.yml | 111 +++++++++++++++++++++++++++- 2 files changed, 191 insertions(+), 4 deletions(-) create mode 100644 warden/setup-environment/README.md diff --git a/warden/setup-environment/README.md b/warden/setup-environment/README.md new file mode 100644 index 00000000..77aaa131 --- /dev/null +++ b/warden/setup-environment/README.md @@ -0,0 +1,84 @@ +# Setup Mage-OS in Warden + +Brings up a full Mage-OS service stack on the runner using +[Warden](https://github.com/wardenenv/warden), and optionally installs Magento +into it. + +Used by [`full-integration-tests.yaml`](../../.github/workflows/full-integration-tests.yaml) +and [`nx-integration-tests.yml`](../../.github/workflows/nx-integration-tests.yml). + +## Usage + +```yaml +- uses: mage-os/github-actions/warden/setup-environment@main + with: + php_version: '8.4' + database: 'mariadb:11.4' + search: 'opensearch:3.3' + run_composer_install: '1' + run_setup_install: '1' +``` + +### Browser-based tests + +PHPUnit suites drive Magento's own bootstrap and never make an HTTP request, so +they need nothing beyond the above. A browser does. Three things have to be true +before one can reach the storefront, and all three are off by default: + +```yaml +- uses: mage-os/github-actions/warden/setup-environment@main + id: warden + with: + php_version: '8.4' + run_composer_install: '1' + run_setup_install: '1' + # Install on the URL the environment is actually served on, otherwise + # Magento redirects the browser to its default base URL. + base_url: 'https://app.mageos.test/' + # Warden uses dnsmasq locally; a runner has no such resolver. + configure_host_resolution: '1' + # Without deployed static content the storefront returns 200 and renders + # nothing. + run_static_content_deploy: '1' + static_content_themes: 'Magento/luma' + +- run: npx playwright test + env: + E2E_BASE_URL: ${{ steps.warden.outputs.base_url }} +``` + +## Inputs + +| Name | Default | Description | +| --- | --- | --- | +| `warden_version` | `0.14.2` | Warden version to use. | +| `php_version` | `8.2` | PHP version in the Warden containers. | +| `composer_version` | `2.2.22` | Composer version to use. | +| `database` | `mariadb:10.6` | `distribution:version` of the database. | +| `search` | `opensearch:2.5` | Search engine; `elasticsearch:*` or `opensearch:*`. | +| `varnish` | `varnish:7.3` | Varnish version, or `null` to disable. | +| `rabbitmq` | `rabbitmq:3.11` | RabbitMQ version, or `null` to disable. | +| `redis` | `redis:7.0` | Redis version, or `null` to disable. | +| `base_directory` | `./` | Base directory of the Mage-OS codebase. | +| `run_composer_install` | `0` | Run `composer install`. | +| `run_setup_install` | `0` | Run `setup:install`. | +| `run_setup_upgrade` | `0` | Run `setup:upgrade`. | +| `run_reindex` | `0` | Run `indexer:reindex`. | +| `run_production_deploy_mode` | `0` | Run `deploy:mode:set production`. | +| `run_magento_config_preset` | `0` | Apply the test-oriented config preset. | +| `run_admin_user_creation` | `0` | Create an `admin` / `abcABC123` user. | +| `env_name` | `mageos` | `WARDEN_ENV_NAME`. | +| `traefik_domain` | `mageos.test` | `TRAEFIK_DOMAIN`. | +| `traefik_subdomain` | `app` | `TRAEFIK_SUBDOMAIN`. | +| `backend_frontname` | `admin` | Admin frontName passed to `setup:install`. | +| `base_url` | *(empty)* | Passed as `--base-url` with `--use-rewrites=1`. Empty leaves Magento's default. | +| `configure_host_resolution` | `0` | Resolve `.` to `127.0.0.1` on the runner. | +| `run_static_content_deploy` | `0` | Run `setup:static-content:deploy`. | +| `static_content_languages` | `en_US` | Space separated locales to deploy. | +| `static_content_themes` | *(empty)* | Space separated themes, e.g. `Magento/luma`. Empty deploys every theme. | + +## Outputs + +| Name | Description | +| --- | --- | +| `base_url` | The URL the environment is served on, derived from `traefik_subdomain` and `traefik_domain`. | diff --git a/warden/setup-environment/action.yml b/warden/setup-environment/action.yml index f38b9e8b..275259f2 100644 --- a/warden/setup-environment/action.yml +++ b/warden/setup-environment/action.yml @@ -83,6 +83,56 @@ inputs: default: "./" description: "Base directory for the Mage-OS codebase." + env_name: + required: false + default: "mageos" + description: "Warden environment name (WARDEN_ENV_NAME)." + + traefik_domain: + required: false + default: "mageos.test" + description: "Traefik domain the environment is served on (TRAEFIK_DOMAIN)." + + traefik_subdomain: + required: false + default: "app" + description: "Traefik subdomain the environment is served on (TRAEFIK_SUBDOMAIN)." + + backend_frontname: + required: false + default: "admin" + description: "Admin frontName passed to setup:install. Pinning this keeps the admin URL predictable, which browser-based tests need." + + base_url: + required: false + default: "" + description: "Base URL passed to setup:install as --base-url. Empty leaves Magento's default, which is what non-browser test suites want." + + configure_host_resolution: + required: false + default: "0" + description: "Whether to resolve the Traefik hostname on the runner itself, so tools outside the containers (a browser, curl) can reach the store." + + run_static_content_deploy: + required: false + default: "0" + description: "Whether to run setup:static-content:deploy. Required before a browser can render the storefront; pointless for PHPUnit suites." + + static_content_languages: + required: false + default: "en_US" + description: "Space separated locales to deploy static content for." + + static_content_themes: + required: false + default: "" + description: "Space separated themes to deploy static content for, e.g. 'Magento/luma'. Empty deploys every theme, which is considerably slower." + +outputs: + base_url: + description: "The URL the environment is served on, for callers that need to point a browser at it." + value: ${{ steps.resolve-base-url.outputs.base_url }} + runs: using: composite steps: @@ -104,6 +154,9 @@ runs: VARNISH: ${{ inputs.varnish }} RABBITMQ: ${{ inputs.rabbitmq }} REDIS: ${{ inputs.redis }} + ENV_NAME: ${{ inputs.env_name }} + TRAEFIK_DOMAIN_INPUT: ${{ inputs.traefik_domain }} + TRAEFIK_SUBDOMAIN_INPUT: ${{ inputs.traefik_subdomain }} run: | # Splitting database input to distribution and version DB_DISTRIBUTION=${DATABASE%%:*} @@ -149,12 +202,12 @@ runs: # Creating .env file by substituting variables directly in the template cat << EOF > .env - WARDEN_ENV_NAME=mageos + WARDEN_ENV_NAME=${ENV_NAME} WARDEN_ENV_TYPE=magento2 WARDEN_WEB_ROOT=/ - TRAEFIK_DOMAIN=mageos.test - TRAEFIK_SUBDOMAIN=app + TRAEFIK_DOMAIN=${TRAEFIK_DOMAIN_INPUT} + TRAEFIK_SUBDOMAIN=${TRAEFIK_SUBDOMAIN_INPUT} WARDEN_DB=1 WARDEN_ELASTICSEARCH=${WARDEN_ELASTICSEARCH} @@ -196,6 +249,15 @@ runs: echo ".env created" cat .env + - name: Resolve served base URL + id: resolve-base-url + shell: bash + env: + TRAEFIK_DOMAIN_INPUT: ${{ inputs.traefik_domain }} + TRAEFIK_SUBDOMAIN_INPUT: ${{ inputs.traefik_subdomain }} + run: | + echo "base_url=https://${TRAEFIK_SUBDOMAIN_INPUT}.${TRAEFIK_DOMAIN_INPUT}/" >> "$GITHUB_OUTPUT" + - name: Warden svc up && Warden env up working-directory: ${{ inputs.base_directory }} shell: bash @@ -211,6 +273,18 @@ runs: export WARDEN="$(dirname $(pwd))/warden/bin/warden" ${WARDEN} env exec -T php-fpm sudo chmod -R 777 . + - name: Resolve the Traefik hostname on the runner + if: ${{ inputs.configure_host_resolution == '1' }} + shell: bash + env: + HOSTNAME_TO_RESOLVE: ${{ inputs.traefik_subdomain }}.${{ inputs.traefik_domain }} + run: | + # Warden relies on dnsmasq locally; a runner has no such resolver, so + # anything running outside the containers -- a browser, curl -- cannot + # reach the store without this. + echo "127.0.0.1 ${HOSTNAME_TO_RESOLVE}" | sudo tee -a /etc/hosts + getent hosts "${HOSTNAME_TO_RESOLVE}" + - name: Wait for environment to be ready working-directory: ${{ inputs.base_directory }} shell: bash @@ -263,6 +337,8 @@ runs: RABBITMQ: ${{ inputs.rabbitmq }} VARNISH: ${{ inputs.varnish }} RUN_SETUP_INSTALL: ${{ inputs.run_setup_install }} + BACKEND_FRONTNAME: ${{ inputs.backend_frontname }} + BASE_URL: ${{ inputs.base_url }} run: | if [ $RUN_SETUP_INSTALL == "1" ]; then SEARCH_ENGINE_VERSION=${SEARCH##*:} @@ -291,7 +367,13 @@ runs: esac declare -a PARAMETERS - PARAMETERS+=(--backend-frontname=admin --db-host=db --db-name=magento --db-user=magento --db-password=magento) + PARAMETERS+=(--backend-frontname=${BACKEND_FRONTNAME} --db-host=db --db-name=magento --db-user=magento --db-password=magento) + + # Magento otherwise installs on its default base URL, which a browser + # pointed at the Traefik hostname would be redirected away from. + if [[ -n $BASE_URL ]]; then + PARAMETERS+=(--base-url=${BASE_URL} --use-rewrites=1) + fi if [[ -n $REDIS ]]; then PARAMETERS+=(--session-save=redis --session-save-redis-host=redis --session-save-redis-port=6379 --session-save-redis-db=2 --cache-backend=redis --cache-backend-redis-server=redis --cache-backend-redis-db=0 --cache-backend-redis-port=6379 --page-cache=redis --page-cache-redis-server=redis --page-cache-redis-db=1 --page-cache-redis-port=6379) @@ -374,6 +456,27 @@ runs: echo "Skipping deploy:mode:set production" fi + - name: Deploy static content + working-directory: ${{ inputs.base_directory }} + shell: bash + env: + LANGUAGES: ${{ inputs.static_content_languages }} + THEMES: ${{ inputs.static_content_themes }} + run: | + if [ ${{ inputs.run_static_content_deploy }} == "1" ]; then + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + declare -a DEPLOY_ARGS + DEPLOY_ARGS+=(${LANGUAGES}) + DEPLOY_ARGS+=(-f) + # Deploying every theme costs minutes a browser test does not need. + for THEME in ${THEMES}; do + DEPLOY_ARGS+=(--theme "${THEME}") + done + ${WARDEN} env exec -T php-fpm bin/magento setup:static-content:deploy "${DEPLOY_ARGS[@]}" + else + echo "Skipping setup:static-content:deploy" + fi + - name: Run Magento Re-indexation working-directory: ${{ inputs.base_directory }} shell: bash From 291691ca2e8e57b2b08f6878c7e12f6bbc284b47 Mon Sep 17 00:00:00 2001 From: Marcel Martinez Date: Thu, 5 Nov 2026 08:16:35 -0600 Subject: [PATCH 02/42] test(e2e): run a storefront smoke test against the Warden environment Adds the canary for the browser-serving inputs on warden/setup-environment: it installs Mage-OS, serves it, deploys Luma's static content and drives a browser at the result, following the _internal-* convention the other actions in this repository use. The suite lives with the demo package, as the dummy e2e test already did. It stays deliberately small: its job is to prove a storefront is being served, not to cover a store's behaviour. The assertions are chosen to fail against things that should not pass. A 200 is not evidence of a storefront -- the admin login page, a CMS no-route page and a Magento error page all answer 200 with a header, a footer and a title -- so the suite checks the resolved route in the body class, Luma's minicart block and whether a stylesheet actually parsed into rules. Without the last one it would pass against a store whose pub/static was never deployed. The suite now refuses to start without PLAYWRIGHT_BASE_URL rather than falling back to a public demo store, since a suite that reports green about a store nobody asked about is worse than one that will not run. --- .github/workflows/_internal-e2e.yaml | 121 ++++++++++++++++++ _test/demo-package/Test/e2e/.env | 1 - _test/demo-package/Test/e2e/.env.example | 3 + _test/demo-package/Test/e2e/.gitignore | 4 + _test/demo-package/Test/e2e/README.md | 46 ++++++- .../Test/e2e/hello-magento.spec.ts | 50 +++++--- _test/demo-package/Test/e2e/package-lock.json | 77 +++++++++++ _test/demo-package/Test/e2e/package.json | 13 ++ .../Test/e2e/playwright.config.ts | 33 ++++- 9 files changed, 326 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/_internal-e2e.yaml delete mode 100644 _test/demo-package/Test/e2e/.env create mode 100644 _test/demo-package/Test/e2e/.env.example create mode 100644 _test/demo-package/Test/e2e/.gitignore create mode 100644 _test/demo-package/Test/e2e/package-lock.json create mode 100644 _test/demo-package/Test/e2e/package.json diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml new file mode 100644 index 00000000..894fd704 --- /dev/null +++ b/.github/workflows/_internal-e2e.yaml @@ -0,0 +1,121 @@ +name: E2E Test + +on: + workflow_dispatch: {} + push: + branches: + - main + paths: + - "_test/demo-package/Test/e2e/**" + - "warden/**" + - "setup-magento/**" + - ".github/workflows/_internal-e2e.yaml" + - "!(**/*.md)" + pull_request: + branches: + - main + paths: + - "_test/demo-package/Test/e2e/**" + - "warden/**" + - "setup-magento/**" + - ".github/workflows/_internal-e2e.yaml" + - "!(**/*.md)" + +# Standing up the whole stack costs a runner for a while; there is no reason to +# keep paying for a run whose commit has already been superseded. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + storefront-smoke-test: + name: "storefront smoke test" + if: "!startsWith(github.head_ref, 'release-please')" + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + # setup:install, the hostname the runner resolves and the URL the browser + # opens all have to agree, so they are derived from one place. + TRAEFIK_DOMAIN: mageos.test + TRAEFIK_SUBDOMAIN: app + E2E_DIRECTORY: _test/demo-package/Test/e2e + # Pinned rather than taken from supported-version: this workflow is here + # to tell us whether the action still serves a store, so a service bump + # elsewhere should not change what it reports. The release pipeline picks + # its own versions. + PHP_VERSION: "8.4" + COMPOSER_VERSION: "2.10.2" + steps: + - uses: actions/checkout@v6 + + # mode: extension is how the other internal workflows get a project onto + # disk -- composer create-project --no-install, into ./_ghamagento. The + # dependencies are then installed inside the container, by the PHP version + # that will serve them. + - name: Create the Mage-OS project + uses: ./setup-magento + with: + php-version: ${{ env.PHP_VERSION }} + tools: "composer:v2" + mode: extension + magento_repository: "https://repo.mage-os.org/" + magento_version: "mage-os/project-community-edition:4.0.0" + + - name: Serve the store in Warden + id: warden + uses: ./warden/setup-environment + with: + base_directory: "./_ghamagento" + php_version: ${{ env.PHP_VERSION }} + composer_version: ${{ env.COMPOSER_VERSION }} + database: "mariadb:11.8" + search: "opensearch:3.4" + rabbitmq: "rabbitmq:4.2" + redis: "redis:7.4" + varnish: "varnish:8.0" + run_composer_install: 1 + run_setup_install: 1 + run_admin_user_creation: 1 + run_magento_config_preset: 1 + run_reindex: 1 + traefik_domain: ${{ env.TRAEFIK_DOMAIN }} + traefik_subdomain: ${{ env.TRAEFIK_SUBDOMAIN }} + # The three inputs a browser needs, and nothing a PHPUnit suite pays for. + base_url: "https://${{ env.TRAEFIK_SUBDOMAIN }}.${{ env.TRAEFIK_DOMAIN }}/" + configure_host_resolution: 1 + run_static_content_deploy: 1 + static_content_themes: "Magento/luma" + + # Separate from the test run so that "the store was never reachable" and + # "the store rendered the wrong thing" are different red steps. + - name: Confirm the store answers on the resolved hostname + run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: ${{ env.E2E_DIRECTORY }}/package-lock.json + + - name: Install Playwright + working-directory: ${{ env.E2E_DIRECTORY }} + run: | + npm ci + npx playwright install --with-deps chromium + + - name: Run the storefront smoke test + working-directory: ${{ env.E2E_DIRECTORY }} + env: + PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} + run: npx playwright test + + - name: Upload the Playwright report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: playwright-report + path: | + ${{ env.E2E_DIRECTORY }}/playwright-report + ${{ env.E2E_DIRECTORY }}/test-results + retention-days: 7 + if-no-files-found: ignore diff --git a/_test/demo-package/Test/e2e/.env b/_test/demo-package/Test/e2e/.env deleted file mode 100644 index d0f3f161..00000000 --- a/_test/demo-package/Test/e2e/.env +++ /dev/null @@ -1 +0,0 @@ -PLAYWRIGHT_BASE_URL=https://hyva-demo.elgentos.io/ diff --git a/_test/demo-package/Test/e2e/.env.example b/_test/demo-package/Test/e2e/.env.example new file mode 100644 index 00000000..735dc1a9 --- /dev/null +++ b/_test/demo-package/Test/e2e/.env.example @@ -0,0 +1,3 @@ +# The store the suite opens. There is no default: a suite that silently tests +# someone else's demo store is worse than one that refuses to start. +PLAYWRIGHT_BASE_URL=https://app.mageos.test/ diff --git a/_test/demo-package/Test/e2e/.gitignore b/_test/demo-package/Test/e2e/.gitignore new file mode 100644 index 00000000..3c3e172c --- /dev/null +++ b/_test/demo-package/Test/e2e/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +playwright-report/ +test-results/ +.env diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 36c8d271..76e1df29 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -1,5 +1,41 @@ -cd e2e -npm install -D @playwright/test -npx playwright install -npm install -D dotenv -npx playwright test hello-magento.spec.ts +# Storefront smoke test + +A deliberately small Playwright suite whose only job is to prove that a Mage-OS +storefront is **being served** -- installed, reachable over HTTP(S) and +rendering with its static content deployed. + +It is the canary for [`warden/setup-environment`](../../../../warden/setup-environment): +`.github/workflows/_internal-e2e.yaml` stands a store up with that action on +every change to it and runs this suite against the result. + +It is not a test suite for a store's behaviour. Product, cart and checkout +coverage belongs in a suite of its own, with its own fixtures. + +## Running it against a store + +```bash +cp .env.example .env # then point PLAYWRIGHT_BASE_URL at your store +npm ci +npx playwright install --with-deps chromium +npm test +``` + +There is no default base URL. A suite that silently falls back to some public +demo store reports green about a store nobody asked about. + +## Why the assertions look like that + +A `200` is not evidence of a storefront. The admin login page, a CMS no-route +page and a Magento error page all answer `200`, and all of them have a header, +a footer, a `` and no console errors. So each assertion here is one that +fails against something that should not pass: + +| Assertion | What it rejects | +| --- | --- | +| `body` has `cms-index-index` | Any other route answering 200 -- `/admin`, a 404 CMS page | +| `[data-block="minicart"]` is attached | A storefront page rendered without the Luma layout | +| A stylesheet parsed into CSS rules | A store whose `pub/static` was never deployed | + +Before changing an assertion, check that it still fails for the reason it was +written -- point `PLAYWRIGHT_BASE_URL` at the admin URL, or clear `pub/static`, +and watch the step go red. diff --git a/_test/demo-package/Test/e2e/hello-magento.spec.ts b/_test/demo-package/Test/e2e/hello-magento.spec.ts index 37762363..5de89855 100644 --- a/_test/demo-package/Test/e2e/hello-magento.spec.ts +++ b/_test/demo-package/Test/e2e/hello-magento.spec.ts @@ -1,20 +1,40 @@ import { test, expect } from '@playwright/test'; -test.describe('Page health checks', () => { - test('Homepage_returns_200', {tag: ['@smoke', '@cold']}, async ({page}) => { - const homepageURL = process.env.PLAYWRIGHT_BASE_URL || process.env.BASE_URL; - if (!homepageURL) { - throw new Error("PLAYWRIGHT_BASE_URL has not been defined in the .env file."); - } +// A 200 proves very little on its own: the admin login page, a CMS no-route +// page and a Magento error page all answer 200 and all carry a header, a +// footer and a title. Every assertion below is here because it fails on +// something a storefront check should not accept. +test.describe('Storefront smoke test', () => { + test('serves the Luma homepage with its static content deployed', { tag: ['@smoke', '@cold'] }, async ({ page }) => { + const response = await page.goto('/'); - const homepageResponsePromise = page.waitForResponse(homepageURL); - await page.goto(homepageURL); - const homepageResponse = await homepageResponsePromise; - expect(homepageResponse.status(), 'Homepage should return 200').toBe(200); + await test.step('the homepage responds 200', async () => { + expect(response?.status(), 'the homepage should respond 200').toBe(200); + }); - const pageTtitle = page.getByRole('heading', {level: 1}) + await test.step('the response is the storefront homepage, not some other 200', async () => { + // Luma puts the resolved route in the body class, which is the + // cheapest way to tell the homepage apart from /admin or a 404. + await expect(page.locator('body')).toHaveClass(/cms-index-index/); + await expect(page.locator('[data-block="minicart"]')).toBeAttached(); + }); - await expect(pageTtitle, 'Homepage has a visible title').toBeVisible(); - await expect(pageTtitle).toHaveText(/\S+/); - }) -}) + await test.step('static content is deployed', async () => { + await expect(page.locator('link[rel="stylesheet"]').first()).toBeAttached(); + + // A stylesheet that 404s is still a link element, so ask the + // browser whether any of them parsed into rules. Without this the + // test passes against a store whose pub/static is empty. + const ruleCount = await page.evaluate(() => + Array.from(document.styleSheets).reduce((total, sheet) => { + try { + return total + sheet.cssRules.length; + } catch { + return total; + } + }, 0), + ); + expect(ruleCount, 'at least one stylesheet should have loaded').toBeGreaterThan(0); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/package-lock.json b/_test/demo-package/Test/e2e/package-lock.json new file mode 100644 index 00000000..363816ae --- /dev/null +++ b/_test/demo-package/Test/e2e/package-lock.json @@ -0,0 +1,77 @@ +{ + "name": "demo-package-e2e", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "demo-package-e2e", + "version": "0.0.0", + "devDependencies": { + "@playwright/test": "1.64.1", + "dotenv": "^18.0.9" + } + }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/dotenv": { + "version": "18.0.9", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.9.tgz", + "integrity": "sha512-3fVOW4cB02R066PUSwn8O4TJyz9NckQl7F81blIbaq9jKBm2tSmOKky7ZHIXzGvkVPXCSn6jkpziBPZdGFs8Tw==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "dotenv": "dist/index.cjs" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/_test/demo-package/Test/e2e/package.json b/_test/demo-package/Test/e2e/package.json new file mode 100644 index 00000000..65e5465a --- /dev/null +++ b/_test/demo-package/Test/e2e/package.json @@ -0,0 +1,13 @@ +{ + "name": "demo-package-e2e", + "version": "0.0.0", + "private": true, + "description": "Minimal Playwright suite proving a Mage-OS storefront is actually served.", + "scripts": { + "test": "playwright test" + }, + "devDependencies": { + "@playwright/test": "1.64.1", + "dotenv": "^18.0.9" + } +} diff --git a/_test/demo-package/Test/e2e/playwright.config.ts b/_test/demo-package/Test/e2e/playwright.config.ts index a71c8359..fc1f2550 100644 --- a/_test/demo-package/Test/e2e/playwright.config.ts +++ b/_test/demo-package/Test/e2e/playwright.config.ts @@ -1,8 +1,39 @@ -import { defineConfig } from '@playwright/test'; +import { defineConfig, devices } from '@playwright/test'; import dotenv from 'dotenv'; dotenv.config(); +const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? process.env.BASE_URL; + +if (!baseURL) { + throw new Error( + 'No store to test: set PLAYWRIGHT_BASE_URL, e.g. https://app.mageos.test/ (see .env.example).', + ); +} + export default defineConfig({ testDir: '.', + // A cold Magento page can take a while on a shared runner; everything here + // is deliberately slower than a Playwright default. + timeout: 120_000, + expect: { timeout: 20_000 }, + workers: 1, + fullyParallel: false, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + reporter: process.env.CI + ? [['github'], ['list'], ['html', { open: 'never' }]] + : [['list'], ['html', { open: 'never' }]], + use: { + baseURL, + // Warden serves the environment under its own certificate authority, + // which is not installed on a GitHub runner. + ignoreHTTPSErrors: true, + navigationTimeout: 90_000, + actionTimeout: 20_000, + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], }); From 8971c3d773c005d686dfb04d230120860fb60c67 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Thu, 5 Nov 2026 08:24:11 -0600 Subject: [PATCH 03/42] test(e2e): check this repository out into a subdirectory The first run failed in the post phase of the Warden step: the local action could no longer be found. warden/setup-environment checks the Warden CLI out into warden/ at the workspace root, which is exactly where this repository keeps that action, so the checkout landed on top of it. Checking the repository out into actions/ leaves the workspace root free for the Warden CLI, which the steps reach as $(dirname $(pwd))/warden/bin/warden. --- .github/workflows/_internal-e2e.yaml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 894fd704..a7984863 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -38,7 +38,7 @@ jobs: # opens all have to agree, so they are derived from one place. TRAEFIK_DOMAIN: mageos.test TRAEFIK_SUBDOMAIN: app - E2E_DIRECTORY: _test/demo-package/Test/e2e + E2E_DIRECTORY: actions/_test/demo-package/Test/e2e # Pinned rather than taken from supported-version: this workflow is here # to tell us whether the action still serves a store, so a service bump # elsewhere should not change what it reports. The release pipeline picks @@ -46,14 +46,19 @@ jobs: PHP_VERSION: "8.4" COMPOSER_VERSION: "2.10.2" steps: + # Not at the workspace root: warden/setup-environment checks the Warden + # CLI out into warden/ there, which is where this repository keeps that + # action, and the checkout would land on top of it. - uses: actions/checkout@v6 + with: + path: actions # mode: extension is how the other internal workflows get a project onto # disk -- composer create-project --no-install, into ./_ghamagento. The # dependencies are then installed inside the container, by the PHP version # that will serve them. - name: Create the Mage-OS project - uses: ./setup-magento + uses: ./actions/setup-magento with: php-version: ${{ env.PHP_VERSION }} tools: "composer:v2" @@ -63,7 +68,7 @@ jobs: - name: Serve the store in Warden id: warden - uses: ./warden/setup-environment + uses: ./actions/warden/setup-environment with: base_directory: "./_ghamagento" php_version: ${{ env.PHP_VERSION }} From 100535d4453480a7ad7bb38a4df8ecb02a06b6dc Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Thu, 5 Nov 2026 10:52:01 -0600 Subject: [PATCH 04/42] docs(e2e): correct how to verify an assertion still bites The README told the reader to point PLAYWRIGHT_BASE_URL at the admin URL and watch the test go red. It does not go red: page.goto("/") resolves against the origin and drops the path, so the run hits the homepage again and passes -- the exact vacuous green this suite exists to refuse. Replacing it with a throwaway spec that navigates to the admin path directly, and the output it produces against a real store. --- _test/demo-package/Test/e2e/README.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 76e1df29..cd5d0eda 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -37,5 +37,28 @@ fails against something that should not pass: | A stylesheet parsed into CSS rules | A store whose `pub/static` was never deployed | Before changing an assertion, check that it still fails for the reason it was -written -- point `PLAYWRIGHT_BASE_URL` at the admin URL, or clear `pub/static`, -and watch the step go red. +written. Do that with a throwaway spec, not by repointing `PLAYWRIGHT_BASE_URL` +at the admin URL: a base URL with a path in it will not do what you expect, +because `page.goto("/")` resolves against the origin and drops the path, so you +end up testing the homepage again and watching it pass. + +```ts +// negative-control.spec.ts -- delete it afterwards +import { test, expect } from "@playwright/test"; + +test("the admin login page must not satisfy the homepage assertions", async ({ page }) => { + const response = await page.goto("/admin"); // your backend frontName + expect(response?.status()).toBe(200); // it answers 200 -- that is the point + await expect(page.locator("body")).toHaveClass(/cms-index-index/); +}); +``` + +Against a real store that fails on the body class alone, with the 200 and the +stylesheets both satisfied: + +``` +Expected pattern: /cms-index-index/ +Received string: "m137-admin-theme adminhtml-auth-login page-layout-admin-login" +``` + +For the static content assertion, clear `pub/static` and reload. From fed2ea69257bebbd3eae4cc99d3beb73f16dd304 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Thu, 5 Nov 2026 11:19:04 -0600 Subject: [PATCH 05/42] test(e2e): keep the evidence from the first failure trace: on-first-retry only produces a trace once a test has failed and been retried. A gate that fails is read by someone deciding whether to ship, and "re-run it and watch" is not an answer at that point, so the first failure now carries its own trace. Report artifacts are kept for 30 days rather than 7, long enough to outlive a release weekend. --- .github/workflows/_internal-e2e.yaml | 2 +- _test/demo-package/Test/e2e/playwright.config.ts | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index a7984863..3dea4c20 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -122,5 +122,5 @@ jobs: path: | ${{ env.E2E_DIRECTORY }}/playwright-report ${{ env.E2E_DIRECTORY }}/test-results - retention-days: 7 + retention-days: 30 if-no-files-found: ignore diff --git a/_test/demo-package/Test/e2e/playwright.config.ts b/_test/demo-package/Test/e2e/playwright.config.ts index fc1f2550..eed3cadf 100644 --- a/_test/demo-package/Test/e2e/playwright.config.ts +++ b/_test/demo-package/Test/e2e/playwright.config.ts @@ -31,7 +31,11 @@ export default defineConfig({ ignoreHTTPSErrors: true, navigationTimeout: 90_000, actionTimeout: 20_000, - trace: 'on-first-retry', + // retain-on-failure, not on-first-retry: the first failure is the one + // that has to carry its own evidence. A release gate that fails is + // read by someone deciding whether to ship, and "re-run it and watch" + // is not an answer at that point. + trace: 'retain-on-failure', screenshot: 'only-on-failure', video: 'retain-on-failure', }, From 99b519e2e3b3d27cbebe0042f17b2a89f94dd93f Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 21:44:46 -0600 Subject: [PATCH 06/42] test(e2e): place a guest order against the served store The homepage check proves a store is served. It does not prove a store can take money. This walks the deepest path a storefront check can: category listing, product page, cart, shipping address, rate selection, payment, order. It touches the price index, the quote, the shipping and payment method pools, order placement, and the private-content sections Varnish has to punch holes for. That path needs a salable product, which a bare setup:install does not have. fixtures/mageos-e2e.xml seeds the least data it takes: 20 simple products with deterministic SKUs, one configurable, two categories in the main navigation. 12s wall clock on Mage-OS 4.0.0 under Warden, including the reindex the command runs itself, and idempotent. Core ships no profile for functional seeding -- the smallest of the five performance profiles generates 800 products, 100 images and 80 orders, because those profiles exist to benchmark a store under catalog weight. Sample data was the other option and is worse for a gate: its content changes between releases, so an assertion on a product name is an assertion about sample data rather than about Mage-OS. Verified both directions against a Warden store: green with three persisted guest orders carrying Flat Rate and a $6.00 grand total, and red at the rate-selection step with carriers/flatrate/active set to 0. --- _test/demo-package/Test/e2e/README.md | 76 ++++++++- .../Test/e2e/fixtures/mageos-e2e.xml | 96 +++++++++++ .../Test/e2e/guest-checkout.spec.ts | 158 ++++++++++++++++++ 3 files changed, 324 insertions(+), 6 deletions(-) create mode 100644 _test/demo-package/Test/e2e/fixtures/mageos-e2e.xml create mode 100644 _test/demo-package/Test/e2e/guest-checkout.spec.ts diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index cd5d0eda..daf1bd8b 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -1,15 +1,18 @@ -# Storefront smoke test +# Storefront tests -A deliberately small Playwright suite whose only job is to prove that a Mage-OS -storefront is **being served** -- installed, reachable over HTTP(S) and -rendering with its static content deployed. +A small Playwright suite that proves a Mage-OS storefront is **being served** +and **can take an order** -- installed, reachable over HTTP(S), rendering with +its static content deployed, and able to carry a guest from a category listing +to a persisted order. It is the canary for [`warden/setup-environment`](../../../../warden/setup-environment): `.github/workflows/_internal-e2e.yaml` stands a store up with that action on every change to it and runs this suite against the result. -It is not a test suite for a store's behaviour. Product, cart and checkout -coverage belongs in a suite of its own, with its own fixtures. +| Spec | Needs fixtures | Asserts | +| --- | --- | --- | +| `hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | +| `guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | ## Running it against a store @@ -20,6 +23,9 @@ npx playwright install --with-deps chromium npm test ``` +`guest-checkout.spec.ts` needs a salable product, which a bare `setup:install` +does not have. Seed one first -- see [Fixtures](#fixtures). + There is no default base URL. A suite that silently falls back to some public demo store reports green about a store nobody asked about. @@ -62,3 +68,61 @@ Received string: "m137-admin-theme adminhtml-auth-login page-layout-admin-login ``` For the static content assertion, clear `pub/static` and reload. + +## Fixtures + +`fixtures/mageos-e2e.xml` is a performance-toolkit profile, run with the +command the toolkit ships: + +```bash +bin/magento setup:performance:generate-fixtures path/to/fixtures/mageos-e2e.xml +``` + +Measured on Mage-OS 4.0.0 under Warden: **12s wall clock**, including the +reindex the command runs itself -- no separate `indexer:reindex` needed. It is +idempotent: re-running it does not duplicate anything. + +It produces 20 simple products (`product_dynamic_1` .. `product_dynamic_20`), +one configurable with three variations, and two categories that appear in the +main navigation. The SKUs are deterministic, which is the thing sample data +cannot offer: no assertion breaks because a product was renamed upstream. + +### Why not a profile that already exists + +Core ships five profiles, and the smallest is not small: + +| Profile | simple products | categories | customers | orders | images | +| --- | --- | --- | --- | --- | --- | +| `small` | 800 | 30 | 200 | 80 | 100 | +| `medium` | 24,000 | 300 | 2,000 | 50,000 | 1,000 | +| `large` | 300,000 | 3,000 | 5,000 | 100,000 | 2,000 | + +They exist to benchmark a store under catalog weight. Core ships nothing for +functional seeding, so this profile is that. + +### Why not sample data + +`magento2-sample-data` is mirrored into `repo.mage-os.org`, so it is installable +without Adobe credentials. But it is hundreds of megabytes, and its *content* +changes between releases -- an assertion on "Joust Duffle Bag" is an assertion +about sample data, not about Mage-OS. A gate that goes red because a product was +renamed is a gate people switch off. + +### Two things to know about the profile + +`small.xml` sets `admin/security/use_form_key` to `0` and +`admin_account_sharing` to `1`. Reasonable for load testing, wrong here: a gate +running against a store with admin CSRF protection disabled is not testing the +store we ship. Do not copy those over. + +`ConfigsApplyFixture` iterates `$configs['config']` as a list, but a single +`<config>` element collapses to a flat map, so the fixture iterates that +element's own values and fatals with `Cannot access offset of type string on +string`. `small.xml` carries four entries, so upstream never sees it. Keep at +least two in the `<configs>` block. + +## What the checkout spec does not cover + +Registered-customer checkout, a real payment gateway, taxes, discounts and +multi-address shipping. Each wants fixtures of its own, and none of them is on +the path between "we tagged a release" and "a shopper can buy something". diff --git a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml new file mode 100644 index 00000000..1fce5599 --- /dev/null +++ b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml @@ -0,0 +1,96 @@ +<?xml version="1.0"?> +<!-- + A fixture profile for the Mage-OS storefront check. + + The performance toolkit ships five profiles, and the smallest, small.xml, + generates 800 simple products, 16 configurables, 100 images, 30 categories, + 200 customers and 80 orders. Those profiles exist to benchmark a store under + catalog weight, not to seed a functional test, and core ships no profile for + the latter. This is that profile: the least data a storefront check needs to + reach a product page and place a guest order. + + Measured on Mage-OS 4.0.0 under Warden: 12s wall clock, including the reindex + the command runs itself. Re-running it does not duplicate anything. + + Deliberately absent: images (the slow part), customers and orders (guest + checkout needs neither), price rules, coupons, extra attribute sets and tax + rates. Nothing asserts on them. + + Also deliberately absent: small.xml sets admin/security/use_form_key to 0 and + admin_account_sharing to 1. That is reasonable for load testing and wrong + here. A gate that runs against a store with admin CSRF protection disabled is + not testing the store we ship. +--> +<config xmlns:xi="http://www.w3.org/2001/XInclude"> + <profile> + <websites>1</websites> + <store_groups>1</store_groups> + <store_views>1</store_views> + <sources>1</sources> + <stocks>1</stocks> + <assign_entities_to_all_websites>0</assign_entities_to_all_websites> + + <!-- product_dynamic_1 .. product_dynamic_20, and + "Configurable Product 1" with three variations. The SKUs are + deterministic, which is the thing sample data cannot offer: no + assertion breaks because a product was renamed upstream. --> + <simple_products>20</simple_products> + <configurable_products> + <config> + <attributes> + <attribute> + <options>3</options> + </attribute> + </attributes> + <sku>Configurable Product %s</sku> + <products>1</products> + </config> + </configurable_products> + + <categories>2</categories> + <categories_nesting_level>1</categories_nesting_level> + + <customers>0</customers> + <orders>0</orders> + <catalog_price_rules>0</catalog_price_rules> + <cart_price_rules>0</cart_price_rules> + <coupon_codes>0</coupon_codes> + <product_attribute_sets>0</product_attribute_sets> + + <configs> + <!-- No SMTP on a CI runner. A failed order confirmation email + must not obscure a real checkout failure. --> + <config> + <path>system/smtp/disable</path> + <scope>default</scope> + <scopeId>0</scopeId> + <value>1</value> + </config> + <!-- Already the stock default; stated so this profile carries + what guest checkout needs rather than relying on it. + + It is also a workaround. ConfigsApplyFixture iterates + $configs['config'] as a list, but a single <config> element + collapses to a flat map, so the fixture iterates that + element's own values and fatals with "Cannot access offset of + type string on string". small.xml carries four entries, so + upstream never sees it. Keep at least two here. --> + <config> + <path>carriers/flatrate/active</path> + <scope>default</scope> + <scopeId>0</scopeId> + <value>1</value> + </config> + </configs> + + <!-- Realtime indexing: the check must not wait on cron. --> + <indexers> + <indexer><id>catalog_category_product</id><set_scheduled>false</set_scheduled></indexer> + <indexer><id>catalog_product_category</id><set_scheduled>false</set_scheduled></indexer> + <indexer><id>catalog_product_price</id><set_scheduled>false</set_scheduled></indexer> + <indexer><id>catalog_product_attribute</id><set_scheduled>false</set_scheduled></indexer> + <indexer><id>cataloginventory_stock</id><set_scheduled>false</set_scheduled></indexer> + <indexer><id>catalogsearch_fulltext</id><set_scheduled>false</set_scheduled></indexer> + </indexers> + </profile> +</config> diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/guest-checkout.spec.ts new file mode 100644 index 00000000..122f2c07 --- /dev/null +++ b/_test/demo-package/Test/e2e/guest-checkout.spec.ts @@ -0,0 +1,158 @@ +import { test, expect, type Page } from '@playwright/test'; + +// The deepest path a storefront check can walk: catalog -> product -> cart -> +// shipping -> payment -> order. It touches the layered navigation, the price +// index, the quote, the shipping and payment method pools, the order +// placement and the private-content sections that Varnish punches holes for. +// If a release breaks any of those, this fails and the homepage check does not. +// +// It needs a salable product, which a bare setup:install does not have. See +// fixtures/mageos-e2e.xml. + +const shopper = { + email: `mageos-e2e-${Date.now()}@example.com`, + firstname: 'Mage', + lastname: 'Tester', + street: '1 Open Source Way', + city: 'Austin', + regionId: process.env.E2E_REGION_ID ?? '57', // Texas + postcode: '78701', + telephone: '5125550123', + countryId: process.env.E2E_COUNTRY_ID ?? 'US', +}; + +// Every selector below is Luma's. Keeping them in one place is what makes the +// Hyva variant of this suite a copy of this file with a different map, rather +// than a rewrite. +const luma = { + navCategory: '.navigation li.level0 > a', + productItem: '.product-item-info', + productItemLink: 'a.product-item-link', + addToCart: '#product-addtocart-button', + cartSuccess: '.message-success', + minicartCounter: '.minicart-wrapper .counter-number', + cartItemName: '.cart.item .product-item-name', + proceedToCheckout: 'button[data-role="proceed-to-checkout"]', + checkoutEmail: '#customer-email', + shippingForm: '#co-shipping-form', + shippingMethod: 'input[value="flatrate_flatrate"]', + nextButton: 'button[data-role="opc-continue"]', + paymentSection: '#checkout-step-payment', + placeOrder: '#checkout-payment-method-load button.action.checkout.primary', + successPageTitle: '.page-title', + successBlock: '.checkout-success', +}; + +async function fillShippingAddress(page: Page) { + const form = page.locator(luma.shippingForm); + + // The country select repopulates the region field, so it goes first. + await form.locator('select[name="country_id"]').selectOption(shopper.countryId); + await form.locator('input[name="firstname"]').fill(shopper.firstname); + await form.locator('input[name="lastname"]').fill(shopper.lastname); + await form.locator('input[name="street[0]"]').fill(shopper.street); + await form.locator('input[name="city"]').fill(shopper.city); + + // Magento renders either a region select or a free-text input depending on + // the country. Handle whichever is actually on the page. + const regionSelect = form.locator('select[name="region_id"]'); + if (await regionSelect.isVisible()) { + await regionSelect.selectOption(shopper.regionId); + } else { + await form.locator('input[name="region"]').fill('Texas'); + } + + await form.locator('input[name="postcode"]').fill(shopper.postcode); + await form.locator('input[name="telephone"]').fill(shopper.telephone); +} + +test.describe('Guest checkout', () => { + test('places an order as a guest', { tag: ['@checkout', '@guest'] }, async ({ page }) => { + await test.step('a category in the main navigation lists products', async () => { + await page.goto('/'); + + const category = page.locator(luma.navCategory).first(); + await expect(category, 'the fixture categories should appear in the main navigation').toBeVisible(); + await category.click(); + + await expect(page.locator('body')).toHaveClass(/catalog-category-view/); + // Not toBeVisible on .first(): an empty category still renders the + // listing wrapper, and a priced, indexed, in-stock product is the + // thing being asserted. + await expect(page.locator(luma.productItem).first()).toBeVisible(); + }); + + await test.step('the product page offers the product for sale', async () => { + await page.locator(luma.productItemLink).first().click(); + + await expect(page.locator('body')).toHaveClass(/catalog-product-view/); + await expect(page.locator('.page-title')).toBeVisible(); + // A price proves the price index ran. Out-of-stock or unindexed + // products render a page but no add-to-cart button. + await expect(page.locator('.product-info-main .price').first()).toBeVisible(); + await expect(page.locator(luma.addToCart)).toBeEnabled(); + }); + + await test.step('adding to the cart updates the minicart', async () => { + await page.locator(luma.addToCart).click(); + + // customer-data arrives over a separate /customer/section/load + // request that Varnish must not have cached. A stale minicart here + // is a real bug, so assert the counter, not just the message. + await expect(page.locator(luma.cartSuccess)).toContainText('to your shopping cart'); + await expect(page.locator(luma.minicartCounter)).toHaveText('1'); + }); + + await test.step('the cart holds the line item', async () => { + await page.goto('/checkout/cart/'); + + await expect(page.locator('body')).toHaveClass(/checkout-cart-index/); + await expect(page.locator(luma.cartItemName)).toHaveCount(1); + await expect(page.locator(luma.proceedToCheckout)).toBeEnabled(); + }); + + await test.step('the shipping step accepts a guest address and a rate', async () => { + await page.locator(luma.proceedToCheckout).click(); + + await expect(page.locator(luma.checkoutEmail)).toBeVisible(); + await page.locator(luma.checkoutEmail).fill(shopper.email); + await fillShippingAddress(page); + + // The rate pool is requested from the server once the address is + // complete. No rate means no checkout, which is a release blocker. + const flatRate = page.locator(luma.shippingMethod); + await expect(flatRate, 'Flat Rate should be offered for the shipping address').toBeVisible(); + await flatRate.check(); + + await page.locator(luma.nextButton).click(); + }); + + await test.step('the payment step places the order', async () => { + await expect(page.locator(luma.paymentSection)).toBeVisible(); + + // Check / Money order is active by default and is the only method + // on a store with no gateway credentials, so it is already + // selected. Assert rather than click, so a store that offers + // nothing fails here instead of timing out on Place Order. + const checkmo = page.locator('input[value="checkmo"]'); + await expect(checkmo, 'Check / Money order should be available').toBeChecked(); + + await page.locator(luma.placeOrder).click(); + }); + + await test.step('the order is confirmed with an increment id', async () => { + await expect(page).toHaveURL(/checkout\/onepage\/success/); + // The confirmation copy is in the page heading; the increment id is + // in the block below it. + await expect(page.locator(luma.successPageTitle)).toContainText('Thank you for your purchase'); + await expect(page.locator(luma.successBlock)).toBeVisible(); + + // An increment id proves the order was persisted, not just that a + // success page rendered. Matched as a pattern rather than through + // a selector: success.phtml wraps the id in a.order-number only + // when the viewer can open the order, so a guest gets a bare + // <span>. Digits also keep this assertion locale-independent. + await expect(page.locator(luma.successBlock)).toContainText(/\d{9}/); + }); + }); +}); From 04e710ef9df8b6d02e2c32880bd8d1e355f073b0 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 21:45:56 -0600 Subject: [PATCH 07/42] ci(e2e): seed a catalog before the storefront tests The checkout spec needs something to buy, and the install the workflow stands up has nothing. The profile is copied into the project directory because the command runs inside the container, which sees only that. It reindexes itself, so no indexer:reindex follows it. --- .github/workflows/_internal-e2e.yaml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 3dea4c20..ec783444 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -29,7 +29,7 @@ concurrency: jobs: storefront-smoke-test: - name: "storefront smoke test" + name: "storefront tests" if: "!startsWith(github.head_ref, 'release-please')" runs-on: ubuntu-latest timeout-minutes: 60 @@ -96,6 +96,20 @@ jobs: - name: Confirm the store answers on the resolved hostname run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 + # A bare setup:install has no salable product, so the checkout spec has + # nothing to buy. The profile is copied into the project because the + # command runs inside the container, which only sees that directory. + # It reindexes itself, so no indexer:reindex follows. + - name: Seed the catalog + working-directory: ./_ghamagento + shell: bash + env: + PROFILE: ${{ github.workspace }}/${{ env.E2E_DIRECTORY }}/fixtures/mageos-e2e.xml + run: | + cp "${PROFILE}" var/mageos-e2e.xml + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + ${WARDEN} env exec -T php-fpm bin/magento setup:performance:generate-fixtures var/mageos-e2e.xml + - uses: actions/setup-node@v4 with: node-version: 22 @@ -108,7 +122,7 @@ jobs: npm ci npx playwright install --with-deps chromium - - name: Run the storefront smoke test + - name: Run the storefront tests working-directory: ${{ env.E2E_DIRECTORY }} env: PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} From a53d46b5f185161b8b2f5a3a2a88768b4f053719 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 21:50:39 -0600 Subject: [PATCH 08/42] ci(e2e): stream the fixture profile into the container The runner cannot write into the project directories the container has written to, because those are owned by the container's user: cp: cannot create regular file 'var/mageos-e2e.xml': Permission denied Piping the profile through exec avoids host permissions entirely and leaves nothing behind in the project. Keeping the profile outside setup/performance-toolkit means its di.xml is not loaded, which only mocks the mail transport -- noted in the profile, and nothing here generates customers or orders. --- .github/workflows/_internal-e2e.yaml | 13 ++++++++----- _test/demo-package/Test/e2e/fixtures/mageos-e2e.xml | 6 ++++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index ec783444..d195dca7 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -97,18 +97,21 @@ jobs: run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 # A bare setup:install has no salable product, so the checkout spec has - # nothing to buy. The profile is copied into the project because the - # command runs inside the container, which only sees that directory. - # It reindexes itself, so no indexer:reindex follows. + # nothing to buy. It reindexes itself, so no indexer:reindex follows. + # + # The profile is streamed into the container rather than copied into the + # project: the command runs inside the container, which sees only that + # directory, and the directories the container has written to are owned by + # its own user, so the runner cannot write there. - name: Seed the catalog working-directory: ./_ghamagento shell: bash env: PROFILE: ${{ github.workspace }}/${{ env.E2E_DIRECTORY }}/fixtures/mageos-e2e.xml run: | - cp "${PROFILE}" var/mageos-e2e.xml export WARDEN="$(dirname $(pwd))/warden/bin/warden" - ${WARDEN} env exec -T php-fpm bin/magento setup:performance:generate-fixtures var/mageos-e2e.xml + ${WARDEN} env exec -T php-fpm bash -c 'cat > /tmp/mageos-e2e.xml' < "${PROFILE}" + ${WARDEN} env exec -T php-fpm bin/magento setup:performance:generate-fixtures /tmp/mageos-e2e.xml - uses: actions/setup-node@v4 with: diff --git a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml index 1fce5599..b5965c09 100644 --- a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml +++ b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml @@ -16,6 +16,12 @@ checkout needs neither), price rules, coupons, extra attribute sets and tax rates. Nothing asserts on them. + One consequence of keeping this file outside setup/performance-toolkit: + FixtureConfig derives the profile's di.xml from dirname() of this file, so + the toolkit's own di.xml is not loaded. All it does is mock the mail + transport, and nothing here generates customers or orders, so nothing tries + to send mail. The smtp/disable config below covers the rest. + Also deliberately absent: small.xml sets admin/security/use_form_key to 0 and admin_account_sharing to 1. That is reasonable for load testing and wrong here. A gate that runs against a store with admin CSRF protection disabled is From f69b5e6098e9582eb75f1fbdc774d923efbc3531 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 22:01:12 -0600 Subject: [PATCH 09/42] test(e2e): add to the cart whatever the catalog lists first Which product a category lists first is not ours to decide, and on a clean install it is the configurable. That will not go into the cart until every attribute has a value, so the first CI run failed waiting for a success message that was never coming -- it had a validation error instead. It passed locally only because a leftover simple product happened to sort ahead of it. Selecting the first available value for whatever the page asks for makes the step indifferent to catalog order, and lets the spec run against a simple product, a configurable, or a merchant's own catalog. Verified against a configurable locally: one dropdown, three values, first selection adds to the cart. --- .github/workflows/_internal-e2e.yaml | 10 ++---- .../Test/e2e/guest-checkout.spec.ts | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index d195dca7..346e2d5d 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -96,13 +96,9 @@ jobs: - name: Confirm the store answers on the resolved hostname run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 - # A bare setup:install has no salable product, so the checkout spec has - # nothing to buy. It reindexes itself, so no indexer:reindex follows. - # - # The profile is streamed into the container rather than copied into the - # project: the command runs inside the container, which sees only that - # directory, and the directories the container has written to are owned by - # its own user, so the runner cannot write there. + # A bare setup:install has nothing to buy. The command reindexes itself. + # Streamed in rather than copied: the project directories are owned by the + # container's user. - name: Seed the catalog working-directory: ./_ghamagento shell: bash diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/guest-checkout.spec.ts index 122f2c07..1e16c6a5 100644 --- a/_test/demo-package/Test/e2e/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/guest-checkout.spec.ts @@ -29,6 +29,9 @@ const luma = { productItem: '.product-item-info', productItemLink: 'a.product-item-link', addToCart: '#product-addtocart-button', + swatchGroup: '.swatch-attribute', + swatchOption: '.swatch-option:not(.disabled)', + optionSelect: 'select.super-attribute-select', cartSuccess: '.message-success', minicartCounter: '.minicart-wrapper .counter-number', cartItemName: '.cart.item .product-item-name', @@ -43,6 +46,35 @@ const luma = { successBlock: '.checkout-success', }; +// A configurable product will not go into the cart until every attribute has a +// value, and which product the catalog lists first is not ours to decide. So +// pick the first available value for whatever the page asks for, and let the +// spec work on a simple product, a configurable, or a merchant's own catalog. +async function selectRequiredOptions(page: Page) { + const swatchGroups = page.locator(luma.swatchGroup); + for (let i = 0; i < (await swatchGroups.count()); i++) { + const option = swatchGroups.nth(i).locator(luma.swatchOption).first(); + if (await option.count()) { + await option.click(); + } + } + + // Configurables render dropdowns instead of swatches when the attribute + // has no swatch values, which is what the fixture profile produces. + const selects = page.locator(luma.optionSelect); + for (let i = 0; i < (await selects.count()); i++) { + const select = selects.nth(i); + const values = await select + .locator('option') + .evaluateAll((options) => + options.map((option) => (option as HTMLOptionElement).value).filter(Boolean), + ); + if (values.length) { + await select.selectOption(values[0]); + } + } +} + async function fillShippingAddress(page: Page) { const form = page.locator(luma.shippingForm); @@ -94,6 +126,7 @@ test.describe('Guest checkout', () => { }); await test.step('adding to the cart updates the minicart', async () => { + await selectRequiredOptions(page); await page.locator(luma.addToCart).click(); // customer-data arrives over a separate /customer/section/load From 53fa1d001a968991f3c634291ecf900979986871 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 22:34:20 -0600 Subject: [PATCH 10/42] feat(e2e): add a reusable workflow for browser-based tests _internal-e2e.yaml proves the actions work, but it cannot be reused: it references them through "./", and a relative path in a reusable workflow resolves against the caller's checkout, which is not this repository when the caller is the release pipeline. So own-repo actions are referenced by full ref here, as integration.yaml and full-integration-tests.yaml already do. test_command is an input rather than a hardcoded "npx playwright test". The workflow's job is to stand a store up and hand over a URL; it should not know what runner points at it, and a caller wanting a grep filter, a shard or a different reporter should not need a new input for each. It arrives through the environment rather than interpolated into the script, so quoting is bash's problem and not the expression engine's. Evidence policy stays in the suite's config, so the default command carries no flags: a CLI flag overrides the config, and --trace on records a trace for every passing test. fixture_profile seeds a catalog before the run, because a bare setup:install has nothing to buy. Empty skips it, which is right for a suite that asserts only on what a bare install provides. Verified green end to end on a throwaway branch, with the Warden action pointed at the stacked serving branch: store served, catalog seeded in 9s, 2 specs passed. At @main it needs the serving inputs, so this cannot go green until #395 is on main. --- .github/workflows/e2e-README.md | 156 +++++++++++++++++++++ .github/workflows/e2e.yaml | 241 ++++++++++++++++++++++++++++++++ 2 files changed, 397 insertions(+) create mode 100644 .github/workflows/e2e-README.md create mode 100644 .github/workflows/e2e.yaml diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md new file mode 100644 index 00000000..e8b1c098 --- /dev/null +++ b/.github/workflows/e2e-README.md @@ -0,0 +1,156 @@ +# Browser-based E2E Tests for Mage-OS + +A Github Workflow that stands a Mage-OS store up, **serves it**, and points a +browser-based test runner at it. + +This is not the PHPUnit-based suite that upstream calls "functional tests". It +installs a store, serves it through Traefik and Varnish on a resolvable +hostname, optionally seeds a catalog, and runs a browser against the result. + +## Inputs + +See the [e2e.yaml](./e2e.yaml) + +### What to install + +| Input | Description | Required | Default | +| -------------------- | --------------------------------------------------------------------------- | -------- | ----------------------------- | +| magento_version | The package to install, e.g. `mage-os/project-community-edition:4.0.0` | true | NULL | +| magento_repository | The composer repository to install it from | false | https://repo.mage-os.org/ | +| php_version | The PHP version that installs and serves the store | false | 8.4 | +| composer_version | The Composer version used inside the container | false | 2.10.2 | + +A release gate points `magento_repository` at the preview repository and +`magento_version` at the release being built, which is how it tests the +artifact about to be tagged rather than whatever is already published. + +### What to serve it with + +| Input | Description | Required | Default | +| ---------------------- | ------------------------------------------------------------------------- | -------- | --------------- | +| database | Database service and version | false | mariadb:11.8 | +| search | Search service and version | false | opensearch:3.4 | +| rabbitmq | Message queue service and version | false | rabbitmq:4.2 | +| redis | Cache service and version | false | redis:7.4 | +| varnish | HTTP cache service and version | false | varnish:8.0 | +| static_content_themes | Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. | false | Magento/luma | + +### Where the suite comes from + +| Input | Description | Required | Default | +| ----------------- | ---------------------------------------------------------------- | -------- | --------------------------------- | +| suite_repository | The repository holding the test suite | false | mage-os/github-actions | +| suite_ref | The ref to check it out at | false | main | +| test_directory | The suite's directory, relative to the root of `suite_repository` | false | _test/demo-package/Test/e2e | + +The defaults point at the suite this repository carries for its own canary. A +caller with a suite of its own overrides all three. + +### How to run it + +| Input | Description | Required | Default | +| ------------------------ | ------------------------------------------------------------------ | -------- | -------------------- | +| test_command | The command to run, from `test_directory` | false | `npx playwright test` | +| node_version | Node version for the runner | false | 22 | +| fixture_profile | A performance-toolkit profile to seed, relative to the suite root. Empty skips seeding. | false | _test/demo-package/Test/e2e/fixtures/mageos-e2e.xml | +| timeout_minutes | Job timeout | false | 60 | +| artifact_name | Name of the uploaded report artifact | false | playwright-report | +| artifact_retention_days | How long the report is kept | false | 30 | + +## Secrets + +| Input | Description | Required | Default | +| ------------- | --------------------------------------------------------------------------- | -------- | ------- | +| composer_auth | JSON string of composer credentials | false | NULL | + +## Outputs + +| Output | Description | +| -------- | ------------------------------------- | +| base_url | The URL the store was served on | + +## `test_command` + +The workflow does not know what test runner you use. `test_command` is run from +`test_directory` with `PLAYWRIGHT_BASE_URL` already set to the served store, so +a caller can pass grep filters, shards, a different reporter, or something that +is not Playwright at all, without this workflow growing an input per flag. + +The command arrives through the environment rather than interpolated into the +script, so its quoting is bash's problem and not the expression engine's. + +**Keep evidence policy out of it.** `trace`, `video` and `screenshot` belong in +the suite's own config, where they are reviewable. A CLI flag overrides the +config, and `--trace on` records a trace for every passing test, which uploads +a large artifact for no benefit. The default command carries no flags for that +reason. + +### A setup phase + +Playwright's project `dependencies` are the mechanism for shared state that is +expensive to build -- an authenticated admin or customer session saved as +`storageState` and reused by every spec that needs it. Express that in the +suite's config rather than as two `--grep` / `--grep-invert` invocations in +`test_command`: two invocations write to the same report directory, so the +second overwrites the first and a failing setup phase loses its own evidence. +One command, one report, one exit code. + +Data is a different matter. Catalog and configuration are seeded through +`fixture_profile` by the CLI in seconds; doing the same work through a browser +would be slower and flakier for no gain. + +## Fixtures + +`fixture_profile` is a [performance +toolkit](https://developer.adobe.com/commerce/php/development/tools/performance-toolkit/) +profile, applied with `setup:performance:generate-fixtures`. The command +reindexes as part of its own run, so no `indexer:reindex` follows it. + +A bare `setup:install` has no salable product, so any suite that reaches a +product page or a checkout needs this. Leave it empty for a suite that asserts +only on what a bare install provides. + +## Usage + +```yaml +jobs: + e2e: + uses: mage-os/github-actions/.github/workflows/e2e.yaml@main + with: + magento_version: "mage-os/project-community-edition:4.0.0" +``` + +Gating a release on the artifact that is about to be tagged: + +```yaml +jobs: + storefront-check: + needs: [ deploy ] + uses: mage-os/github-actions/.github/workflows/e2e.yaml@main + with: + magento_repository: ${{ inputs.repo }} + magento_version: "mage-os/project-community-edition:${{ inputs.mageos_release }}" + artifact_name: "storefront-check-${{ inputs.mageos_release }}" +``` + +Running a suite of your own: + +```yaml +jobs: + e2e: + uses: mage-os/github-actions/.github/workflows/e2e.yaml@main + with: + magento_version: "mage-os/project-community-edition:4.0.0" + suite_repository: my-org/my-e2e-tests + suite_ref: v1.2.0 + test_directory: "." + test_command: "npx playwright test --grep @smoke" + fixture_profile: "fixtures/minimal.xml" +``` + +## Where things end up on the runner + +`warden/setup-environment` checks the Warden CLI out into `warden/` at the +workspace root, and `base_directory` has to sit exactly one level below it. +That is why the suite is checked out into `suite/` and the store into +`_ghamagento/`, and why neither is at the workspace root. diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml new file mode 100644 index 00000000..cd1d8563 --- /dev/null +++ b/.github/workflows/e2e.yaml @@ -0,0 +1,241 @@ +name: E2E Tests + +# A reusable workflow that stands a Mage-OS store up, serves it, and points a +# browser-based test runner at it. +# +# It does not know what runner that is: test_command is an input, so a caller +# can pass grep filters, shards, a different reporter, or something that is not +# Playwright at all, without this workflow growing an input per flag. +# +# Own-repo actions are referenced by full ref rather than by "./", as +# integration.yaml and full-integration-tests.yaml do. A relative path in a +# reusable workflow resolves against the caller's checkout, which is not this +# repository when the caller is the release pipeline. + +on: + workflow_call: + inputs: + # What to install. + magento_version: + required: true + type: string + description: "The package to install, e.g. mage-os/project-community-edition:4.0.0." + magento_repository: + required: false + type: string + default: "https://repo.mage-os.org/" + description: "The composer repository to install it from. A release gate points this at the preview repository." + php_version: + required: false + type: string + default: "8.4" + composer_version: + required: false + type: string + default: "2.10.2" + + # What to serve it with. + database: + required: false + type: string + default: "mariadb:11.8" + search: + required: false + type: string + default: "opensearch:3.4" + rabbitmq: + required: false + type: string + default: "rabbitmq:4.2" + redis: + required: false + type: string + default: "redis:7.4" + varnish: + required: false + type: string + default: "varnish:8.0" + static_content_themes: + required: false + type: string + default: "Magento/luma" + description: "Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower." + + # Where the suite comes from. The default is the suite this repository + # carries for its own canary; a caller with a suite of its own overrides + # both of these. + suite_repository: + required: false + type: string + default: "mage-os/github-actions" + suite_ref: + required: false + type: string + default: "main" + test_directory: + required: false + type: string + default: "_test/demo-package/Test/e2e" + description: "The suite's directory, relative to the root of suite_repository." + + # How to run it. + test_command: + required: false + type: string + default: "npx playwright test" + description: > + Run from test_directory with PLAYWRIGHT_BASE_URL set. Keep evidence + policy (trace, video, screenshot) in the suite's own config rather + than in flags here: a CLI flag overrides the config, and a gate that + records a trace for every passing test uploads a large artifact for + no benefit. + node_version: + required: false + type: string + default: "22" + fixture_profile: + required: false + type: string + default: "_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml" + description: > + A performance-toolkit profile, relative to the root of + suite_repository, seeded before the tests run. Empty skips seeding, + which is right for a suite that asserts only on what a bare + setup:install provides. + + # Housekeeping. + timeout_minutes: + required: false + type: number + default: 60 + artifact_name: + required: false + type: string + default: "playwright-report" + description: "Give this a release-specific name when several gates upload to the same run." + artifact_retention_days: + required: false + type: number + default: 30 + + secrets: + composer_auth: + required: false + + outputs: + base_url: + description: "The URL the store was served on." + value: ${{ jobs.e2e.outputs.base_url }} + +jobs: + e2e: + name: "e2e tests" + runs-on: ubuntu-latest + timeout-minutes: ${{ inputs.timeout_minutes }} + outputs: + base_url: ${{ steps.warden.outputs.base_url }} + + env: + TRAEFIK_DOMAIN: mageos.test + TRAEFIK_SUBDOMAIN: app + # The suite is checked out here, and the tests run in SUITE/<dir>. + SUITE: suite + + steps: + # Not at the workspace root: warden/setup-environment checks the Warden CLI + # out into warden/ there, and base_directory has to sit exactly one level + # below it. + - name: Check out the test suite + uses: actions/checkout@v6 + with: + repository: ${{ inputs.suite_repository }} + ref: ${{ inputs.suite_ref }} + path: suite + + - name: Create the Mage-OS project + uses: mage-os/github-actions/setup-magento@main + with: + php-version: ${{ inputs.php_version }} + tools: "composer:v2" + mode: extension + magento_repository: ${{ inputs.magento_repository }} + magento_version: ${{ inputs.magento_version }} + composer_auth: ${{ secrets.composer_auth }} + + - name: Serve the store in Warden + id: warden + uses: mage-os/github-actions/warden/setup-environment@main + with: + base_directory: "./_ghamagento" + php_version: ${{ inputs.php_version }} + composer_version: ${{ inputs.composer_version }} + database: ${{ inputs.database }} + search: ${{ inputs.search }} + rabbitmq: ${{ inputs.rabbitmq }} + redis: ${{ inputs.redis }} + varnish: ${{ inputs.varnish }} + run_composer_install: 1 + run_setup_install: 1 + run_admin_user_creation: 1 + run_magento_config_preset: 1 + run_reindex: 1 + traefik_domain: ${{ env.TRAEFIK_DOMAIN }} + traefik_subdomain: ${{ env.TRAEFIK_SUBDOMAIN }} + base_url: "https://${{ env.TRAEFIK_SUBDOMAIN }}.${{ env.TRAEFIK_DOMAIN }}/" + configure_host_resolution: 1 + run_static_content_deploy: 1 + static_content_themes: ${{ inputs.static_content_themes }} + + # Separate from the test run so that "the store was never reachable" and + # "the store rendered the wrong thing" are different red steps. + - name: Confirm the store answers on the resolved hostname + run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 + + # A bare setup:install has nothing to buy. The command reindexes itself. + # Streamed in rather than copied: the project directories are owned by the + # container's user. + - name: Seed the catalog + if: inputs.fixture_profile != '' + working-directory: ./_ghamagento + shell: bash + env: + PROFILE: ${{ github.workspace }}/${{ env.SUITE }}/${{ inputs.fixture_profile }} + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + ${WARDEN} env exec -T php-fpm bash -c 'cat > /tmp/fixture-profile.xml' < "${PROFILE}" + ${WARDEN} env exec -T php-fpm bin/magento setup:performance:generate-fixtures /tmp/fixture-profile.xml + + - uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node_version }} + cache: npm + cache-dependency-path: ${{ env.SUITE }}/${{ inputs.test_directory }}/package-lock.json + + - name: Install the test runner + working-directory: ${{ env.SUITE }}/${{ inputs.test_directory }} + run: | + npm ci + npx playwright install --with-deps chromium + + # The command arrives through the environment rather than interpolated into + # the script, so its quoting is bash's problem and not the expression + # engine's. + - name: Run the tests + working-directory: ${{ env.SUITE }}/${{ inputs.test_directory }} + env: + TEST_COMMAND: ${{ inputs.test_command }} + PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} + run: bash -c "$TEST_COMMAND" + + # A failing gate is read by someone deciding whether to ship, so the + # evidence has to outlive the run. + - name: Upload the test report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.artifact_name }} + path: | + ${{ env.SUITE }}/${{ inputs.test_directory }}/playwright-report + ${{ env.SUITE }}/${{ inputs.test_directory }}/test-results + retention-days: ${{ inputs.artifact_retention_days }} + if-no-files-found: ignore From 9fe237d0ea73c59a161861695b99c7371cbee2ef Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 22:48:43 -0600 Subject: [PATCH 11/42] ci(e2e): pass the base URL through the environment An expression interpolated into run: is substituted before bash sees the script, so its content has to be trusted as shell. This one is our own action's output rather than anything a caller supplies, so nothing was exploitable, but it is the pattern issue #314 asks this repository to stop using, and there is no reason for the gate to be the exception. No expression is interpolated into a run: block in either workflow now. --- .github/workflows/_internal-e2e.yaml | 4 +++- .github/workflows/e2e.yaml | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 346e2d5d..72961194 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -94,7 +94,9 @@ jobs: # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. - name: Confirm the store answers on the resolved hostname - run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 + env: + BASE_URL: ${{ steps.warden.outputs.base_url }} + run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index cd1d8563..31c60d90 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -189,7 +189,9 @@ jobs: # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. - name: Confirm the store answers on the resolved hostname - run: curl --silent --show-error --fail --insecure --head "${{ steps.warden.outputs.base_url }}" | head -1 + env: + BASE_URL: ${{ steps.warden.outputs.base_url }} + run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the From acca57c77019a2d69d4dfdb4232b9aed9cf05bbd Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 9 Nov 2026 23:04:24 -0600 Subject: [PATCH 12/42] ci(e2e): record the stack the gate ran against Probed from the running store rather than echoed back from the inputs. A version input can be a constraint, the repository can resolve it differently than expected, and a service tag does not carry its patch level: the local store asked for opensearch 3.3 and runs 3.3.2. A failing release gate has to be able to say which. MAGEOS_VERSION and MAGENTO_VERSION reach the suite, because a spec may reasonably branch on either -- Luma markup tracks upstream Magento while feature availability tracks Mage-OS. The rest goes to the job summary; no spec should branch on a Redis patch level. Nothing here can fail the job. A probe that comes back empty reports unknown, because a disabled service is not a broken store. Two probes needed care: varnishd -V writes its version to stderr, and OpenSearch reports its own several lines into a JSON body. The READMEs state the preference for test.skip with a reason over a --grep exclusion, so that a version condition which stops applying is visible in the report instead of silently selecting nothing. --- .github/workflows/_internal-e2e.yaml | 49 +++++++++++++++++++++++++++ .github/workflows/e2e-README.md | 32 +++++++++++++++++ .github/workflows/e2e.yaml | 49 +++++++++++++++++++++++++++ _test/demo-package/Test/e2e/README.md | 12 +++++++ 4 files changed, 142 insertions(+) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 72961194..095dd33d 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -98,6 +98,53 @@ jobs: BASE_URL: ${{ steps.warden.outputs.base_url }} run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 + # What the gate ran against, probed from the running stack rather than + # echoed back from the inputs: a version input can be a constraint, the + # repository can resolve it differently than expected, and a service tag + # does not carry its patch level. A failing release gate has to be able to + # say "it broke on OpenSearch 3.3.2", not "we asked for 3.3". + # + # Nothing here can fail the job. A probe that comes back empty reports + # "unknown" -- a disabled service is not a broken store. + - name: Record the stack under test + id: stack + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + # Stderr is captured too: varnishd -V writes its version there. + probe() { ${WARDEN} env exec -T "$1" "${@:2}" 2>&1 | tr -d '\r' || true; } + + RAW="$(probe php-fpm bin/magento --version | head -1)" + echo "${RAW}" + MAGEOS="$(printf '%s' "${RAW}" | sed -n 's/.*CLI \([0-9][^ ]*\).*/\1/p')" + MAGENTO="$(printf '%s' "${RAW}" | sed -n 's/.*based on Magento \([0-9][^)]*\).*/\1/p')" + + PHP="$(probe php-fpm php -r 'echo PHP_VERSION;' | head -1)" + DB="$(probe db mariadb --version | sed -n 's/.*from \([0-9][0-9.]*\).*/\1/p' | head -1)" + SEARCH="$(probe php-fpm curl -s http://opensearch:9200 | tr -d '\n' | sed -n 's/.*"number"[^"]*"\([^"]*\)".*/\1/p')" + REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" + VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" + + # Only the application versions reach the tests. A spec may reasonably + # branch on those; none should branch on a Redis patch level. + echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT + echo "magento=${MAGENTO:-unknown}" >> $GITHUB_OUTPUT + + { + echo "### Stack under test" + echo + echo "| | Version |" + echo "| --- | --- |" + echo "| Mage-OS | ${MAGEOS:-unknown} |" + echo "| Magento | ${MAGENTO:-unknown} |" + echo "| PHP | ${PHP:-unknown} |" + echo "| Database | ${DB:-unknown} |" + echo "| Search | ${SEARCH:-unknown} |" + echo "| Redis | ${REDIS:-unknown} |" + echo "| Varnish | ${VARNISH:-unknown} |" + } >> $GITHUB_STEP_SUMMARY + # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the # container's user. @@ -127,6 +174,8 @@ jobs: working-directory: ${{ env.E2E_DIRECTORY }} env: PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} + MAGEOS_VERSION: ${{ steps.stack.outputs.mageos }} + MAGENTO_VERSION: ${{ steps.stack.outputs.magento }} run: npx playwright test - name: Upload the Playwright report diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index e8b1c098..ec36b9ce 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -99,6 +99,38 @@ Data is a different matter. Catalog and configuration are seeded through `fixture_profile` by the CLI in seconds; doing the same work through a browser would be slower and flakier for no gain. +## What the suite is told about the store + +| Variable | Value | +| --- | --- | +| `PLAYWRIGHT_BASE_URL` | the served store's URL | +| `MAGEOS_VERSION` | e.g. `4.0.0` | +| `MAGENTO_VERSION` | the upstream version it is based on, e.g. `2.4.9` | + +Both versions are **probed from the running store** (`bin/magento --version`), +not echoed back from `magento_version`. A version input can be a constraint, +the repository can resolve it differently than expected, and a gate should +report what installed rather than what was asked for. + +Two versions rather than one because they drift apart for different reasons: +Luma markup tracks upstream Magento, while feature availability tracks Mage-OS. +A spec that has to care about either should say so next to the assertion: + +```ts +test('...', async ({ page }) => { + test.skip(!atLeast(process.env.MAGEOS_VERSION, '5.0.0'), 'introduced in 5.0'); +}); +``` + +Prefer `test.skip` with a reason over excluding the spec with `--grep`. A skip +appears in the report, with its reason, so "why did this not run" is answerable +from the artifact. A grep exclusion is invisible, and nothing fails when a +version condition goes stale. + +The step also writes the full stack -- PHP, database, search, Redis and Varnish +patch levels, probed from the containers -- to the job summary, so a red gate +says what it ran against without anyone reading the log. + ## Fixtures `fixture_profile` is a [performance diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 31c60d90..ceae28bb 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -193,6 +193,53 @@ jobs: BASE_URL: ${{ steps.warden.outputs.base_url }} run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 + # What the gate ran against, probed from the running stack rather than + # echoed back from the inputs: a version input can be a constraint, the + # repository can resolve it differently than expected, and a service tag + # does not carry its patch level. A failing release gate has to be able to + # say "it broke on OpenSearch 3.3.2", not "we asked for 3.3". + # + # Nothing here can fail the job. A probe that comes back empty reports + # "unknown" -- a disabled service is not a broken store. + - name: Record the stack under test + id: stack + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + # Stderr is captured too: varnishd -V writes its version there. + probe() { ${WARDEN} env exec -T "$1" "${@:2}" 2>&1 | tr -d '\r' || true; } + + RAW="$(probe php-fpm bin/magento --version | head -1)" + echo "${RAW}" + MAGEOS="$(printf '%s' "${RAW}" | sed -n 's/.*CLI \([0-9][^ ]*\).*/\1/p')" + MAGENTO="$(printf '%s' "${RAW}" | sed -n 's/.*based on Magento \([0-9][^)]*\).*/\1/p')" + + PHP="$(probe php-fpm php -r 'echo PHP_VERSION;' | head -1)" + DB="$(probe db mariadb --version | sed -n 's/.*from \([0-9][0-9.]*\).*/\1/p' | head -1)" + SEARCH="$(probe php-fpm curl -s http://opensearch:9200 | tr -d '\n' | sed -n 's/.*"number"[^"]*"\([^"]*\)".*/\1/p')" + REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" + VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" + + # Only the application versions reach the tests. A spec may reasonably + # branch on those; none should branch on a Redis patch level. + echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT + echo "magento=${MAGENTO:-unknown}" >> $GITHUB_OUTPUT + + { + echo "### Stack under test" + echo + echo "| | Version |" + echo "| --- | --- |" + echo "| Mage-OS | ${MAGEOS:-unknown} |" + echo "| Magento | ${MAGENTO:-unknown} |" + echo "| PHP | ${PHP:-unknown} |" + echo "| Database | ${DB:-unknown} |" + echo "| Search | ${SEARCH:-unknown} |" + echo "| Redis | ${REDIS:-unknown} |" + echo "| Varnish | ${VARNISH:-unknown} |" + } >> $GITHUB_STEP_SUMMARY + # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the # container's user. @@ -227,6 +274,8 @@ jobs: env: TEST_COMMAND: ${{ inputs.test_command }} PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} + MAGEOS_VERSION: ${{ steps.stack.outputs.mageos }} + MAGENTO_VERSION: ${{ steps.stack.outputs.magento }} run: bash -c "$TEST_COMMAND" # A failing gate is read by someone deciding whether to ship, so the diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index daf1bd8b..25521b2c 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -69,6 +69,18 @@ Received string: "m137-admin-theme adminhtml-auth-login page-layout-admin-login For the static content assertion, clear `pub/static` and reload. +## Version-dependent assertions + +When run from `e2e.yaml`, the suite receives `MAGEOS_VERSION` and +`MAGENTO_VERSION`, probed from the running store rather than taken from the +workflow input. Nothing uses them yet. + +When something does, use `test.skip(condition, reason)` next to the assertion +rather than excluding the spec from the command line: a skip appears in the +report with its reason, while a `--grep` exclusion is invisible and goes stale +silently. For markup that moves between versions, branch the selector map at +the top of the spec rather than the spec itself. + ## Fixtures `fixtures/mageos-e2e.xml` is a performance-toolkit profile, run with the From 0543ee23671506e478bc59c766362a838bf2178b Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Wed, 11 Nov 2026 21:59:33 -0600 Subject: [PATCH 13/42] test(e2e): sign in to the admin The storefront is a thin skin over the catalog; the admin is where the framework lives, and where a release is most likely to break. This adds the enablement the admin needs and one spec that proves it works, so the specs that exercise UI components and the EAV save path have somewhere to start. Nothing in Magento switches two-factor authentication off. There is no enable flag, and leaving twofactorauth/general/force_providers empty does not help: ControllerActionPredispatch still routes a fresh admin user to tfa/tfa/index, which redirects to tfa/tfa/requestconfig. Disabling the module is the only route in, and MageOS_PasskeyAuth requires it and registers an admin 2FA provider, so both go in one command or dependency validation refuses it. The cost is stated in the workflow and the README: this gate does not cover admin 2FA, and doing that properly means driving a TOTP provider. The admin login CAPTCHA is on by default -- admin/captcha/enable 1, after_fail mode, three failed attempts per login name, counted in captcha_log. A suite that asserts a bad credential is refused manufactures exactly those failures, so leaving it on lets the negative control poison the positive one, reported as an "Incorrect CAPTCHA" on a correct password. Disabled, and the specs limit their own exposure: the refusal test uses a name that is not an account, and the three sign-in assertions are separate tests, so each gets its own context. No blanket modal dismissal. Both candidates were checked instead of assumed: Magento_AdminAnalytics' prompt is gated by admin/usage/enabled, which defaults to 0 and is now pinned, and Magento_ReleaseNotification builds its URL from system/release_notification/content_url, which Mage-OS ships empty. Neither renders. A helper that clicked away whatever covered the page would be dead code today and would hide a real blocking dialog later. Assertions are on page identity, not URLs: Magento serves the dashboard at whichever admin path was requested, so a URL assertion passes or fails depending on how the session arrived. #login-form is ambiguous -- the storefront authentication popup uses the same id -- so the body class is asserted first, which a wrong-frontname negative control found. The sign-in is a project dependency rather than a globalSetup hook so it is its own reported result: a broken session fails once and the admin specs report "did not run", instead of a wall of identical reds. Verified against a live store: three sign-in tests and the storefront smoke green in 14s, and both negative controls red -- a wrong password and a wrong frontname each fail the session setup on the assertion that should catch them. --- .github/workflows/_internal-e2e.yaml | 72 +++++++++++- .github/workflows/e2e-README.md | 53 ++++++++- .github/workflows/e2e.yaml | 76 ++++++++++++- _test/demo-package/Test/e2e/.env.example | 7 ++ _test/demo-package/Test/e2e/.gitignore | 1 + _test/demo-package/Test/e2e/README.md | 103 +++++++++++++++++- .../demo-package/Test/e2e/admin/login.spec.ts | 50 +++++++++ .../Test/e2e/admin/session.setup.ts | 26 +++++ _test/demo-package/Test/e2e/admin/support.ts | 84 ++++++++++++++ .../Test/e2e/playwright.config.ts | 24 +++- 10 files changed, 483 insertions(+), 13 deletions(-) create mode 100644 _test/demo-package/Test/e2e/admin/login.spec.ts create mode 100644 _test/demo-package/Test/e2e/admin/session.setup.ts create mode 100644 _test/demo-package/Test/e2e/admin/support.ts diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 095dd33d..085e1648 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -29,7 +29,7 @@ concurrency: jobs: storefront-smoke-test: - name: "storefront tests" + name: "storefront and admin tests" if: "!startsWith(github.head_ref, 'release-please')" runs-on: ubuntu-latest timeout-minutes: 60 @@ -45,6 +45,14 @@ jobs: # its own versions. PHP_VERSION: "8.4" COMPOSER_VERSION: "2.10.2" + # Declared once and handed to both the install and the suite. Two places + # holding separate opinions about the admin URL is a silent 404 that + # looks like a broken admin. + ADMIN_FRONTNAME: "admin" + # What warden/setup-environment's admin:user:create step makes. Not a + # secret: it is a throwaway store that exists for the length of the job. + ADMIN_USER: "admin" + ADMIN_PASSWORD: "abcABC123" steps: # Not at the workspace root: warden/setup-environment checks the Warden # CLI out into warden/ there, which is where this repository keeps that @@ -88,8 +96,12 @@ jobs: # The three inputs a browser needs, and nothing a PHPUnit suite pays for. base_url: "https://${{ env.TRAEFIK_SUBDOMAIN }}.${{ env.TRAEFIK_DOMAIN }}/" configure_host_resolution: 1 + backend_frontname: ${{ env.ADMIN_FRONTNAME }} run_static_content_deploy: 1 - static_content_themes: "Magento/luma" + # Magento/backend as well as the storefront theme: the admin specs + # would otherwise have to wait for every asset to be generated on + # demand, which reads as a timeout rather than as a missing deploy. + static_content_themes: "Magento/luma Magento/backend" # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. @@ -145,6 +157,57 @@ jobs: echo "| Varnish | ${VARNISH:-unknown} |" } >> $GITHUB_STEP_SUMMARY + # Magento has no switch for two-factor authentication. There is no enable + # flag, and leaving twofactorauth/general/force_providers empty does not + # help: ControllerActionPredispatch still routes a fresh admin user to + # tfa/tfa/index, which redirects to tfa/tfa/requestconfig. Disabling the + # module is the only way in. MageOS_PasskeyAuth requires it and registers + # an admin 2FA provider, so both have to go in one command or dependency + # validation refuses it. + # + # The cost is stated rather than hidden: this gate does not cover admin + # 2FA. Covering it means driving a TOTP provider from its shared secret, + # which is worth doing, as its own spec. + - name: Open the admin to the test suite + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + MODULES=() + for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do + # module:status exits 0 even for a module that is not installed, so + # its output is the only signal. MageOS_PasskeyAuth is Mage-OS only, + # and this workflow should still work against a Magento install. + if ${WARDEN} env exec -T php-fpm bin/magento module:status "${MODULE}" 2>&1 | grep -q 'does not exist'; then + echo "${MODULE} is not installed" + else + MODULES+=("${MODULE}") + fi + done + + # An array, not a string: module:disable takes the names as separate + # arguments and reads a single space-joined string as one unknown + # module name. Re-running it changes nothing and still exits 0. + if [ ${#MODULES[@]} -gt 0 ]; then + ${WARDEN} env exec -T php-fpm bin/magento module:disable "${MODULES[@]}" + fi + + # Already the default. Pinned so the suite does not rely on one: + # it gates Magento_AdminAnalytics' usage-data modal, which would + # otherwise cover the dashboard on first sign-in. + ${WARDEN} env exec -T php-fpm bin/magento config:set admin/usage/enabled 0 + + # The admin login CAPTCHA is on by default (admin/captcha/enable 1) in + # after_fail mode, and asks for one after three failed attempts per + # login name -- counted in the captcha_log table, which survives + # across runs against a long-lived store. A suite that asserts a bad + # credential is refused produces exactly those failures, so leaving + # this on lets the negative control poison the positive one, and the + # symptom is an "Incorrect CAPTCHA" that looks nothing like the cause. + ${WARDEN} env exec -T php-fpm bin/magento config:set admin/captcha/enable 0 + ${WARDEN} env exec -T php-fpm bin/magento cache:flush + # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the # container's user. @@ -170,12 +233,15 @@ jobs: npm ci npx playwright install --with-deps chromium - - name: Run the storefront tests + - name: Run the tests working-directory: ${{ env.E2E_DIRECTORY }} env: PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} MAGEOS_VERSION: ${{ steps.stack.outputs.mageos }} MAGENTO_VERSION: ${{ steps.stack.outputs.magento }} + MAGENTO_ADMIN_USER: ${{ env.ADMIN_USER }} + MAGENTO_ADMIN_PASSWORD: ${{ env.ADMIN_PASSWORD }} + MAGENTO_ADMIN_FRONTNAME: ${{ env.ADMIN_FRONTNAME }} run: npx playwright test - name: Upload the Playwright report diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index ec36b9ce..e2852f94 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -33,7 +33,9 @@ artifact about to be tagged rather than whatever is already published. | rabbitmq | Message queue service and version | false | rabbitmq:4.2 | | redis | Cache service and version | false | redis:7.4 | | varnish | HTTP cache service and version | false | varnish:8.0 | -| static_content_themes | Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. | false | Magento/luma | +| static_content_themes | Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. | false | Magento/luma Magento/backend | +| backend_frontname | `setup:install --backend-frontname`. Passed to the install and to the suite from this one place, so the two cannot disagree about the admin URL. | false | admin | +| disable_admin_auth_modules | Disable `Magento_TwoFactorAuth` and `MageOS_PasskeyAuth` so a suite can sign in to the admin. Set `false` for a storefront-only run. | false | true | ### Where the suite comes from @@ -106,7 +108,54 @@ would be slower and flakier for no gain. | `PLAYWRIGHT_BASE_URL` | the served store's URL | | `MAGEOS_VERSION` | e.g. `4.0.0` | | `MAGENTO_VERSION` | the upstream version it is based on, e.g. `2.4.9` | - +| `MAGENTO_ADMIN_USER` | the admin account the install created | +| `MAGENTO_ADMIN_PASSWORD` | its password | +| `MAGENTO_ADMIN_FRONTNAME` | whatever `backend_frontname` was set to | + +The admin credentials are not inputs. `warden/setup-environment` hardcodes +them in its `admin:user:create` step, so an input a caller could change +without the store changing would only ever be a lie. They are not secrets +either: the store is created and destroyed inside one job. + +`backend_frontname` **is** an input, and it reaches the install and the suite +from that single place. Two places holding separate opinions about the admin +URL is a 404 that presents as a broken admin. + +## Signing in to the admin + +`disable_admin_auth_modules` (default `true`) disables +`Magento_TwoFactorAuth` and `MageOS_PasskeyAuth` after the install. + +This is not a convenience. Magento has no configuration flag that switches 2FA +off: `twofactorauth/general/force_providers` is empty by default, and +`ControllerActionPredispatch` still routes a fresh admin user to +`tfa/tfa/index`, which redirects to `tfa/tfa/requestconfig`. Disabling the +module is the only way in. `MageOS_PasskeyAuth` requires it and registers an +admin 2FA provider, so the two go together or `module:disable` refuses the +command. `MageOS_PasskeyAuth` does not exist outside Mage-OS, so the step +checks before naming it -- `module:status` exits `0` even for a module that is +not installed, so its output is the only signal. + +The step also pins `admin/usage/enabled` to `0`, its own default, because that +flag gates `Magento_AdminAnalytics`' usage-data modal, which would otherwise +cover the dashboard on first sign-in. + +And it disables the admin login CAPTCHA. That one is **on** by default: +`admin/captcha/enable` is `1` in `after_fail` mode, asking for a CAPTCHA after +three failed attempts per login name, counted in the `captcha_log` table. Any +suite that asserts a bad credential is refused generates those failures, so +leaving it on lets a negative control poison the positive one -- and it +surfaces as `Incorrect CAPTCHA` on a password that is correct, which sends you +looking in the wrong place entirely. + +The cost is explicit: **a run with this on does not cover admin 2FA.** Doing +that properly means driving a TOTP provider from its shared secret, which is +worth a spec of its own rather than a flag here. + +`Magento/backend` is in the `static_content_themes` default for the same +reason: an admin spec against an undeployed admin theme waits for every asset +to be generated on demand, and reads as a timeout rather than as a missing +deploy. Both versions are **probed from the running store** (`bin/magento --version`), not echoed back from `magento_version`. A version input can be a constraint, the repository can resolve it differently than expected, and a gate should diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index ceae28bb..00bc8b1b 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -58,8 +58,18 @@ on: static_content_themes: required: false type: string - default: "Magento/luma" - description: "Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower." + default: "Magento/luma Magento/backend" + description: "Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. Magento/backend is in the default because an admin spec against an undeployed admin theme reads as a timeout rather than as a missing deploy." + backend_frontname: + required: false + type: string + default: "admin" + description: "setup:install --backend-frontname. Passed to the install and to the suite from this one place, so the two cannot disagree about the admin URL." + disable_admin_auth_modules: + required: false + type: boolean + default: true + description: "Disable Magento_TwoFactorAuth and MageOS_PasskeyAuth so a suite can sign in to the admin. Magento offers no configuration flag for this; see the step for why. Set false for a storefront-only run, which then leaves 2FA in place." # Where the suite comes from. The default is the suite this repository # carries for its own canary; a caller with a suite of its own overrides @@ -140,6 +150,12 @@ jobs: TRAEFIK_SUBDOMAIN: app # The suite is checked out here, and the tests run in SUITE/<dir>. SUITE: suite + # What warden/setup-environment's admin:user:create step makes. The + # action hardcodes these, so they are not inputs: an input a caller + # could change without the store changing would only ever be a lie. + # Not a secret either -- a throwaway store for the length of the job. + ADMIN_USER: "admin" + ADMIN_PASSWORD: "abcABC123" steps: # Not at the workspace root: warden/setup-environment checks the Warden CLI @@ -181,6 +197,7 @@ jobs: run_reindex: 1 traefik_domain: ${{ env.TRAEFIK_DOMAIN }} traefik_subdomain: ${{ env.TRAEFIK_SUBDOMAIN }} + backend_frontname: ${{ inputs.backend_frontname }} base_url: "https://${{ env.TRAEFIK_SUBDOMAIN }}.${{ env.TRAEFIK_DOMAIN }}/" configure_host_resolution: 1 run_static_content_deploy: 1 @@ -243,6 +260,58 @@ jobs: # A bare setup:install has nothing to buy. The command reindexes itself. # Streamed in rather than copied: the project directories are owned by the # container's user. + # Magento has no switch for two-factor authentication. There is no enable + # flag, and leaving twofactorauth/general/force_providers empty does not + # help: ControllerActionPredispatch still routes a fresh admin user to + # tfa/tfa/index, which redirects to tfa/tfa/requestconfig. Disabling the + # module is the only way in. MageOS_PasskeyAuth requires it and registers + # an admin 2FA provider, so both have to go in one command or dependency + # validation refuses it. + # + # The cost is stated rather than hidden: a run with this on does not cover + # admin 2FA. Covering it means driving a TOTP provider from its shared + # secret, which is worth doing, as its own spec. + - name: Open the admin to the test suite + if: inputs.disable_admin_auth_modules + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + MODULES=() + for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do + # module:status exits 0 even for a module that is not installed, so + # its output is the only signal. MageOS_PasskeyAuth is Mage-OS only, + # and this workflow should still work against a Magento install. + if ${WARDEN} env exec -T php-fpm bin/magento module:status "${MODULE}" 2>&1 | grep -q 'does not exist'; then + echo "${MODULE} is not installed" + else + MODULES+=("${MODULE}") + fi + done + + # An array, not a string: module:disable takes the names as separate + # arguments and reads a single space-joined string as one unknown + # module name. Re-running it changes nothing and still exits 0. + if [ ${#MODULES[@]} -gt 0 ]; then + ${WARDEN} env exec -T php-fpm bin/magento module:disable "${MODULES[@]}" + fi + + # Already the default. Pinned so the suite does not rely on one: it + # gates Magento_AdminAnalytics' usage-data modal, which would + # otherwise cover the dashboard on first sign-in. + ${WARDEN} env exec -T php-fpm bin/magento config:set admin/usage/enabled 0 + + # The admin login CAPTCHA is on by default (admin/captcha/enable 1) in + # after_fail mode, and asks for one after three failed attempts per + # login name -- counted in the captcha_log table, which survives + # across runs against a long-lived store. A suite that asserts a bad + # credential is refused produces exactly those failures, so leaving + # this on lets the negative control poison the positive one, and the + # symptom is an "Incorrect CAPTCHA" that looks nothing like the cause. + ${WARDEN} env exec -T php-fpm bin/magento config:set admin/captcha/enable 0 + ${WARDEN} env exec -T php-fpm bin/magento cache:flush + - name: Seed the catalog if: inputs.fixture_profile != '' working-directory: ./_ghamagento @@ -276,6 +345,9 @@ jobs: PLAYWRIGHT_BASE_URL: ${{ steps.warden.outputs.base_url }} MAGEOS_VERSION: ${{ steps.stack.outputs.mageos }} MAGENTO_VERSION: ${{ steps.stack.outputs.magento }} + MAGENTO_ADMIN_USER: ${{ env.ADMIN_USER }} + MAGENTO_ADMIN_PASSWORD: ${{ env.ADMIN_PASSWORD }} + MAGENTO_ADMIN_FRONTNAME: ${{ inputs.backend_frontname }} run: bash -c "$TEST_COMMAND" # A failing gate is read by someone deciding whether to ship, so the diff --git a/_test/demo-package/Test/e2e/.env.example b/_test/demo-package/Test/e2e/.env.example index 735dc1a9..f13089b0 100644 --- a/_test/demo-package/Test/e2e/.env.example +++ b/_test/demo-package/Test/e2e/.env.example @@ -1,3 +1,10 @@ # The store the suite opens. There is no default: a suite that silently tests # someone else's demo store is worse than one that refuses to start. PLAYWRIGHT_BASE_URL=https://app.mageos.test/ + +# The admin account warden/setup-environment creates, and the frontname +# setup:install was given. Defaults in admin/support.ts match the action, so +# these only need setting when pointing the suite at some other store. +MAGENTO_ADMIN_USER=admin +MAGENTO_ADMIN_PASSWORD=abcABC123 +MAGENTO_ADMIN_FRONTNAME=admin diff --git a/_test/demo-package/Test/e2e/.gitignore b/_test/demo-package/Test/e2e/.gitignore index 3c3e172c..6fb83b67 100644 --- a/_test/demo-package/Test/e2e/.gitignore +++ b/_test/demo-package/Test/e2e/.gitignore @@ -2,3 +2,4 @@ node_modules/ playwright-report/ test-results/ .env +.auth/ diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 25521b2c..fb23d217 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -1,9 +1,10 @@ -# Storefront tests +# Browser tests -A small Playwright suite that proves a Mage-OS storefront is **being served** -and **can take an order** -- installed, reachable over HTTP(S), rendering with -its static content deployed, and able to carry a guest from a category listing -to a persisted order. +A small Playwright suite that proves a Mage-OS release is **being served**, +**can take an order** and **lets an administrator in** -- installed, reachable +over HTTP(S), rendering with its static content deployed, able to carry a +guest from a category listing to a persisted order, and able to authenticate +into the admin. It is the canary for [`warden/setup-environment`](../../../../warden/setup-environment): `.github/workflows/_internal-e2e.yaml` stands a store up with that action on @@ -13,6 +14,7 @@ every change to it and runs this suite against the result. | --- | --- | --- | | `hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | | `guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | +| `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | ## Running it against a store @@ -26,9 +28,100 @@ npm test `guest-checkout.spec.ts` needs a salable product, which a bare `setup:install` does not have. Seed one first -- see [Fixtures](#fixtures). +The admin specs need an admin account and a reachable admin URL. Set +`MAGENTO_ADMIN_USER`, `MAGENTO_ADMIN_PASSWORD` and `MAGENTO_ADMIN_FRONTNAME` +in `.env` if your store does not match the defaults in `admin/support.ts`, and +disable the two auth modules named below. To run one side only: + +```bash +npx playwright test --project=storefront +npx playwright test --project=admin # pulls in admin-session itself +``` + There is no default base URL. A suite that silently falls back to some public demo store reports green about a store nobody asked about. +## The admin specs + +The storefront is a thin skin over the catalog; the admin is where the +framework lives -- UI components, data providers, the EAV save path, ACL, the +requirejs and knockout bootstrap. Those are also the most-refactored parts of +the codebase, which makes them the parts a release is most likely to break. + +They run in their own Playwright project: + +| Project | Selects | Session | +| --- | --- | --- | +| `admin-session` | `admin/session.setup.ts` | signs in, saves `admin/.auth/admin.json` | +| `storefront` | everything outside `admin/` | none | +| `admin` | `admin/*.spec.ts` | reuses the saved session | + +The sign-in is a **project dependency** rather than a `globalSetup` hook so +that it appears in the report as its own result. "The session could not be +created" and "every admin spec failed" are different problems; if the sign-in +breaks, the dependency fails once and the admin specs report `did not run` +instead of producing a wall of identical reds. + +`admin/login.spec.ts` resets `storageState` to empty, because it is the one +spec whose subject *is* the sign-in form. Everything else inherits the session. + +### Two traps worth knowing + +The password field's id is `login`, not `password` -- the id is on the field, +`login[password]` is its name. Guessing gives a timeout that reads like a +broken store. + +`#login-form` is **ambiguous**. The storefront authentication popup uses the +same id, so a request that lands on the storefront instead of the admin finds +a `#login-form` and the failure stops being about the admin. The specs assert +the `adminhtml-auth-login` body class first, the same route-discriminator +trick the storefront specs use, and scope the form to `.login-content`. This +was found by a negative control, not by reading markup: pointing the suite at +a wrong frontname passed its form assertion against the storefront's hidden +login form. + +### What makes the admin reachable at all + +Magento has **no configuration flag that switches two-factor authentication +off**. `twofactorauth/general/force_providers` is empty by default, and that +does not help: `ControllerActionPredispatch` still routes a fresh admin user +to `tfa/tfa/index`, which redirects to `tfa/tfa/requestconfig`. Disabling +`Magento_TwoFactorAuth` is the only way in, and `MageOS_PasskeyAuth` requires +it and registers an admin 2FA provider, so both have to be disabled in one +command or dependency validation refuses it. The workflow does this and says +so; the cost is that this gate does not cover admin 2FA. + +The admin login **CAPTCHA** is on by default -- `admin/captcha/enable` is +`1`, in `after_fail` mode, asking for one after **three failed attempts per +login name**. The count lives in the `captcha_log` table, so against a +long-lived store it accumulates across runs. A suite that asserts a bad +credential is refused manufactures exactly those failures, which is how a +negative control ends up poisoning the positive one; the symptom is an +`Incorrect CAPTCHA` on a *correct* password, which looks nothing like its +cause. The workflow disables it. If you hit it on a store that has not been +configured that way, `truncate table captcha_log` is the reset. + +The specs reduce their own exposure anyway: the refusal test signs in as a +name that is not an account, so the failures are counted against a login +nobody will use, and the three sign-in tests are separate tests rather than +steps of one, so each runs in its own browser context. + +There is deliberately **no modal dismissal helper**. Both candidates were +checked rather than assumed: + +- `Magento_AdminAnalytics`' usage-data prompt is gated by + `CanViewNotification::isVisible()`, which returns `false` unless + `admin/usage/enabled` is set. It defaults to `0`, and the workflow pins it. +- `Magento_ReleaseNotification` builds its content URL from + `system/release_notification/content_url`. Mage-OS ships that **empty**, so + `UrlBuilder::getUrl()` returns `''` and there is nothing to render. + +Neither appears on a store this gate installs. A blanket "click away whatever +is covering the page" helper would be dead code today and a liability later: +if a future release does grow a blocking dialog on first sign-in, the right +outcome is a red test with a screenshot of it, not a suite that dismisses it +and reports green. + ## Why the assertions look like that A `200` is not evidence of a storefront. The admin login page, a CMS no-route diff --git a/_test/demo-package/Test/e2e/admin/login.spec.ts b/_test/demo-package/Test/e2e/admin/login.spec.ts new file mode 100644 index 00000000..6124386e --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/login.spec.ts @@ -0,0 +1,50 @@ +import { expect, test } from '@playwright/test'; +import { admin, adminSelectors, adminUrl, signIn } from './support'; + +// These specs are about the sign-in form itself, so they start with no session +// rather than the one admin/session.setup.ts saved. Without this they would +// arrive already authenticated and assert nothing. +test.use({ storageState: { cookies: [], origins: [] } }); + +// Two tests rather than two steps of one, so each gets its own browser context. +// Signing in badly and then well inside a single context does not behave like +// two separate attempts: Magento counts the failure, and the admin CAPTCHA +// (admin/captcha/enable, on by default, after_fail at three attempts per login +// name) can then intercept the good credential. The workflow turns that off, +// and the contexts keep these independent of each other as well. +test.describe('Admin sign-in', () => { + test('@admin serves the sign-in form under the admin frontname', async ({ page }) => { + const response = await page.goto(adminUrl()); + + expect(response?.status()).toBe(200); + // The route discriminator, asserted before the form: #login-form alone + // is ambiguous, because the storefront authentication popup uses that + // id too. Without this, a request that lands on the storefront passes. + await expect(page.locator('body')).toHaveClass(adminSelectors.loginPageBodyClass); + await expect(page.locator(adminSelectors.loginForm)).toBeVisible(); + }); + + test('@admin refuses a credential that is not an account', async ({ page }) => { + // A username that does not exist, rather than the real account with a + // wrong password: failures are counted per login name, in captcha_log + // and in admin_user.failures_num. Spending them on a name nobody will + // sign in with keeps this from making the next test flaky. + await signIn(page, 'not-a-real-admin', 'definitely-not-the-password'); + + await expect(page.locator(adminSelectors.errorMessage)).toBeVisible(); + // Still the sign-in page, rather than "not the dashboard": asserting + // the absence of a URL passes on an error page too. + await expect(page.locator('body')).toHaveClass(adminSelectors.loginPageBodyClass); + }); + + test('@admin accepts the account the install created', async ({ page }) => { + await signIn(page, admin.user, admin.password); + + // The dashboard by page identity, not by URL. Magento serves it at + // whatever admin path was requested rather than always redirecting to + // admin/dashboard, so the URL depends on how the session got here. + await expect(page.locator('body')).toHaveClass(adminSelectors.dashboardBodyClass); + await expect(page.locator(adminSelectors.menu)).toBeVisible(); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('Dashboard'); + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/session.setup.ts b/_test/demo-package/Test/e2e/admin/session.setup.ts new file mode 100644 index 00000000..55503444 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/session.setup.ts @@ -0,0 +1,26 @@ +import { expect, test as setup } from '@playwright/test'; +import { admin, adminSelectors, adminStateFile, signIn } from './support'; + +/** + * Signs in once and saves the session for every spec in the admin project. + * + * This is a project dependency rather than a globalSetup hook so that the + * sign-in shows up in the report as its own result. "The session could not be + * created" and "every admin spec failed" are different problems, and a release + * gate is read by someone deciding whether to ship: they should not look alike. + */ +setup('an admin session can be established and saved', async ({ page }) => { + await setup.step('the sign-in form accepts the credentials the install made', async () => { + await signIn(page, admin.user, admin.password); + }); + + await setup.step('the dashboard loads with the admin menu rendered', async () => { + // By page identity rather than URL: Magento serves the dashboard at + // whichever admin path was requested, so the URL is not a reliable + // statement about which page rendered. + await expect(page.locator('body')).toHaveClass(adminSelectors.dashboardBodyClass); + await expect(page.locator(adminSelectors.menu)).toBeVisible(); + }); + + await page.context().storageState({ path: adminStateFile }); +}); diff --git a/_test/demo-package/Test/e2e/admin/support.ts b/_test/demo-package/Test/e2e/admin/support.ts new file mode 100644 index 00000000..5f7a9129 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/support.ts @@ -0,0 +1,84 @@ +import { expect, type Page } from '@playwright/test'; +import path from 'node:path'; + +/** + * These mirror what warden/setup-environment's admin:user:create step makes. + * The action hardcodes them, so the workflow passes them through rather than + * letting the suite and the store hold separate opinions about the password. + */ +export const admin = { + user: process.env.MAGENTO_ADMIN_USER ?? 'admin', + password: process.env.MAGENTO_ADMIN_PASSWORD ?? 'abcABC123', + // setup:install --backend-frontname. Pinned by the workflow so a spec can + // navigate straight to an admin route instead of clicking through menus, + // which is the difference between an admin suite that is maintainable and + // one that breaks whenever the menu is reordered. + frontname: process.env.MAGENTO_ADMIN_FRONTNAME ?? 'admin', +}; + +/** + * Written by admin/session.setup.ts and read by the admin project's + * storageState. Not committed: it holds a live admin session cookie. + */ +export const adminStateFile = path.resolve(__dirname, '.auth/admin.json'); + +/** A path under the admin frontname, e.g. adminUrl('catalog/product/new'). */ +export function adminUrl(route = ''): string { + return `/${admin.frontname}/${route.replace(/^\/+/, '')}`; +} + +export const adminSelectors = { + // The admin login route, identified by its body class the same way the + // storefront specs identify theirs. This is asserted before the form + // because #login-form on its own is ambiguous: the storefront + // authentication popup carries that same id, so a request that lands on + // the storefront rather than the admin -- a wrong frontname, say -- finds + // a #login-form and the failure stops being about the admin at all. + loginPageBodyClass: /adminhtml-auth-login/, + loginForm: '.login-content #login-form', + // The dashboard, identified the same way. Asserted instead of the URL + // because Magento renders the dashboard at whichever admin path was + // requested -- sign in from /admin/ and you stay on /admin/ -- so a URL + // assertion passes or fails depending on how the session arrived. + dashboardBodyClass: /adminhtml-dashboard-index/, + username: '#username', + // The password field's id is "login", not "password" -- the name is + // login[password]. Worth stating, because guessing #password here gives a + // timeout that looks like a broken store rather than a bad selector. + password: '#login', + submit: 'button.action-login', + errorMessage: '.message-error', + menu: '.admin__menu', + pageTitle: '.page-title', +}; + +/* + * There is deliberately no "dismiss whatever modal is covering the page" + * helper here, and the two candidates were checked rather than assumed: + * + * - Magento_AdminAnalytics' usage-data prompt is gated by + * CanViewNotification::isVisible(), which returns false unless + * admin/usage/enabled is set. It defaults to 0, and the workflow pins it. + * - Magento_ReleaseNotification builds its content URL from + * system/release_notification/content_url. Mage-OS ships that empty, so + * UrlBuilder::getUrl() returns '' and the modal has nothing to render. + * + * So neither appears on a store this gate installs. Blanket modal dismissal + * would be dead code today and a liability later: if a future release does + * grow a blocking dialog on first sign-in, the right outcome is a red test + * with a screenshot of it, not a suite that clicks it away and reports green. + */ + +/** + * Asserts the page really is the admin sign-in form, then fills and submits + * it. Says nothing about whether the sign-in succeeded -- that is the caller's + * assertion to make, and both outcomes are worth testing. + */ +export async function signIn(page: Page, user: string, password: string): Promise<void> { + await page.goto(adminUrl()); + await expect(page.locator('body')).toHaveClass(adminSelectors.loginPageBodyClass); + await expect(page.locator(adminSelectors.loginForm)).toBeVisible(); + await page.fill(adminSelectors.username, user); + await page.fill(adminSelectors.password, password); + await page.click(adminSelectors.submit); +} diff --git a/_test/demo-package/Test/e2e/playwright.config.ts b/_test/demo-package/Test/e2e/playwright.config.ts index eed3cadf..c2ea40e8 100644 --- a/_test/demo-package/Test/e2e/playwright.config.ts +++ b/_test/demo-package/Test/e2e/playwright.config.ts @@ -1,5 +1,6 @@ import { defineConfig, devices } from '@playwright/test'; import dotenv from 'dotenv'; +import { adminStateFile } from './admin/support'; dotenv.config(); @@ -39,5 +40,26 @@ export default defineConfig({ screenshot: 'only-on-failure', video: 'retain-on-failure', }, - projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + projects: [ + // The admin specs share one signed-in session rather than signing in + // again per spec. A project dependency, not a globalSetup hook: this + // way the sign-in is a reported result of its own, so a broken login + // and a broken admin page do not present as the same red. + { + name: 'admin-session', + testMatch: /admin[\\/]session\.setup\.ts$/, + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'storefront', + testIgnore: /admin[\\/]/, + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'admin', + testMatch: /admin[\\/].*\.spec\.ts$/, + dependencies: ['admin-session'], + use: { ...devices['Desktop Chrome'], storageState: adminStateFile }, + }, + ], }); From 0a885fe4c4aa4508ec676365c31122d579a3e240 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Wed, 11 Nov 2026 22:01:48 -0600 Subject: [PATCH 14/42] docs(e2e): note what to pair with disable_admin_auth_modules: false Leaving 2FA in place means the admin specs cannot sign in, so the flag only makes sense together with a test_command that does not select them. Without that, the run fails on the session setup rather than on anything it meant to test. --- .github/workflows/e2e-README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index e2852f94..944aa766 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -152,6 +152,15 @@ The cost is explicit: **a run with this on does not cover admin 2FA.** Doing that properly means driving a TOTP provider from its shared secret, which is worth a spec of its own rather than a flag here. +Setting it `false` leaves 2FA in place, which means the admin specs cannot +sign in. Pair it with a `test_command` that does not select them, or the run +fails on the session setup rather than on anything it meant to test: + +```yaml +disable_admin_auth_modules: false +test_command: "npx playwright test --project=storefront" +``` + `Magento/backend` is in the `static_content_themes` default for the same reason: an admin spec against an undeployed admin theme waits for every asset to be generated on demand, and reads as a timeout rather than as a missing From d40cea75129c1115b46bfd49c67c9952ccd42160 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:08:02 -0600 Subject: [PATCH 15/42] test(e2e): work a grid and create a product in the admin Two admin specs, in this order on purpose. The grid spec is the whole Magento_Ui stack in one page: requirejs resolves the component, Knockout renders the table, a separate mui/index/render request answers with the data and the collection applies the filter. If that is broken, every admin screen is broken -- and a create-product spec fails too, with no way to tell "the form never rendered" from "the product could not be saved". The create spec then crosses the seams no storefront check can reach: form validation, the EAV write path, attribute set defaults, the stock item, url rewrite generation, the indexers that make a product salable, and a storefront quote. Fixtures are written straight to the database, so a seeded catalog passing says nothing about whether a merchant can add a product. The Luma selector map moves to luma.ts, shared with guest-checkout, so the two specs agree on what a product page looks like. Four traps, each found by a red run rather than by reading markup: - Every grid toolbar and table exists twice, duplicated inside .sticky-header, so both match two elements. The real table carries data-role="grid"; the real toolbar is a direct child of the outer wrap. - The notification bell is a second grid on every admin page, and its loading mask is otherwise indistinguishable from the one under test, so the mask is selected by data-component. - Grid filter state is saved per admin user in ui_bookmark, not per session, so a filter one run leaves applied is still applied for the next. Both specs start unfiltered and the filter is cleared as an asserted step. - The grid caches pages client-side, so clearing a filter can re-render with no request at all. Counts that settle asynchronously are polled. catalog/product/new is a 404 without an attribute set, so the spec clicks Add Product rather than hardcoding the default set id, and the url key is set explicitly so the storefront step is about url rewrites rather than about how a name becomes a url. The spec writes one product per run, with the sku generated inside the test so a retry does not collide with what the failed attempt saved. Both READMEs say so: an admin suite belongs against a throwaway store. --- .github/workflows/e2e-README.md | 6 + _test/demo-package/Test/e2e/README.md | 91 +++++++++- .../Test/e2e/admin/create-product.spec.ts | 163 ++++++++++++++++++ .../Test/e2e/admin/product-grid.spec.ts | 113 ++++++++++++ _test/demo-package/Test/e2e/admin/support.ts | 125 +++++++++++++- .../Test/e2e/guest-checkout.spec.ts | 28 +-- _test/demo-package/Test/e2e/luma.ts | 44 +++++ 7 files changed, 538 insertions(+), 32 deletions(-) create mode 100644 _test/demo-package/Test/e2e/admin/create-product.spec.ts create mode 100644 _test/demo-package/Test/e2e/admin/product-grid.spec.ts create mode 100644 _test/demo-package/Test/e2e/luma.ts diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 944aa766..1c1ed934 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -161,6 +161,12 @@ disable_admin_auth_modules: false test_command: "npx playwright test --project=storefront" ``` +An admin suite also **writes to the store**. The specs in this repository +create a product per run, and the admin grids remember their filters per admin +user in the `ui_bookmark` table. Both are fine against the throwaway store this +workflow installs, and neither is something to point at a store anyone cares +about. + `Magento/backend` is in the `static_content_themes` default for the same reason: an admin spec against an undeployed admin theme waits for every asset to be generated on demand, and reads as a timeout rather than as a missing diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index fb23d217..d3d8b0ad 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -1,10 +1,10 @@ # Browser tests A small Playwright suite that proves a Mage-OS release is **being served**, -**can take an order** and **lets an administrator in** -- installed, reachable -over HTTP(S), rendering with its static content deployed, able to carry a -guest from a category listing to a persisted order, and able to authenticate -into the admin. +**can take an order** and **can be administered** -- installed, reachable over +HTTP(S), rendering with its static content deployed, able to carry a guest from +a category listing to a persisted order, and able to let an administrator sign +in, work a grid and create a product that a shopper can then buy. It is the canary for [`warden/setup-environment`](../../../../warden/setup-environment): `.github/workflows/_internal-e2e.yaml` stands a store up with that action on @@ -15,6 +15,12 @@ every change to it and runs this suite against the result. | `hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | | `guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | | `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | +| `admin/product-grid.spec.ts` | yes | the product grid renders through Magento_Ui and filters server-side | +| `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | + +Storefront selectors live in `luma.ts`, shared by every spec that looks at a +storefront page. A Hyva variant of this suite is that file with a different +map, not a rewrite of the specs. ## Running it against a store @@ -65,7 +71,7 @@ instead of producing a wall of identical reds. `admin/login.spec.ts` resets `storageState` to empty, because it is the one spec whose subject *is* the sign-in form. Everything else inherits the session. -### Two traps worth knowing +### Two traps in the sign-in form The password field's id is `login`, not `password` -- the id is on the field, `login[password]` is its name. Guessing gives a timeout that reads like a @@ -80,6 +86,81 @@ was found by a negative control, not by reading markup: pointing the suite at a wrong frontname passed its form assertion against the storefront's hidden login form. +### Why the grid spec runs before the create spec + +A grid is the whole `Magento_Ui` stack in one page: requirejs resolves the +component, Knockout renders the table, a separate `mui/index/render` request +answers with the data and the collection applies the filters. None of that +markup is in the HTML the server sends, so a grid that renders at all is a +statement that the admin's JavaScript stack works. + +That ordering is the point. If the UI component stack is broken, the create +spec fails too -- and on its own it cannot tell you whether the form never +rendered or the product could not be saved. The grid spec answers that first, +cheaply. + +`admin/create-product.spec.ts` then crosses the seams a storefront-only check +cannot reach: the form's validation, the EAV write path, the attribute set +defaults, the stock item, url rewrite generation, the indexers that make a +product salable, and finally the storefront and a quote. Fixtures are written +straight to the database, so **they skip that entire write path** -- which is +why a seeded catalog passing says nothing about whether a merchant can add a +product. + +It writes data. One product per run, with a unique SKU, and the SKU is +generated inside the test rather than at module scope so that a retry does not +collide with what the failed attempt already saved. Point this suite at a +throwaway store, not a long-lived one. + +### Traps in the admin UI components + +Each of these cost a red run to find, and none of them is visible in the +markup the server sends. + +**Every grid toolbar and table exists twice.** The admin renders a copy of +both inside a `.sticky-header` element, with the same classes, so +`table.data-grid` and `button[data-action="grid-filter-expand"]` each match two +elements and Playwright refuses to act on either. The real table is the one +with `data-role="grid"`; the real toolbar is the one that is a *direct* child +of `.admin__data-grid-outer-wrap`. `admin/support.ts` scopes both. + +**There is a second grid on every admin page.** The notification bell in the +header is a grid component of its own, and its loading mask carries the same +class as the one belonging to the grid under test. The mask has to be selected +by `data-component`, which is why `adminGrid()` takes the listing name. + +**Grid filter state is saved per admin user, not per session.** It lives in +the `ui_bookmark` table, so a filter a spec leaves applied is still applied the +next time anything -- another spec, a retry, a human -- opens that grid. The +grid spec clears its filter as an asserted step, and both specs call +`startUnfiltered()` first so a half-failed run cannot decide what the next one +sees. This was found the honest way: a throwaway probe script left a filter +behind and the listing assertion went red on the next run, which is exactly +what `> 1 row` rather than `> 0 rows` is there to catch. + +**The grid caches pages client-side.** Clearing a filter often re-renders from +`Magento_Ui/js/grid/data-storage` with **no network request at all**, so +waiting for a response hangs, and reading the record count once reads the +number that was on screen before Knockout re-rendered. Numbers that settle +asynchronously are asserted with `expect.poll`. + +**`catalog/product/new` is a 404.** The controller forwards to noroute without +an attribute set, so the real route is +`catalog/product/new/set/<id>/type/simple`. The create spec clicks **Add +Product** on the grid instead, because the id of the default attribute set is +not something a spec should hardcode. + +**Admin body classes are the full action name**, and only the screens that live +in `Magento_Backend` are prefixed with `adminhtml-`. The dashboard is +`adminhtml-dashboard-index`; the product grid is `catalog-product-index`, with +no prefix at all. + +**The product form renders its collapsible sections lazily.** `url_key` is not +in the DOM until the Search Engine Optimization section has been clicked open. +The create spec sets the url key explicitly rather than deriving it from the +product name, so that the storefront step is a statement about url rewrites +instead of a guess about how a name becomes a url. + ### What makes the admin reachable at all Magento has **no configuration flag that switches two-factor authentication diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts new file mode 100644 index 00000000..b768e647 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -0,0 +1,163 @@ +import { expect, test } from '@playwright/test'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +import { luma, productUrl } from '../luma'; + +/** + * The spec that crosses the most seams in the application, and the reason the + * admin is worth gating a release on at all. + * + * Saving one simple product in the admin form exercises the UI component form + * and its validation, the EAV write path, the attribute set defaults, the + * stock item, the url rewrite generation and the indexers that make a product + * salable. Buying it afterwards proves all of that reached the storefront. + * Each of those has broken in a Magento release at some point, and none of + * them is visible from a storefront-only smoke test against a seeded catalog: + * fixtures are written straight to the database, so they skip the entire write + * path this spec is about. + */ + +const productForm = { + bodyClass: /catalog-product-new/, + savedBodyClass: /catalog-product-edit/, + addProduct: '#add_new_product', + name: '.admin__field[data-index=name] input', + sku: '.admin__field[data-index=sku] input', + price: '.admin__field[data-index=price] input', + quantity: '.admin__field[data-index=qty] input', + stockStatus: '[data-index="product-details"] select[name="product[quantity_and_stock_status][is_in_stock]"]', + // Collapsed on load, and its fields are not in the DOM until it is opened: + // the collapsible renders its content lazily, so url_key cannot be filled + // without clicking this first. + seoSection: 'div[data-index="search-engine-optimization"]', + urlKey: 'input[name="product[url_key]"]', + save: '#save-button', + saved: 'div[data-ui-id="messages-message-success"]', +}; + +test.describe('Creating a product in the admin', () => { + test('@admin creates a simple product and sells it', async ({ page }) => { + // Inside the test, not at module scope, so that a retry gets its own + // sku. The first attempt may well have saved the product before + // failing, and "The value of attribute SKU must be unique" on the + // retry would bury the failure that mattered. + const stamp = `${Date.now()}`; + const product = { + name: `Mage-OS E2E Product ${stamp}`, + sku: `mageos-e2e-${stamp}`, + price: '42.00', + quantity: '100', + urlKey: `mageos-e2e-product-${stamp}`, + }; + + await test.step('the admin offers a new product form', async () => { + // Through the grid's Add Product button rather than straight to a + // URL: catalog/product/new on its own is a 404, because the + // controller forwards to noroute without an attribute set, and the + // id of the default set is not something a spec should hardcode. + await page.goto(adminUrl('catalog/product/')); + await adminGrid(page, 'product_listing').ready(); + await page.locator(productForm.addProduct).click(); + + await expect(page.locator('body')).toHaveClass(productForm.bodyClass); + // The form is a UI component too: these fields are rendered by + // Knockout, so finding them is already a statement that the form + // bootstrapped rather than that a page was served. + await expect(page.locator(productForm.name)).toBeVisible(); + await expect(page.locator(productForm.sku)).toBeVisible(); + await expect(page.locator(productForm.price)).toBeVisible(); + }); + + await test.step('the form accepts a simple product', async () => { + await page.locator(productForm.name).fill(product.name); + // After the name, because the sku field auto-fills from it and + // would overwrite whatever was typed here first. + await page.locator(productForm.sku).fill(product.sku); + await page.locator(productForm.price).fill(product.price); + await page.locator(productForm.quantity).fill(product.quantity); + // Set rather than assumed: the default is In Stock, but a product + // that cannot be bought is the one failure this spec must not + // mistake for a broken storefront. + await page.locator(productForm.stockStatus).selectOption('1'); + }); + + await test.step('the url key is set explicitly', async () => { + // Magento would derive one from the name, and this spec could + // guess at that transformation. Setting it means the storefront + // step below is a statement about url rewrites rather than a guess + // about how a name becomes a url. + await page.locator(productForm.seoSection).click(); + await expect(page.locator(productForm.urlKey)).toBeVisible(); + await page.locator(productForm.urlKey).fill(product.urlKey); + }); + + await test.step('saving the product reports success', async () => { + await page.locator(productForm.save).click(); + + await expect(page.locator(productForm.saved)).toContainText('You saved the product.'); + // On the edit form for a product with an id: the save redirected + // to a persisted entity rather than re-rendering the new form with + // the values still in it. + await expect(page.locator('body')).toHaveClass(productForm.savedBodyClass); + await expect(page).toHaveURL(/catalog\/product\/edit\/id\/\d+/); + await expect(page.locator(adminSelectors.pageTitle)).toContainText(product.name); + }); + + await test.step('the grid finds the product by its sku', async () => { + const grid = adminGrid(page, 'product_listing'); + + await page.goto(adminUrl('catalog/product/')); + await grid.ready(); + await grid.startUnfiltered(); + await grid.filterBy('sku', product.sku); + + // Exactly one, unlike the grid spec's LIKE filter caveat: this sku + // is unique to this attempt, so anything else here means the grid + // is showing rows that do not match its own filter. + await expect.poll(() => grid.recordsFound()).toBe(1); + await expect(grid.rows.first()).toContainText(product.sku); + + // The grid remembers filters per admin user, so leaving this one + // applied would change what every later run of the grid spec sees. + await grid.clearFilters(); + }); + + await test.step('the storefront serves the product it has never seen', async () => { + // Straight to the url key, with no catalog navigation: a url + // rewrite that was not generated is a 404 here, which is precisely + // the failure worth reporting. Finding the product through a + // category listing would additionally depend on the category + // assignment and the catalog search index, and would report all + // three as one red. + const response = await page.goto(productUrl(product.urlKey)); + + expect(response?.status(), 'the url rewrite for a saved product should resolve').toBe(200); + await expect(page.locator('body')).toHaveClass(/catalog-product-view/); + await expect(page.locator(luma.pageTitle)).toContainText(product.name); + // The price this spec typed, rather than any price: a rendered + // price is the price index having run for a product that did not + // exist a moment ago, and the storefront renders it as $42.00, so + // the stored value is a substring of what the theme shows. + await expect(page.locator(luma.productPrice).first()).toContainText(product.price); + // Enabled, not merely present: the button renders for an + // out-of-stock product too, so this is the salability assertion. + await expect(page.locator(luma.addToCart)).toBeEnabled(); + }); + + await test.step('the product can be bought', async () => { + await page.locator(luma.addToCart).click(); + + await expect(page.locator(luma.cartSuccess)).toContainText('to your shopping cart'); + // The minicart arrives over a separate customer-data request, so + // this is also the private-content path for a brand new product. + await expect(page.locator(luma.minicartCounter)).toHaveText('1'); + + await page.goto('/checkout/cart/'); + await expect(page.locator(luma.cartItemName)).toContainText(product.name); + }); + + // Checkout stops here on purpose. guest-checkout.spec.ts already walks + // shipping, payment and order placement; what this spec adds is that a + // product created through the admin reaches a quote at all, and + // repeating the rest would only make a slow suite slower. + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/product-grid.spec.ts b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts new file mode 100644 index 00000000..dc8a49a2 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts @@ -0,0 +1,113 @@ +import { expect, test } from '@playwright/test'; +import { adminGrid, adminSelectors, adminUrl } from './support'; + +/** + * The first admin screen worth gating a release on, and deliberately ahead of + * the specs that create things. + * + * A grid is the whole Magento_Ui stack in one page: requirejs resolves the + * component, Knockout renders the table, the data provider answers a separate + * mui/index/render request and the collection applies the filters. If any of + * that is broken then every admin screen is broken -- and a create-product + * spec fails too, with no way to tell "the form never rendered" from "the + * product could not be saved". This spec is what makes that distinction + * readable in a release report. + */ + +const productGrid = { + // Not adminhtml-catalog-product-index: the body class is the full action + // name, and this controller answers under the catalog route, so the admin + // screens outside Magento_Backend are not prefixed the way the dashboard + // and the login page are. + bodyClass: /catalog-product-index/, + route: 'catalog/product/', + component: 'product_listing', +}; + +test.describe('Admin product grid', () => { + test('@admin renders the product grid', async ({ page }) => { + const grid = adminGrid(page, productGrid.component); + + await test.step('the listing page loads under the admin frontname', async () => { + await page.goto(adminUrl(productGrid.route)); + + await expect(page.locator('body')).toHaveClass(productGrid.bodyClass); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('Products'); + }); + + await test.step('the grid component draws the catalog', async () => { + await grid.ready(); + await grid.startUnfiltered(); + + // More than one row, not just one: a spec that left a filter + // applied would otherwise pass here, and grid state is saved per + // admin user, so that leak is real and should be loud. + const rows = await grid.rows.count(); + expect(rows, 'the seeded catalog should fill the product grid').toBeGreaterThan(1); + + // The rows and the count come from different parts of the + // component -- the rendered records and the collection size -- so + // having them agree on the first page is a cheap consistency check. + expect(await grid.recordsFound()).toBeGreaterThanOrEqual(rows); + }); + + await test.step('the rows carry the columns a merchant works from', async () => { + const sku = await grid.columnIndex('SKU'); + + // Not an empty cell: a data provider that answered with the right + // shape but no values renders a full table of blanks. + await expect(grid.column(sku).first()).not.toBeEmpty(); + }); + }); + + test('@admin filters the product grid by sku', async ({ page }) => { + const grid = adminGrid(page, productGrid.component); + + await page.goto(adminUrl(productGrid.route)); + await grid.ready(); + // The grid remembers its filters per admin user, so a retry of this + // test would otherwise inherit the filter the failed attempt applied + // and measure "unfiltered" against an already filtered grid. + await grid.startUnfiltered(); + + const skuColumn = await grid.columnIndex('SKU'); + const unfiltered = await grid.recordsFound(); + const sku = (await grid.column(skuColumn).first().innerText()).trim(); + + await test.step(`the sku filter narrows the grid to ${sku}`, async () => { + await grid.filterBy('sku', sku); + + // The applied filter is shown back to the merchant. A filter that + // reached the collection but was never acknowledged in the UI is a + // bug that a row count alone would miss. + await expect(grid.activeFilters).toContainText(sku); + + // Polled rather than read once. The count is rendered by Knockout + // after the grid settles, and the grid does not always go to the + // server to settle: it caches pages it has already fetched, keyed + // by the request, so a filter the merchant has used before -- or + // the unfiltered page below -- can re-render with no request at + // all. Waiting for a response would hang on exactly that case, and + // reading the number once reads whatever was on screen before. + // + // Fewer, rather than exactly one: the sku filter is a LIKE and + // fixture skus are numbered, so one sku is legitimately a prefix + // of another. What matters is that the filter reached the + // collection and that every remaining row satisfies it. + await expect + .poll(() => grid.recordsFound(), { message: 'filtering should remove rows' }) + .toBeLessThan(unfiltered); + await expect(grid.rows).not.toHaveCount(0); + + for (const found of await grid.column(skuColumn).allInnerTexts()) { + expect(found.trim()).toContain(sku); + } + }); + + await test.step('clearing the filter restores the full listing', async () => { + await grid.clearFilters(); + + await expect.poll(() => grid.recordsFound()).toBe(unfiltered); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/support.ts b/_test/demo-package/Test/e2e/admin/support.ts index 5f7a9129..286ff071 100644 --- a/_test/demo-package/Test/e2e/admin/support.ts +++ b/_test/demo-package/Test/e2e/admin/support.ts @@ -1,4 +1,4 @@ -import { expect, type Page } from '@playwright/test'; +import { expect, type Locator, type Page } from '@playwright/test'; import path from 'node:path'; /** @@ -52,6 +52,129 @@ export const adminSelectors = { pageTitle: '.page-title', }; +/** + * Every admin listing -- products, customers, orders, CMS pages -- is the same + * Magento_Ui grid component, so one object drives all of them. + * + * It is also why a grid spec is worth more than it looks: none of this markup + * exists in the HTML the server sends. The table, the row count and the filter + * controls are rendered by Knockout from a separate mui/index/render request, + * so a grid that renders at all is a statement that requirejs resolved, the + * component bootstrapped and the data provider answered. A release that breaks + * any of those breaks every admin screen. + * + * @param component the listing's component name, e.g. product_listing. Needed + * because the admin header carries a second grid of its own -- the + * notification area -- whose loading mask is otherwise indistinguishable + * from the one belonging to the grid under test. + */ +export function adminGrid(page: Page, component: string) { + // The page content, which excludes the notification grid in the header. + const scope = page.locator('#container'); + // data-role="grid" rather than the class alone: the admin renders a second + // copy of the toolbar and the table inside a .sticky-header element, which + // carries the same classes. Every selector here has to say which copy it + // means or it matches two elements and Playwright refuses to act. + const table = scope.locator('table.data-grid[data-role="grid"]'); + // The real toolbar, as a direct child of the outer wrap. The sticky copy + // sits a level deeper, so this relationship is what separates them. + const toolbar = scope.locator('.admin__data-grid-outer-wrap > .admin__data-grid-header'); + + return { + table, + toolbar, + rows: table.locator('tr.data-row'), + headers: table.locator('thead th'), + activeFilters: toolbar.locator('.admin__data-grid-filters-current._show'), + + /** + * Waits for the grid to finish whatever request it is making. Every + * filter, sort and page change is an ajax round trip behind a loading + * mask, so without this an assertion races the rows it counts. + */ + async ready(): Promise<void> { + // Scoped by component: the admin header carries a grid of its own + // -- the notification area -- whose loading mask is otherwise + // indistinguishable from this one's. + await expect( + page.locator(`.admin__data-grid-loading-mask[data-component*="${component}"]`), + ).toBeHidden(); + await expect(table).toBeVisible(); + }, + + /** + * The number of records the grid says it found, which comes from the + * collection size rather than from the rows it drew. + */ + async recordsFound(): Promise<number> { + const text = await toolbar.locator('.admin__control-support-text').first().innerText(); + const found = text.match(/([\d,]+)\s+records found/); + + expect(found, `the grid should report how many records it found; it says "${text}"`).not.toBeNull(); + + return Number(found![1].replace(/,/g, '')); + }, + + /** + * The index of a column, by its header label. Which columns a grid + * shows is per-admin-user state -- saved as bookmarks, reorderable by + * dragging -- so a spec that wants the SKU cell asks which column that + * is rather than counting on it being the seventh. + */ + async columnIndex(label: string): Promise<number> { + const labels = (await this.headers.allInnerTexts()).map((header) => header.trim()); + const index = labels.findIndex((header) => header === label); + + expect( + index, + `the grid should have a "${label}" column; it has: ${labels.join(', ')}`, + ).toBeGreaterThanOrEqual(0); + + return index; + }, + + /** The cells of one column, top to bottom, as the grid renders them. */ + column(index: number): Locator { + return this.rows.locator(`td:nth-child(${index + 1})`); + }, + + /** Opens the filter panel, sets one field and applies it. */ + async filterBy(field: string, value: string): Promise<void> { + await toolbar.locator('button[data-action="grid-filter-expand"]').click(); + await toolbar.locator(`input.admin__control-text[name="${field}"]`).fill(value); + await toolbar.locator('button[data-action="grid-filter-apply"]').click(); + await this.ready(); + }, + + /** + * Clears every applied filter. Not politeness: grid state lives in the + * ui_bookmark table per admin user, so a filter a spec leaves applied + * is still applied the next time anything opens that grid. + */ + async clearFilters(): Promise<void> { + await toolbar.locator('button[data-action="grid-filter-reset"]').click(); + await this.ready(); + }, + + /** + * Starts from an unfiltered grid, whatever the last visitor left + * behind. Because that state is persisted per admin user rather than + * per session, the leak this cleans up is the suite's own: a filter + * spec that fails halfway, or a human clicking around the same store, + * otherwise decides what the next run sees. Says nothing about the + * store, so it asserts nothing. + */ + async startUnfiltered(): Promise<void> { + const clear = toolbar.locator('button[data-action="grid-filter-reset"]'); + + if (await clear.count()) { + await clear.click(); + await this.ready(); + } + }, + }; +} + /* * There is deliberately no "dismiss whatever modal is covering the page" * helper here, and the two candidates were checked rather than assumed: diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/guest-checkout.spec.ts index 1e16c6a5..895475f5 100644 --- a/_test/demo-package/Test/e2e/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/guest-checkout.spec.ts @@ -1,4 +1,5 @@ import { test, expect, type Page } from '@playwright/test'; +import { luma } from './luma'; // The deepest path a storefront check can walk: catalog -> product -> cart -> // shipping -> payment -> order. It touches the layered navigation, the price @@ -21,31 +22,6 @@ const shopper = { countryId: process.env.E2E_COUNTRY_ID ?? 'US', }; -// Every selector below is Luma's. Keeping them in one place is what makes the -// Hyva variant of this suite a copy of this file with a different map, rather -// than a rewrite. -const luma = { - navCategory: '.navigation li.level0 > a', - productItem: '.product-item-info', - productItemLink: 'a.product-item-link', - addToCart: '#product-addtocart-button', - swatchGroup: '.swatch-attribute', - swatchOption: '.swatch-option:not(.disabled)', - optionSelect: 'select.super-attribute-select', - cartSuccess: '.message-success', - minicartCounter: '.minicart-wrapper .counter-number', - cartItemName: '.cart.item .product-item-name', - proceedToCheckout: 'button[data-role="proceed-to-checkout"]', - checkoutEmail: '#customer-email', - shippingForm: '#co-shipping-form', - shippingMethod: 'input[value="flatrate_flatrate"]', - nextButton: 'button[data-role="opc-continue"]', - paymentSection: '#checkout-step-payment', - placeOrder: '#checkout-payment-method-load button.action.checkout.primary', - successPageTitle: '.page-title', - successBlock: '.checkout-success', -}; - // A configurable product will not go into the cart until every attribute has a // value, and which product the catalog lists first is not ours to decide. So // pick the first available value for whatever the page asks for, and let the @@ -121,7 +97,7 @@ test.describe('Guest checkout', () => { await expect(page.locator('.page-title')).toBeVisible(); // A price proves the price index ran. Out-of-stock or unindexed // products render a page but no add-to-cart button. - await expect(page.locator('.product-info-main .price').first()).toBeVisible(); + await expect(page.locator(luma.productPrice).first()).toBeVisible(); await expect(page.locator(luma.addToCart)).toBeEnabled(); }); diff --git a/_test/demo-package/Test/e2e/luma.ts b/_test/demo-package/Test/e2e/luma.ts new file mode 100644 index 00000000..159d90df --- /dev/null +++ b/_test/demo-package/Test/e2e/luma.ts @@ -0,0 +1,44 @@ +/** + * Every storefront selector the suite uses, in one place. + * + * All of these are Luma's. Keeping them here is what makes a Hyva variant of + * this suite a copy of this file with a different map, rather than a rewrite + * of the specs -- and it means a spec that creates a product in the admin and + * one that buys a fixture product agree on what a product page looks like. + */ +export const luma = { + navCategory: '.navigation li.level0 > a', + productItem: '.product-item-info', + productItemLink: 'a.product-item-link', + pageTitle: '.page-title', + productPrice: '.product-info-main .price', + addToCart: '#product-addtocart-button', + swatchGroup: '.swatch-attribute', + swatchOption: '.swatch-option:not(.disabled)', + optionSelect: 'select.super-attribute-select', + cartSuccess: '.message-success', + minicartCounter: '.minicart-wrapper .counter-number', + cartItemName: '.cart.item .product-item-name', + proceedToCheckout: 'button[data-role="proceed-to-checkout"]', + checkoutEmail: '#customer-email', + shippingForm: '#co-shipping-form', + shippingMethod: 'input[value="flatrate_flatrate"]', + nextButton: 'button[data-role="opc-continue"]', + paymentSection: '#checkout-step-payment', + placeOrder: '#checkout-payment-method-load button.action.checkout.primary', + successPageTitle: '.page-title', + successBlock: '.checkout-success', +}; + +/** + * Magento appends catalog/seo/product_url_suffix to a product's url key. The + * default is .html and this gate never changes it, so a spec that navigates + * straight to a product it just created can build the path itself instead of + * hunting for a link to it. + */ +export const productUrlSuffix = process.env.MAGENTO_PRODUCT_URL_SUFFIX ?? '.html'; + +/** The storefront path for a product url key, e.g. storefrontUrl('a-product'). */ +export function productUrl(urlKey: string): string { + return `/${urlKey}${productUrlSuffix}`; +} From dad990d864dee6f7b3d474be5a8b6500fe1dcf68 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:17:03 -0600 Subject: [PATCH 16/42] fix(e2e): fail when the store does not answer The reachability check reported a 404 and passed. It was curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 and a GitHub `run:` without `shell: bash` runs under `bash -e` with no `-o pipefail`, so the pipeline exited with head's status and discarded curl's. The one step whose entire job is to say "nothing was served" said the opposite, and nine specs then failed against a store that was never there -- which reads as a broken suite rather than a broken environment. The status is now captured and compared, so the step does not depend on pipefail being set to mean what it says. A failure diagnostics step comes with it. When this goes wrong the containers leave with the runner, and nothing in the log says whether nginx was up, whether Varnish had a backend, or whether Traefik had a route at all -- a Traefik 404 and a Magento 404 are indistinguishable from outside, and only one of them is about the store. --- .github/workflows/_internal-e2e.yaml | 49 +++++++++++++++++++++++++++- .github/workflows/e2e.yaml | 49 +++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 085e1648..aa92017f 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -105,10 +105,26 @@ jobs: # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. + # + # The status is captured and compared rather than piped into head. This + # step used to be `curl --fail ... | head -1`, which reported a 404 and + # passed anyway: a GitHub `run:` without `shell: bash` gets `bash -e` + # without `-o pipefail`, so the pipeline took head's exit status and + # discarded curl's. The whole point of the step is to be the one red that + # says "nothing was served", and for one run it was a green that said the + # opposite. - name: Confirm the store answers on the resolved hostname + shell: bash env: BASE_URL: ${{ steps.warden.outputs.base_url }} - run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 + run: | + STATUS="$(curl --silent --show-error --insecure --output /dev/null --write-out '%{http_code}' "$BASE_URL")" + echo "${BASE_URL} -> ${STATUS}" + + if [ "${STATUS}" != "200" ]; then + echo "::error::the store answered ${STATUS}, not 200 -- nothing below this ran against a working store" + exit 1 + fi # What the gate ran against, probed from the running stack rather than # echoed back from the inputs: a version input can be a constraint, the @@ -244,6 +260,37 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ env.ADMIN_FRONTNAME }} run: npx playwright test + # What the stack was doing when something went wrong. Without this, "the + # store answered 404" is where the investigation stops: the containers go + # away with the runner, and nothing in the log says whether nginx was up, + # whether Varnish had a backend at all, or whether Traefik had a route to + # send the request to. + # + # Nothing in here may fail the job -- it only runs because something else + # already did. + - name: Report what the stack was doing + if: failure() + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + echo "::group::containers" + ${WARDEN} env ps || true + echo "::endgroup::" + + for SERVICE in nginx varnish php-fpm; do + echo "::group::${SERVICE}" + ${WARDEN} env logs --tail=50 "${SERVICE}" || true + echo "::endgroup::" + done + + # A Traefik 404 and a Magento 404 look identical from the outside, and + # only one of them is about the store. + echo "::group::traefik" + ${WARDEN} svc logs --tail=50 traefik || true + echo "::endgroup::" + - name: Upload the Playwright report if: ${{ !cancelled() }} uses: actions/upload-artifact@v4 diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 00bc8b1b..dd94853a 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -205,10 +205,26 @@ jobs: # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. + # + # The status is captured and compared rather than piped into head. This + # step used to be `curl --fail ... | head -1`, which reported a 404 and + # passed anyway: a GitHub `run:` without `shell: bash` gets `bash -e` + # without `-o pipefail`, so the pipeline took head's exit status and + # discarded curl's. The whole point of the step is to be the one red that + # says "nothing was served", and for one run it was a green that said the + # opposite. - name: Confirm the store answers on the resolved hostname + shell: bash env: BASE_URL: ${{ steps.warden.outputs.base_url }} - run: curl --silent --show-error --fail --insecure --head "$BASE_URL" | head -1 + run: | + STATUS="$(curl --silent --show-error --insecure --output /dev/null --write-out '%{http_code}' "$BASE_URL")" + echo "${BASE_URL} -> ${STATUS}" + + if [ "${STATUS}" != "200" ]; then + echo "::error::the store answered ${STATUS}, not 200 -- nothing below this ran against a working store" + exit 1 + fi # What the gate ran against, probed from the running stack rather than # echoed back from the inputs: a version input can be a constraint, the @@ -350,6 +366,37 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ inputs.backend_frontname }} run: bash -c "$TEST_COMMAND" + # What the stack was doing when something went wrong. Without this, "the + # store answered 404" is where the investigation stops: the containers go + # away with the runner, and nothing in the log says whether nginx was up, + # whether Varnish had a backend at all, or whether Traefik had a route to + # send the request to. + # + # Nothing in here may fail the job -- it only runs because something else + # already did. + - name: Report what the stack was doing + if: failure() + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + echo "::group::containers" + ${WARDEN} env ps || true + echo "::endgroup::" + + for SERVICE in nginx varnish php-fpm; do + echo "::group::${SERVICE}" + ${WARDEN} env logs --tail=50 "${SERVICE}" || true + echo "::endgroup::" + done + + # A Traefik 404 and a Magento 404 look identical from the outside, and + # only one of them is about the store. + echo "::group::traefik" + ${WARDEN} svc logs --tail=50 traefik || true + echo "::endgroup::" + # A failing gate is read by someone deciding whether to ship, so the # evidence has to outlive the run. - name: Upload the test report From 97a55ef8d3388a4a7753230fad39d3a132d11af0 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:22:48 -0600 Subject: [PATCH 17/42] fix(warden): serve the environment through a Traefik the daemon talks to Every request to the store answered 404, with every container in the environment reporting healthy and bin/magento working fine inside them. The diagnostics step added alongside this says why: traefik | level=error msg="Failed to retrieve information of the docker client and server host: Error response from daemon: client version 1.24 is too old. Minimum supported API version is 1.40" Warden 0.14.2 pins traefik:2.2, whose Docker provider speaks API 1.24, and the Docker daemon on GitHub's current runner image refuses anything below 1.40. Traefik therefore reads no container labels, builds no routers, and returns its own 404 for every host -- which from outside is indistinguishable from a Magento 404, and from the install's point of view nothing is wrong at all. The image tag is a variable in the compose file Warden ships (traefik:${TRAEFIK_VERSION:-2.2}), so this sets it to 2.11, the tag Warden itself moved to, rather than bumping the pinned Warden version: 0.16 also changes where the certificates are mounted, which is a larger change than a broken proxy needs. --- warden/setup-environment/action.yml | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/warden/setup-environment/action.yml b/warden/setup-environment/action.yml index 275259f2..1cf40d1c 100644 --- a/warden/setup-environment/action.yml +++ b/warden/setup-environment/action.yml @@ -98,6 +98,17 @@ inputs: default: "app" description: "Traefik subdomain the environment is served on (TRAEFIK_SUBDOMAIN)." + traefik_version: + required: false + default: "2.11" + description: > + The Traefik image tag for the global Warden services (TRAEFIK_VERSION). + Warden 0.14.2 defaults this to 2.2, whose Docker provider speaks Docker + API 1.24. GitHub's runner image now ships a Docker daemon that refuses + anything below 1.40, so Traefik 2.2 cannot read container labels, builds + no routers, and answers 404 to every request -- while every container in + the environment reports healthy. 2.11 is the tag Warden itself moved to. + backend_frontname: required: false default: "admin" @@ -261,9 +272,16 @@ runs: - name: Warden svc up && Warden env up working-directory: ${{ inputs.base_directory }} shell: bash + env: + # Consumed by the docker-compose file Warden ships for its global + # services, which pins image: traefik:${TRAEFIK_VERSION:-2.2}. The + # default is too old to talk to the Docker daemon on a current GitHub + # runner; see the traefik_version input for what that failure looks + # like, because it does not look like a proxy problem. + TRAEFIK_VERSION: ${{ inputs.traefik_version }} run: | export WARDEN="$(dirname $(pwd))/warden/bin/warden" - ${WARDEN} svc up + ${WARDEN} svc up ${WARDEN} env up - name: Change Directory Permissions From d71abc5af4d0edea31f443e21bdba323c1bdd812 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:23:06 -0600 Subject: [PATCH 18/42] docs(warden): say what a 404 on every URL actually means The traefik_version input is only legible with the failure beside it: a proxy that cannot reach the Docker daemon reads, from outside, exactly like a Magento that cannot find a route. --- warden/setup-environment/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/warden/setup-environment/README.md b/warden/setup-environment/README.md index 77aaa131..13fb55c1 100644 --- a/warden/setup-environment/README.md +++ b/warden/setup-environment/README.md @@ -70,6 +70,7 @@ before one can reach the storefront, and all three are off by default: | `env_name` | `mageos` | `WARDEN_ENV_NAME`. | | `traefik_domain` | `mageos.test` | `TRAEFIK_DOMAIN`. | | `traefik_subdomain` | `app` | `TRAEFIK_SUBDOMAIN`. | +| `traefik_version` | `2.11` | `TRAEFIK_VERSION` for Warden's global services. Warden 0.14.2 defaults to `2.2`, which cannot talk to the Docker daemon on a current runner -- see below. | | `backend_frontname` | `admin` | Admin frontName passed to `setup:install`. | | `base_url` | *(empty)* | Passed as `--base-url` with `--use-rewrites=1`. Empty leaves Magento's default. | | `configure_host_resolution` | `0` | Resolve `<subdomain>.<domain>` to `127.0.0.1` on the runner. | @@ -77,6 +78,24 @@ before one can reach the storefront, and all three are off by default: | `static_content_languages` | `en_US` | Space separated locales to deploy. | | `static_content_themes` | *(empty)* | Space separated themes, e.g. `Magento/luma`. Empty deploys every theme. | +### Why `traefik_version` exists + +Warden 0.14.2 pins `traefik:${TRAEFIK_VERSION:-2.2}`, and Traefik 2.2's Docker +provider speaks Docker API 1.24. The Docker daemon on GitHub's current runner +image refuses anything below 1.40: + +``` +traefik | level=error msg="Failed to retrieve information of the docker client +and server host: Error response from daemon: client version 1.24 is too old. +Minimum supported API version is 1.40" +``` + +Traefik then reads no container labels, builds no routers, and answers **404 to +every request**. Nothing else looks wrong: every container is up, `bin/magento` +works inside them, and a Traefik 404 is indistinguishable from a Magento 404 +from outside. If a store answers 404 on every URL, check this before anything +in Magento. + ## Outputs | Name | Description | From afff1881834628ef471cbbca14be04098b63e64b Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:35:22 -0600 Subject: [PATCH 19/42] fix(e2e): save the product the spec says it saved Two findings from the first CI run of this spec, both in the save path. The sku was wrong in the store. Magento_Catalog/js/components/import-handler mirrors the name into sku, url_key and the meta fields through the masks in catalog/fields_masks, and stops only once a field has been edited by hand. The name field is configured valueUpdate: 'keyup', which Playwright's fill() does not emit, so the import runs on the name's change event -- which fires as focus leaves it, i.e. while the sku is being filled. The two interleaved and the store ended up with a sku of "<name><sku>": Mage-OS E2E Product 1794623536178mageos-e2e-1794623536178 Every assertion passed anyway, because the grid's sku filter is a LIKE and a contains assertion is satisfied by a superstring. So the spec reported that it had created a product it had not created. The name is now blurred before anything else is typed, the sku is filled last, and three assertions make the trap unable to return quietly: the field holds what was typed, the saved edit form reads it back, and the grid cell equals the sku rather than containing it. Verified against the database -- the row now reads mageos-e2e-<stamp> exactly. The save was also flaky in CI: it timed out at 20s on the first attempt and the retry passed in 10s end to end. The first product save on a freshly installed store in developer mode pays for code generation along the save path, then for the Update on Save indexers -- price, EAV, product categories, catalog search -- which is work this gate wants happening. So that one assertion gets 90s, and the test 180s. It waits for the success *or* the error message, which is what keeps a generous timeout honest: a save rejected by validation now fails in a second showing the message, instead of in ninety with "element(s) not found". --- .../Test/e2e/admin/create-product.spec.ts | 60 +++++++++++++++++-- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts index b768e647..983871b7 100644 --- a/_test/demo-package/Test/e2e/admin/create-product.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -32,9 +32,16 @@ const productForm = { urlKey: 'input[name="product[url_key]"]', save: '#save-button', saved: 'div[data-ui-id="messages-message-success"]', + // Either outcome of a save, so the spec can wait for whichever the store + // produces rather than only for the one it hopes for. + anyMessage: 'div[data-ui-id="messages-message-success"], div[data-ui-id="messages-message-error"]', }; test.describe('Creating a product in the admin', () => { + // Longer than the suite's 120s, because the save below can take most of a + // minute on its own; see the step for why. + test.setTimeout(180_000); + test('@admin creates a simple product and sells it', async ({ page }) => { // Inside the test, not at module scope, so that a retry gets its own // sku. The first attempt may well have saved the product before @@ -68,16 +75,35 @@ test.describe('Creating a product in the admin', () => { }); await test.step('the form accepts a simple product', async () => { + // The name first, and blurred before anything else is typed. + // + // Magento_Catalog/js/components/import-handler mirrors the name + // into sku, url_key and the meta fields through the masks in + // catalog/fields_masks, and stops only once the field has been + // edited by hand. The name field is configured with + // valueUpdate: 'keyup', which Playwright's fill() does not emit, + // so the import runs on the name's change event -- which fires + // when focus leaves it, i.e. while the sku is being filled. + // + // Fill the sku straight after the name and the two interleave: the + // store ends up with a sku of "<name><sku>". That passed every + // assertion in this spec for an afternoon, because the grid's sku + // filter is a LIKE and a contains assertion is satisfied by a + // superstring. Hence the blur, the sku last, and toHaveValue. await page.locator(productForm.name).fill(product.name); - // After the name, because the sku field auto-fills from it and - // would overwrite whatever was typed here first. - await page.locator(productForm.sku).fill(product.sku); + await page.locator(productForm.name).blur(); + await page.locator(productForm.price).fill(product.price); await page.locator(productForm.quantity).fill(product.quantity); // Set rather than assumed: the default is In Stock, but a product // that cannot be bought is the one failure this spec must not // mistake for a broken storefront. await page.locator(productForm.stockStatus).selectOption('1'); + + await page.locator(productForm.sku).fill(product.sku); + // The field holds exactly what was typed, nothing imported around + // it. Without this the spec cannot tell which product it made. + await expect(page.locator(productForm.sku)).toHaveValue(product.sku); }); await test.step('the url key is set explicitly', async () => { @@ -88,11 +114,29 @@ test.describe('Creating a product in the admin', () => { await page.locator(productForm.seoSection).click(); await expect(page.locator(productForm.urlKey)).toBeVisible(); await page.locator(productForm.urlKey).fill(product.urlKey); + // url_key is imported from the name by the same handler as sku, + // so it gets the same guard. + await expect(page.locator(productForm.urlKey)).toHaveValue(product.urlKey); }); await test.step('saving the product reports success', async () => { await page.locator(productForm.save).click(); + // Whichever message arrives, with a timeout far longer than the + // suite's 20s. This was flaky in CI exactly once and the shape of + // the flake is informative: the first attempt timed out here, and + // the retry passed in 10s end to end. The first product save on a + // freshly installed store in developer mode pays for the code + // generation along the save path, and then for the Update on Save + // indexers -- price, EAV, product categories, catalog search -- + // which is work this gate wants happening, not work to switch off. + // + // Waiting for either message rather than only the success one is + // what keeps the generous timeout honest: a save rejected by + // validation renders an error at the top of the page, and that + // should fail in a second with the message visible, not in ninety + // with "element(s) not found". + await expect(page.locator(productForm.anyMessage).first()).toBeVisible({ timeout: 90_000 }); await expect(page.locator(productForm.saved)).toContainText('You saved the product.'); // On the edit form for a product with an id: the save redirected // to a persisted entity rather than re-rendering the new form with @@ -100,6 +144,9 @@ test.describe('Creating a product in the admin', () => { await expect(page.locator('body')).toHaveClass(productForm.savedBodyClass); await expect(page).toHaveURL(/catalog\/product\/edit\/id\/\d+/); await expect(page.locator(adminSelectors.pageTitle)).toContainText(product.name); + // What was persisted, read back off the edit form: the sku the + // spec asked for, not one the form composed on its way past. + await expect(page.locator(productForm.sku)).toHaveValue(product.sku); }); await test.step('the grid finds the product by its sku', async () => { @@ -114,7 +161,12 @@ test.describe('Creating a product in the admin', () => { // is unique to this attempt, so anything else here means the grid // is showing rows that do not match its own filter. await expect.poll(() => grid.recordsFound()).toBe(1); - await expect(grid.rows.first()).toContainText(product.sku); + // The cell equals the sku rather than containing it. The filter is + // a LIKE, so a product whose sku merely ends with this one would + // satisfy a contains assertion -- which is exactly how a mangled + // sku passed this spec before. + const skuColumn = await grid.columnIndex('SKU'); + await expect(grid.column(skuColumn).first()).toHaveText(product.sku); // The grid remembers filters per admin user, so leaving this one // applied would change what every later run of the grid spec sees. From 9254c56900d5f3e80408a416f500c9037a9fb6bd Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Fri, 13 Nov 2026 20:44:18 -0600 Subject: [PATCH 20/42] fix(e2e): let the first product save take as long as it takes The ceiling of 90s was still not enough: in CI the first attempt ran 1.8 minutes and the retry passed in 14.9s. Three runs now put the first save a store ever performs at 12s, 17s and over 90s, with every retry at about 15s -- so the cost is the first save, not a slow runner. Four minutes, then, with the test at five. High enough that runner variance produces a slow pass rather than a red gate, and retries: 1 covers the rest. A failure on the retry as well would mean the save path itself regressed, which is what the gate is for. Waiting for the error message as well as the success one is what keeps a ceiling this generous honest: a validation failure still reports in about a second. --- _test/demo-package/Test/e2e/README.md | 16 +++++++++++ .../Test/e2e/admin/create-product.spec.ts | 27 +++++++++++-------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index d3d8b0ad..aa1fda36 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -112,6 +112,22 @@ generated inside the test rather than at module scope so that a retry does not collide with what the failed attempt already saved. Point this suite at a throwaway store, not a long-lived one. +### The first save a store ever performs is slow + +`admin/create-product.spec.ts` allows four minutes for the save to report +back, against the suite's usual twenty seconds. Across GitHub runners that +first save has taken 12s, 17s and over 90s, while every retry afterwards +lands in about 15s: a freshly installed store in developer mode pays for code +generation along the save path, and then for the Update on Save indexers -- +price, EAV, product categories, catalog search -- which is work this gate +wants happening rather than work to switch off. + +The ceiling is there so runner variance produces a slow pass instead of a red +gate. If the spec ever fails on its retry as well, the save path itself has +regressed, which is the thing worth reporting. The assertion waits for the +success **or** the error message, so a save rejected by validation still fails +in about a second, showing the message. + ### Traps in the admin UI components Each of these cost a red run to find, and none of them is visible in the diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts index 983871b7..633815d3 100644 --- a/_test/demo-package/Test/e2e/admin/create-product.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -38,9 +38,9 @@ const productForm = { }; test.describe('Creating a product in the admin', () => { - // Longer than the suite's 120s, because the save below can take most of a - // minute on its own; see the step for why. - test.setTimeout(180_000); + // Longer than the suite's 120s, because the save below can take minutes on + // its own the first time a store ever performs one; see the step for why. + test.setTimeout(300_000); test('@admin creates a simple product and sells it', async ({ page }) => { // Inside the test, not at module scope, so that a retry gets its own @@ -122,21 +122,26 @@ test.describe('Creating a product in the admin', () => { await test.step('saving the product reports success', async () => { await page.locator(productForm.save).click(); - // Whichever message arrives, with a timeout far longer than the - // suite's 20s. This was flaky in CI exactly once and the shape of - // the flake is informative: the first attempt timed out here, and - // the retry passed in 10s end to end. The first product save on a + // Whichever message arrives, with a ceiling far above the suite's + // 20s. The number is empirical, not a guess: across GitHub runners + // the *first* save a store ever performs has taken 12s, 17s and + // over 90s, while every retry afterwards lands in about 15s. A // freshly installed store in developer mode pays for the code // generation along the save path, and then for the Update on Save // indexers -- price, EAV, product categories, catalog search -- // which is work this gate wants happening, not work to switch off. // + // So the ceiling is high enough that runner variance produces a + // slow pass instead of a red gate, and retries: 1 covers the rest. + // If this ever fails on the retry too, the save path itself has + // regressed -- which is precisely what the gate exists to report. + // // Waiting for either message rather than only the success one is - // what keeps the generous timeout honest: a save rejected by + // what keeps a ceiling this generous honest: a save rejected by // validation renders an error at the top of the page, and that - // should fail in a second with the message visible, not in ninety - // with "element(s) not found". - await expect(page.locator(productForm.anyMessage).first()).toBeVisible({ timeout: 90_000 }); + // should fail in a second with the message visible rather than in + // minutes with "element(s) not found". + await expect(page.locator(productForm.anyMessage).first()).toBeVisible({ timeout: 240_000 }); await expect(page.locator(productForm.saved)).toContainText('You saved the product.'); // On the edit form for a product with an id: the save redirected // to a persisted entity rather than re-rendering the new form with From d53acbf5a446d79d71a7b0125e99b183cba8fa88 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sun, 15 Nov 2026 16:20:45 -0600 Subject: [PATCH 21/42] test(e2e): create a category and a customer in the admin The product spec covers one write path. These cover the two others a store is actually made of, and almost nothing is shared between them. The category spec drives the jstree sidebar, the category form and the legacy grid widget that assigns products, then asks the storefront for a url that did not exist a moment ago and for a menu entry that was cached without it. The customer spec covers a different entity type, the website and group assignment, and the repository the storefront reads through -- proved by registering the same address on the storefront and being refused. The customer spec deliberately never asserts on the customer grid. Customer::reindex() is a no-op while customer_grid is scheduled, which is its default, so on any store without cron a saved customer is absent from that grid. Asserting it would go red against a store that works. Both were verified by breaking them: a tampered url key fails on the 404, an unassigned category fails on an empty listing, and a fresh email fails the duplicate-address assertion rather than passing on any error at all. --- .github/workflows/e2e-README.md | 9 +- _test/demo-package/Test/e2e/README.md | 63 ++++- .../Test/e2e/admin/create-category.spec.ts | 220 ++++++++++++++++++ .../Test/e2e/admin/create-customer.spec.ts | 140 +++++++++++ _test/demo-package/Test/e2e/luma.ts | 27 +++ 5 files changed, 454 insertions(+), 5 deletions(-) create mode 100644 _test/demo-package/Test/e2e/admin/create-category.spec.ts create mode 100644 _test/demo-package/Test/e2e/admin/create-customer.spec.ts diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 1c1ed934..d929ff25 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -162,10 +162,11 @@ test_command: "npx playwright test --project=storefront" ``` An admin suite also **writes to the store**. The specs in this repository -create a product per run, and the admin grids remember their filters per admin -user in the `ui_bookmark` table. Both are fine against the throwaway store this -workflow installs, and neither is something to point at a store anyone cares -about. +create a product, a category and a customer per run, the category is assigned a +fixture product and appears in the storefront menu, and the admin grids +remember their filters per admin user in the `ui_bookmark` table. All of that +is fine against the throwaway store this workflow installs, and none of it is +something to point at a store anyone cares about. `Magento/backend` is in the `static_content_themes` default for the same reason: an admin spec against an undeployed admin theme waits for every asset diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index aa1fda36..a58ff95f 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -4,7 +4,8 @@ A small Playwright suite that proves a Mage-OS release is **being served**, **can take an order** and **can be administered** -- installed, reachable over HTTP(S), rendering with its static content deployed, able to carry a guest from a category listing to a persisted order, and able to let an administrator sign -in, work a grid and create a product that a shopper can then buy. +in, work a grid and create the catalog and customer records a store is +made of. It is the canary for [`warden/setup-environment`](../../../../warden/setup-environment): `.github/workflows/_internal-e2e.yaml` stands a store up with that action on @@ -17,6 +18,8 @@ every change to it and runs this suite against the result. | `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | | `admin/product-grid.spec.ts` | yes | the product grid renders through Magento_Ui and filters server-side | | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | +| `admin/create-category.spec.ts` | yes | category tree -> save -> url rewrite -> category index -> storefront listing + menu | +| `admin/create-customer.spec.ts` | no | customer form -> save -> read-back -> the storefront refuses the address twice | Storefront selectors live in `luma.ts`, shared by every spec that looks at a storefront page. A Hyva variant of this suite is that file with a different @@ -177,6 +180,64 @@ The create spec sets the url key explicitly rather than deriving it from the product name, so that the storefront step is a statement about url rewrites instead of a guess about how a name becomes a url. +**The two catalog forms spell the same section differently.** The product +form's SEO collapsible is `data-index="search-engine-optimization"`, with +hyphens. The category form's is `search_engine_optimization`, with underscores. +Same label on screen, two modules' `ui_component` XML underneath. + +**The category page is not a grid page.** `catalog/category/` opens the root +category's own edit form -- hence a `catalog-category-edit` body class on what +looks like an index -- with a jstree sidebar beside it. The new-subcategory +form is `catalog-category-add`. + +**Products are assigned to a category through a legacy grid widget**, not a UI +component listing. `#catalog_category_products_table` has its own filter row +that applies on **Enter**, row checkboxes with **no name attribute** (the value +is the product id), and no loading mask worth waiting on. `adminGrid()` does +not apply to it and should not be stretched to fit: it is a different thing +that happens to look similar. + +That grid is also where a filter race is easiest to write by accident. The +unfiltered table already has rows, so polling for "more than zero rows" is +satisfied by the table that was on screen *before* Enter was pressed. The +first version of the category spec read a product name off the stale table, +checked a box in the table that replaced it, and then reported that the +storefront had listed the wrong product. Poll for something only the filtered +grid can satisfy -- every SKU cell matching the filter -- and re-assert the +row's identity after checking its box. + +**The customer grid is the one grid a save does not update.** +`Magento\Customer\Model\Customer::reindex()` is a no-op while the +`customer_grid` indexer is scheduled, which is its default and which nothing +here changes: + +```php +public function reindex() +{ + if (!$this->getIndexer()->isScheduled()) { + $this->getIndexer()->reindexRow($this->getId()); + } +} +``` + +So on any store without cron running -- every CI store, including this gate's +-- a customer saved in the admin is simply absent from the customer grid. The +customer spec therefore proves persistence from the edit form and from the +storefront and never from the grid. An assertion on the grid there would be +red against a store that is working correctly, which is the worst kind of +assertion to put in front of someone deciding whether to ship. + +**A saved customer's form opens on a different tab than a new one's.** The new +form shows Account Information; after a save the page opens on Customer View, +a read-only summary, and the fields are not in the DOM until `#tab_customer` +is clicked. The spec uses **Save and Continue Edit** rather than Save, because +Save redirects to the grid -- see above for why that is a dead end. + +**The fixture profile's simple products start at `product_dynamic_2`.** There +is no `product_dynamic_1`. A spec that hardcodes the first index fails on a +correctly seeded store, so the category spec filters on the `product_dynamic` +prefix and reads the SKU and name it finds out of the DOM. + ### What makes the admin reachable at all Magento has **no configuration flag that switches two-factor authentication diff --git a/_test/demo-package/Test/e2e/admin/create-category.spec.ts b/_test/demo-package/Test/e2e/admin/create-category.spec.ts new file mode 100644 index 00000000..797432d6 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-category.spec.ts @@ -0,0 +1,220 @@ +import { expect, test } from '@playwright/test'; +import { adminSelectors, adminUrl } from './support'; +import { categoryUrl, luma } from '../luma'; + +/** + * A category is the other half of the catalog write path, and almost none of + * it is shared with the product form. + * + * The product form is a UI component form posting to a UI component data + * provider. The category page is a jstree sidebar driving a form whose product + * assignment is still a legacy grid widget, saving through a controller that + * writes the category tree, generates url rewrites for every store view and + * invalidates the catalog_category_product index. The storefront then has to + * resolve the new url, render a listing from that index and show the category + * in a navigation block that was cached before it existed. + * + * So this spec creates a subcategory of the root, assigns it a product, and + * then asks the storefront for a page that did not exist a moment ago and for + * a menu entry that was cached without it. + */ + +const categoryForm = { + // catalog/category/ is the tree page, and it opens on the root category's + // own edit form -- so the body class on what looks like an index is + // -edit. The admin names the action, and the action is editing. + treeBodyClass: /catalog-category-edit/, + formBodyClass: /catalog-category-add/, + savedBodyClass: /catalog-category-edit/, + tree: '.tree-holder', + treeNode: 'li.jstree-node > a', + addSubcategory: '#add_subcategory_button', + name: 'input[name="name"]', + isActive: 'input[name="is_active"]', + // Underscores, deliberately not a typo: the product form's equivalent + // section is data-index="search-engine-optimization" with hyphens. Same + // label in the UI, different spelling in the DOM, and the two forms are + // maintained by different modules' ui_component XML. + seoSection: "div[data-index='search_engine_optimization'] .fieldset-wrapper-title", + urlKey: "input[name='url_key']", + productsSection: "div[data-index='assign_products'] .fieldset-wrapper-title", + // A legacy grid widget, not a UI component listing: its own table id, its + // own filter row that applies on Enter, and row checkboxes with no name + // attribute. adminGrid() does not apply here and should not be stretched + // to; this grid is a different thing that happens to look similar. + productsTable: '#catalog_category_products_table', + productSkuFilter: 'input[name="sku"]', + save: '#save', + // Not div[data-ui-id="messages-message-success"]: the category page + // renders the plain admin message block. + saved: '.page-content .message-success', + anyMessage: '.page-content .message-success, .page-content .message-error', +}; + +test.describe('Creating a category in the admin', () => { + // As with the product spec: a category save on a cold store pays for code + // generation and then for the category/product and url rewrite indexers. + test.setTimeout(300_000); + + test('@admin creates a category and the storefront lists it', async ({ page }) => { + // Per attempt, not per module: a retry that collided with the url key + // its own first attempt saved would report "the url key already + // exists" instead of whatever actually went wrong. + const stamp = `${Date.now()}`; + const category = { + name: `Mage-OS E2E Category ${stamp}`, + urlKey: `mageos-e2e-category-${stamp}`, + }; + + await test.step('the admin offers a new subcategory form', async () => { + await page.goto(adminUrl('catalog/category/')); + + await expect(page.locator('body')).toHaveClass(categoryForm.treeBodyClass); + // The tree is rendered by jstree from a JSON payload, so a visible + // node is already a statement that the sidebar bootstrapped. + await expect(page.locator(categoryForm.tree)).toBeVisible(); + await expect(page.locator(categoryForm.treeNode).first()).toBeVisible(); + + // No id in the URL, so the page opens on the store's root + // category and Add Subcategory makes a child of it. That is the + // level the storefront navigation renders, which is what makes + // the menu assertion at the end of this spec possible. + await page.locator(categoryForm.addSubcategory).click(); + + await expect(page.locator('body')).toHaveClass(categoryForm.formBodyClass); + await expect(page).toHaveURL(/catalog\/category\/add\/store\/\d+\/parent\/\d+/); + await expect(page.locator(categoryForm.name)).toBeVisible(); + // Asserted rather than set. The default is enabled, and a + // disabled category answers 404 on the storefront -- so if this + // default ever changes, the failure should be this line and not a + // mystifying 404 three steps later. + await expect(page.locator(categoryForm.isActive)).toBeChecked(); + }); + + await test.step('the form accepts a name and a url key', async () => { + await page.locator(categoryForm.name).fill(category.name); + await expect(page.locator(categoryForm.name)).toHaveValue(category.name); + + // Collapsed on load and rendered lazily, like every other + // collapsible in the admin: the url key input is not in the DOM + // until the section is opened. + await page.locator(categoryForm.seoSection).click(); + await expect(page.locator(categoryForm.urlKey)).toBeVisible(); + await page.locator(categoryForm.urlKey).fill(category.urlKey); + await expect(page.locator(categoryForm.urlKey)).toHaveValue(category.urlKey); + }); + + let assignedProduct = ''; + + await test.step('a product is assigned to the category', async () => { + await page.locator(categoryForm.productsSection).click(); + + const grid = page.locator(categoryForm.productsTable); + await expect(grid).toBeVisible(); + + // Filtered to the fixture's simple products rather than taking + // whatever sorts first. The fixture also generates a configurable + // and its variations, and a variation is Not Visible Individually + // -- it would save here and then be absent from the storefront + // listing, which would read as a broken category page. + await grid.locator(categoryForm.productSkuFilter).fill('product_dynamic'); + await grid.locator(categoryForm.productSkuFilter).press('Enter'); + + // A legacy grid reloads over AJAX with no response this spec can + // reliably await, so the filtered state has to be polled for. + // + // Polling the row count is not enough, and getting that wrong is + // what this comment is for: the unfiltered grid already has rows, + // so "more than zero rows" is satisfied by the table that was on + // screen before Enter was pressed. The first attempt at this spec + // read a name off that stale table, then checked a box in the + // table that replaced it, and asserted on the storefront that the + // wrong product was listed. Poll for something only the filtered + // grid can satisfy instead. + const headers = (await grid.locator('thead th').allInnerTexts()).map((h) => h.trim()); + const nameColumn = headers.indexOf('Name'); + const skuColumn = headers.indexOf('SKU'); + expect(nameColumn, `the grid should have a Name column; it has ${headers}`).toBeGreaterThan(-1); + expect(skuColumn, `the grid should have a SKU column; it has ${headers}`).toBeGreaterThan(-1); + + await expect + .poll( + async () => { + const skus = await grid.locator(`tbody tr td:nth-child(${skuColumn + 1})`).allInnerTexts(); + return skus.length > 0 && skus.every((sku) => sku.includes('product_dynamic')); + }, + { + message: 'the grid should settle on the fixture products; seed the catalog first', + }, + ) + .toBe(true); + + const row = grid.locator('tbody tr').first(); + assignedProduct = (await row.locator('td').nth(nameColumn).innerText()).trim(); + expect(assignedProduct, 'the grid row should carry a product name').not.toBe(''); + + // No name attribute on these checkboxes -- the value is the + // product id and the id is id_<product id>. Scoped to the row + // rather than selected by name, which there is none of. + await row.locator('input[type="checkbox"]').check(); + await expect(row.locator('input[type="checkbox"]')).toBeChecked(); + // The row that is checked is still the row that was read. If the + // grid re-rendered between the two, this is where that shows up + // rather than in a storefront assertion three steps later. + await expect(row.locator('td').nth(nameColumn)).toHaveText(assignedProduct); + }); + + await test.step('saving the category reports success', async () => { + await page.locator(categoryForm.save).click(); + + // Either message, with the same generous ceiling and the same + // reasoning as the product spec: a validation error should fail + // this in a second with its text on screen, and a slow first + // save on a cold runner should pass slowly rather than go red. + await expect(page.locator(categoryForm.anyMessage).first()).toBeVisible({ timeout: 240_000 }); + await expect(page.locator(categoryForm.saved)).toContainText('You saved the category.'); + + // A persisted entity with an id, not the add form re-rendered + // with the values still in it. + await expect(page.locator('body')).toHaveClass(categoryForm.savedBodyClass); + await expect(page).toHaveURL(/catalog\/category\/edit\/id\/\d+/); + await expect(page.locator(adminSelectors.pageTitle)).toContainText(category.name); + // Read back off the saved form: what the store holds, not what + // the spec typed into a field. + await expect(page.locator(categoryForm.name)).toHaveValue(category.name); + }); + + await test.step('the storefront serves the category it has never seen', async () => { + // Straight to the url key. A url rewrite that was not generated + // for the new category is a 404 here, and that is the failure + // worth reporting rather than hiding behind navigation clicks. + const response = await page.goto(categoryUrl(category.urlKey)); + + expect(response?.status(), 'the url rewrite for a saved category should resolve').toBe(200); + await expect(page.locator('body')).toHaveClass(/catalog-category-view/); + await expect(page.locator(luma.pageTitle)).toContainText(category.name); + + // The listing renders from catalog_category_product, which the + // save had to invalidate and reindex. An empty category page + // returns 200 and looks fine, so this is the assertion that the + // index actually ran. + // Exactly one product, and it is the one that was assigned. A + // count assertion as well as an identity one, because a category + // that lists the whole catalog is also broken -- and that is what + // a misconfigured anchor or display mode looks like. + const listing = page.locator(luma.productList); + await expect(listing.locator(luma.productItemLink)).toHaveCount(1); + await expect(listing.locator(luma.productItemLink)).toHaveText(assignedProduct); + }); + + await test.step('the navigation includes the category', async () => { + // The top menu is a cached block, and it was cached before this + // category existed. Saving a category has to invalidate it, which + // is a seam nothing else in this suite touches: a stale menu is a + // merchant-visible bug that no amount of product testing finds. + await expect( + page.locator(luma.navCategory).filter({ hasText: category.name }), + ).toHaveCount(1); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts new file mode 100644 index 00000000..1f12e88e --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -0,0 +1,140 @@ +import { expect, test } from '@playwright/test'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +import { luma } from '../luma'; + +/** + * Creating a customer exercises a write path the product and category specs + * do not touch: a different entity type, a different form, the website and + * group assignment, and the customer repository that the storefront reads + * through on every registration and login. + * + * It also documents the one grid in the admin that a save does not update. + * Magento\Customer\Model\Customer::reindex() is a no-op when the customer_grid + * indexer is scheduled, which it is by default and which it stays by default: + * + * public function reindex() + * { + * if (!$this->getIndexer()->isScheduled()) { + * $this->getIndexer()->reindexRow($this->getId()); + * } + * } + * + * So on a store without cron running -- every CI store, including this gate's + * -- a customer saved in the admin is absent from the customer grid until + * something indexes it. This spec therefore asserts persistence from the edit + * form and from the storefront, and never from the grid. An assertion on the + * grid would be red against a correctly working store, which is the worst + * kind of test to put in front of someone deciding whether to ship. + */ + +const customerForm = { + gridBodyClass: /customer-index-index/, + // Not customer-index-new. The new-customer form is rendered by the edit + // action, so a new customer and an existing one share a body class, and + // this spec identifies the form by its title and its fields instead. + formBodyClass: /customer-index-edit/, + addCustomer: '#add', + firstName: "input[name='customer[firstname]']", + lastName: "input[name='customer[lastname]']", + email: "input[name='customer[email]']", + // The saved customer's form opens on Customer View, a read-only summary. + // The fields are under Account Information, which is a separate tab and a + // separate render -- the new-customer form shows them without a click, a + // saved one does not. + accountTab: '#tab_customer', + group: "select[name='customer[group_id]']", + website: "select[name='customer[website_id]']", + // Save and Continue Edit rather than Save Customer: Save redirects to the + // grid, and the grid is the one place this customer will not be. Save and + // Continue lands on the persisted entity, which is where the read-back + // below has to happen. + save: "button[title='Save and Continue Edit']", + saved: '.page-content .message-success', + anyMessage: '.page-content .message-success, .page-content .message-error', +}; + +test.describe('Creating a customer in the admin', () => { + test.setTimeout(300_000); + + test('@admin creates a customer the storefront knows about', async ({ page }) => { + const stamp = `${Date.now()}`; + const customer = { + firstName: 'Mage-OS', + lastName: `E2E ${stamp}`, + email: `mageos-e2e-${stamp}@example.test`, + }; + + await test.step('the customer grid renders', async () => { + await page.goto(adminUrl('customer/index/index')); + + await expect(page.locator('body')).toHaveClass(customerForm.gridBodyClass); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('Customers'); + + // A second UI component listing, which is most of the point of + // asserting it at all: product_listing working says little about + // whether customer_listing's own columns and data provider do. + // No assertion on the row count -- the fixture profile creates no + // customers, so an empty grid here is correct. + const grid = adminGrid(page, 'customer_listing'); + await grid.ready(); + expect(await grid.columnIndex('Email')).toBeGreaterThanOrEqual(0); + }); + + await test.step('the admin offers a new customer form', async () => { + await page.locator(customerForm.addCustomer).click(); + + await expect(page.locator('body')).toHaveClass(customerForm.formBodyClass); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('New Customer'); + await expect(page.locator(customerForm.firstName)).toBeVisible(); + await expect(page.locator(customerForm.lastName)).toBeVisible(); + await expect(page.locator(customerForm.email)).toBeVisible(); + + // Left at their defaults, but asserted to have one. These two + // selects are populated by the form's data provider, and an empty + // website select is a bootstrapped form that nonetheless cannot + // save -- a failure that otherwise surfaces as an unhelpful + // validation error further down. + await expect(page.locator(customerForm.website)).not.toHaveValue(''); + await expect(page.locator(customerForm.group)).not.toHaveValue(''); + }); + + await test.step('saving the customer reports success', async () => { + await page.locator(customerForm.firstName).fill(customer.firstName); + await page.locator(customerForm.lastName).fill(customer.lastName); + await page.locator(customerForm.email).fill(customer.email); + + await page.locator(customerForm.save).click(); + + await expect(page.locator(customerForm.anyMessage).first()).toBeVisible({ timeout: 240_000 }); + await expect(page.locator(customerForm.saved)).toContainText('You saved the customer.'); + await expect(page).toHaveURL(/customer\/index\/edit\/id\/\d+/); + + // What the store holds, read off the form it redirected to. + await page.locator(customerForm.accountTab).click(); + await expect(page.locator(customerForm.email)).toHaveValue(customer.email); + await expect(page.locator(customerForm.firstName)).toHaveValue(customer.firstName); + }); + + await test.step('the storefront knows the account exists', async () => { + // The loop closure, and the reason this spec does not end at the + // admin: registering the same address on the storefront has to be + // refused. That answer comes from the customer repository looking + // the address up within the website the admin form assigned, so a + // customer saved to the wrong website -- or not committed at all + // -- registers happily here and the spec goes red. + await page.goto('/customer/account/create/'); + await expect(page.locator(luma.registerForm)).toBeVisible(); + + await page.locator(luma.registerFirstName).fill(customer.firstName); + await page.locator(luma.registerLastName).fill(customer.lastName); + await page.locator(luma.registerEmail).fill(customer.email); + await page.locator(luma.registerPassword).fill('mageos-E2E-1!'); + await page.locator(luma.registerPasswordConfirm).fill('mageos-E2E-1!'); + await page.locator(luma.registerSubmit).click(); + + await expect(page.locator(luma.errorMessage)).toContainText( + 'There is already an account with this email address', + ); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/luma.ts b/_test/demo-package/Test/e2e/luma.ts index 159d90df..accceab1 100644 --- a/_test/demo-package/Test/e2e/luma.ts +++ b/_test/demo-package/Test/e2e/luma.ts @@ -8,6 +8,10 @@ */ export const luma = { navCategory: '.navigation li.level0 > a', + // The category/search listing wrapper. Scoping to it matters: Luma's + // sidebar blocks render product items too, so an unscoped product-item + // count on a category page counts things that are not in the category. + productList: '.products.wrapper', productItem: '.product-item-info', productItemLink: 'a.product-item-link', pageTitle: '.page-title', @@ -28,6 +32,18 @@ export const luma = { placeOrder: '#checkout-payment-method-load button.action.checkout.primary', successPageTitle: '.page-title', successBlock: '.checkout-success', + + // Account registration. Luma's own form, so it belongs in Luma's map: + // firstname and lastname come from a shared name fieldset template, which + // is why their ids carry no prefix while the email field's does. + registerForm: '#form-validate', + registerFirstName: '#firstname', + registerLastName: '#lastname', + registerEmail: '#email_address', + registerPassword: '#password', + registerPasswordConfirm: '#password-confirmation', + registerSubmit: '#form-validate button[type="submit"]', + errorMessage: '.message-error', }; /** @@ -42,3 +58,14 @@ export const productUrlSuffix = process.env.MAGENTO_PRODUCT_URL_SUFFIX ?? '.html export function productUrl(urlKey: string): string { return `/${urlKey}${productUrlSuffix}`; } + +export const categoryUrlSuffix = process.env.MAGENTO_CATEGORY_URL_SUFFIX ?? '.html'; + +/** + * Separate from productUrl because Magento configures the two suffixes + * separately -- catalog/seo/category_url_suffix and product_url_suffix -- and + * a store that changed one and not the other is a perfectly ordinary store. + */ +export function categoryUrl(urlKey: string): string { + return `/${urlKey}${categoryUrlSuffix}`; +} From 99d27916d24de6f1fe32bd5fc4ebe21b0a1ff905 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sun, 15 Nov 2026 17:37:03 -0600 Subject: [PATCH 22/42] test(e2e): fail a spec when the page logs an error nothing asserts on A failed XHR breaks no assertion. Magento_Ui renders a listing from its client-side page cache and keeps the last good state when a request fails, so a grid whose data provider returns 500 goes on showing the rows it already had -- measured: a 500 on mui/index/render left the row count unchanged at 20, raised no pageerror, and the grid spec passed. Private content behaves the same way. That is the half of a page no assertion in this suite can see, and it is most of what a Magento page does after it renders. fixtures.ts watches pageerror, console errors and any response at or above 400, and fails the test with the status, method and URL. Specs import test and expect from it rather than from @playwright/test. Committed strict only after a report-only run of all eleven specs, which produced exactly one recurring finding: guest-carts/<id>/totals answering 404 some 460ms after payment-information returned 200, because the checkout refreshes totals for a quote the place-order call has already consumed. The ignore list is that one entry, scoped to that path and that status, plus the browser's URL-less "Failed to load resource" echo of what the response listener already reports properly. Demonstrated red by 404ing a background XHR no assertion mentions: the spec passes every assertion it makes and then fails on the fixture. --- _test/demo-package/Test/e2e/README.md | 50 ++++++++ .../Test/e2e/admin/create-category.spec.ts | 2 +- .../Test/e2e/admin/create-customer.spec.ts | 2 +- .../Test/e2e/admin/create-product.spec.ts | 2 +- .../demo-package/Test/e2e/admin/login.spec.ts | 2 +- .../Test/e2e/admin/product-grid.spec.ts | 2 +- .../Test/e2e/admin/session.setup.ts | 2 +- _test/demo-package/Test/e2e/fixtures.ts | 117 ++++++++++++++++++ .../Test/e2e/guest-checkout.spec.ts | 3 +- .../Test/e2e/hello-magento.spec.ts | 2 +- 10 files changed, 176 insertions(+), 8 deletions(-) create mode 100644 _test/demo-package/Test/e2e/fixtures.ts diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index a58ff95f..4f708781 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -280,6 +280,56 @@ if a future release does grow a blocking dialog on first sign-in, the right outcome is a red test with a screenshot of it, not a suite that dismisses it and reports green. +## Every page is watched for errors nothing asserts on + +`fixtures.ts` replaces Playwright's `page` fixture with one that watches three +things and fails the test if any of them fires. Specs import `test` and +`expect` from it instead of from `@playwright/test`, and get the check for +free on every page they touch. + +| Signal | Catches | +| --- | --- | +| `pageerror` | an uncaught JS exception -- a missing requirejs module, a mixin that no longer resolves, a knockout binding against a property that moved | +| `console` (errors) | anything the store's own code logged as an error | +| `response` (>= 400) | any failed request, including the ones no assertion looks at | + +The third one is the reason this exists. **A failed XHR breaks no assertion.** +`Magento_Ui` renders a listing from its client-side page cache and keeps the +last good state when a request fails, so a grid whose data provider returns +500 goes on showing the rows it already had. Measured on Mage-OS 4.0.0: a 500 +on `mui/index/render` left the row count unchanged at 20, raised no +`pageerror`, and `product-grid.spec.ts` -- which asserts `rows > 1` -- passed. +Private content behaves the same way: a 500 on `customer/section/load` leaves +the minicart showing whatever `localStorage` last held. + +A 500 or 404 on the *main document* usually does fail a spec, because the +content it asserts on is not there, and two specs check `response.status()` +outright. The gap is everything requested in the background, which is most of +what a Magento page does after it renders. + +It was committed strict only after a report-only run of the whole suite. +Eleven specs produced exactly one recurring finding: `GET +/guest-carts/<id>/totals` answering 404 about 460ms after +`payment-information` returned 200. The checkout refreshes the cart totals +after the order is placed, by which point the quote it is asking about has +been consumed -- the shopper is on the success page and nothing is broken. +That is the single entry in the ignore list, scoped to that path and that +status so it cannot hide a cart that 404s while a shopper is still trying to +check out. + +The browser's own `Failed to load resource` console line is also ignored, for +a different reason: it is a URL-less echo of something the response listener +already reports with a status, a method and a full URL. Keeping both counts +every HTTP finding twice and the duplicate is the less useful of the two. + +**Keep that ignore list short.** A check like this is only as good as its +ignore list, and a growing list is how such a check quietly dies. Anything new +is a finding until someone proves otherwise, in a comment, in the file. + +Demonstrated red the same way as everything else here: 404 a background XHR +that no assertion mentions -- `js-translation.json` will do -- and the spec +passes every one of its own assertions and then fails on the fixture. + ## Why the assertions look like that A `200` is not evidence of a storefront. The admin login page, a CMS no-route diff --git a/_test/demo-package/Test/e2e/admin/create-category.spec.ts b/_test/demo-package/Test/e2e/admin/create-category.spec.ts index 797432d6..f457cd2c 100644 --- a/_test/demo-package/Test/e2e/admin/create-category.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-category.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test } from '../fixtures'; import { adminSelectors, adminUrl } from './support'; import { categoryUrl, luma } from '../luma'; diff --git a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts index 1f12e88e..cdbf5790 100644 --- a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; import { luma } from '../luma'; diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts index 633815d3..a1a19400 100644 --- a/_test/demo-package/Test/e2e/admin/create-product.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; import { luma, productUrl } from '../luma'; diff --git a/_test/demo-package/Test/e2e/admin/login.spec.ts b/_test/demo-package/Test/e2e/admin/login.spec.ts index 6124386e..099dda0b 100644 --- a/_test/demo-package/Test/e2e/admin/login.spec.ts +++ b/_test/demo-package/Test/e2e/admin/login.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test } from '../fixtures'; import { admin, adminSelectors, adminUrl, signIn } from './support'; // These specs are about the sign-in form itself, so they start with no session diff --git a/_test/demo-package/Test/e2e/admin/product-grid.spec.ts b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts index dc8a49a2..8e58a423 100644 --- a/_test/demo-package/Test/e2e/admin/product-grid.spec.ts +++ b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; /** diff --git a/_test/demo-package/Test/e2e/admin/session.setup.ts b/_test/demo-package/Test/e2e/admin/session.setup.ts index 55503444..3ec7a217 100644 --- a/_test/demo-package/Test/e2e/admin/session.setup.ts +++ b/_test/demo-package/Test/e2e/admin/session.setup.ts @@ -1,4 +1,4 @@ -import { expect, test as setup } from '@playwright/test'; +import { expect, test as setup } from '../fixtures'; import { admin, adminSelectors, adminStateFile, signIn } from './support'; /** diff --git a/_test/demo-package/Test/e2e/fixtures.ts b/_test/demo-package/Test/e2e/fixtures.ts new file mode 100644 index 00000000..66aa14f2 --- /dev/null +++ b/_test/demo-package/Test/e2e/fixtures.ts @@ -0,0 +1,117 @@ +import { test as base, expect } from '@playwright/test'; +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * Every spec's page, watched for the failures assertions cannot see. + * + * Three signals, each catching something the other two do not: + * + * pageerror an uncaught JS exception. Knockout gives up on a binding, a + * requirejs module is missing, a mixin no longer resolves. The + * page renders, the screenshot is perfect, every assertion + * passes, and the button does nothing. + * console the browser's own report of a failed subresource, and anything + * the store's own code logged as an error. + * response any response at or above 400. This is the one that matters + * most, because a failed *XHR* breaks no assertion: Magento_Ui + * renders a listing from its client-side page cache and keeps + * the last good state, so a grid whose data provider returns + * 500 goes on showing the rows it already had. Measured: a 500 + * on mui/index/render leaves the row count unchanged and raises + * no pageerror at all. + * + * Findings fail the test, and are also attached to the report and written to + * test-results/js-errors.jsonl so a red run says what happened without + * anyone opening a trace. + * + * This was committed strict only after a report-only run of the whole suite: + * eleven specs produced exactly one recurring finding, the post-order totals + * refresh documented below. A check like this is only as good as its ignore + * list, and a growing ignore list is how such a check dies -- so every entry + * has to earn its comment, and anything new is a finding until proven + * otherwise. + */ + +/** + * Console messages that are not findings. + * + * The browser's own "Failed to load resource" line is a URL-less echo of + * something the response listener below already reports with a status, a + * method and the full URL. Keeping both means every HTTP finding is counted + * twice, and the duplicate is the less informative of the two. + */ +const ignoredConsole: RegExp[] = [/^Failed to load resource/]; + +/** + * HTTP responses that are not findings. One entry, and it has to stay this + * narrow. + * + * Magento's checkout refreshes the cart totals after the order is placed. + * Measured on Mage-OS 4.0.0: payment-information returns 200 at T, and + * GET /guest-carts/<id>/totals returns 404 at T+460ms, because the quote the + * place-order call just consumed is no longer an active guest cart. The + * shopper is on the success page by then and nothing is broken. + * + * Scoped to that one path and that one status rather than to 404s, or to + * /rest/ 404s, so it cannot hide a cart that 404s while the shopper is still + * trying to check out. That failure would also break the spec's own + * assertions -- totals would not render and the order would not be placed -- + * which is what makes an ignore this narrow safe to carry. + */ +const ignoredHttp: RegExp[] = [/^404 GET xhr \/rest\/\S+\/guest-carts\/\w+\/totals/]; + +const logFile = path.resolve(__dirname, 'test-results/js-errors.jsonl'); + +type Finding = { kind: 'pageerror' | 'console' | 'http'; detail: string; where: string }; + +export const test = base.extend({ + page: async ({ page }, use, testInfo) => { + const findings: Finding[] = []; + + page.on('pageerror', (error) => { + findings.push({ kind: 'pageerror', detail: error.message.split('\n')[0], where: page.url() }); + }); + + page.on('console', (message) => { + if (message.type() !== 'error') return; + const text = message.text(); + if (ignoredConsole.some((pattern) => pattern.test(text))) return; + findings.push({ kind: 'console', detail: text.slice(0, 200), where: page.url() }); + }); + + page.on('response', (response) => { + if (response.status() < 400) return; + const request = response.request(); + const detail = `${response.status()} ${request.method()} ${request.resourceType()}`; + const path = response.url().replace(/^https?:\/\/[^/]+/, ''); + if (ignoredHttp.some((pattern) => pattern.test(`${detail} ${path}`))) return; + findings.push({ kind: 'http', detail, where: response.url() }); + }); + + await use(page); + + if (findings.length > 0) { + testInfo.annotations.push({ + type: 'js-errors', + description: findings.map((f) => `${f.kind}: ${f.detail}\n ${f.where}`).join('\n'), + }); + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.appendFileSync( + logFile, + findings + .map((f) => JSON.stringify({ test: testInfo.titlePath.filter(Boolean).join(' > '), ...f })) + .join('\n') + '\n', + ); + } + + // A page that renders correctly and still logs an error is a release + // failure this suite would otherwise report as a pass. + expect( + findings.map((f) => `${f.kind}: ${f.detail} <- ${f.where}`), + 'the page should not have logged a JavaScript error or a failed request', + ).toEqual([]); + }, +}); + +export { expect }; diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/guest-checkout.spec.ts index 895475f5..a45d2c3d 100644 --- a/_test/demo-package/Test/e2e/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/guest-checkout.spec.ts @@ -1,4 +1,5 @@ -import { test, expect, type Page } from '@playwright/test'; +import { type Page } from '@playwright/test'; +import { expect, test } from './fixtures'; import { luma } from './luma'; // The deepest path a storefront check can walk: catalog -> product -> cart -> diff --git a/_test/demo-package/Test/e2e/hello-magento.spec.ts b/_test/demo-package/Test/e2e/hello-magento.spec.ts index 5de89855..e57e856a 100644 --- a/_test/demo-package/Test/e2e/hello-magento.spec.ts +++ b/_test/demo-package/Test/e2e/hello-magento.spec.ts @@ -1,4 +1,4 @@ -import { test, expect } from '@playwright/test'; +import { expect, test } from './fixtures'; // A 200 proves very little on its own: the admin login page, a CMS no-route // page and a Magento error page all answer 200 and all carry a header, a From aeb3c1686b8b9e2b4642a9c164b6d68ba4429c18 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sun, 15 Nov 2026 18:50:25 -0600 Subject: [PATCH 23/42] fix(warden): let Magento invalidate the Varnish in front of it setup:install is already told where to purge whenever a Varnish service is requested (--http-cache-hosts=varnish:80), but Magento's page cache defaults to its own built-in implementation and the purge only fires when the configured type is Varnish: if ((int)$this->config->getType() === Config::VARNISH && ...) So a Warden environment serves every request through a Varnish that Magento never invalidates. Save a product and the category page keeps the copy it already had. This is quiet rather than loud, which is what makes it worth fixing before anything trips over it: a suite whose specs each visit a URL once never notices, because there is no stale copy to serve. The first spec that changes something and looks at the same page again fails, and reads as a Magento bug rather than as an environment that was never told which cache it has. New varnish_as_page_cache input, off by default so existing callers keep the behaviour they have, and set in both e2e workflows. It installs no VCL -- Warden's Varnish image ships a Magento-compatible one. The stack summary now also records which side owns the page cache and what the homepage's Cache-Control, Age and X-Magento-Cache-Debug headers say, so the answer is a line in the report instead of a reading of the source. --- .github/workflows/_internal-e2e.yaml | 27 ++++++++++++++++ .github/workflows/e2e-README.md | 9 ++++++ .github/workflows/e2e.yaml | 27 ++++++++++++++++ warden/setup-environment/README.md | 37 ++++++++++++++++++++++ warden/setup-environment/action.yml | 46 ++++++++++++++++++++++++++++ 5 files changed, 146 insertions(+) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index aa92017f..4fb84ef0 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -90,6 +90,7 @@ jobs: run_setup_install: 1 run_admin_user_creation: 1 run_magento_config_preset: 1 + varnish_as_page_cache: 1 run_reindex: 1 traefik_domain: ${{ env.TRAEFIK_DOMAIN }} traefik_subdomain: ${{ env.TRAEFIK_SUBDOMAIN }} @@ -138,6 +139,8 @@ jobs: id: stack working-directory: ./_ghamagento shell: bash + env: + BASE_URL: ${{ steps.warden.outputs.base_url }} run: | export WARDEN="$(dirname $(pwd))/warden/bin/warden" # Stderr is captured too: varnishd -V writes its version there. @@ -154,6 +157,26 @@ jobs: REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" + # Which side owns the page cache, and whether it is actually caching. + # + # Magento defaults to its own built-in cache, and only purges Varnish + # when it is configured as the cache. A Varnish serving every request + # that Magento never invalidates passes every spec here today -- each + # one visits a given URL once -- and fails the first spec that + # revisits a page after changing it, in a way that reads like a + # Magento bug. So the run says it outright rather than leaving it to + # be re-derived from the source every time. + FPC="$(probe php-fpm bin/magento config:show system/full_page_cache/caching_application | head -1)" + case "${FPC}" in + 2) FPC="Varnish" ;; + 1) FPC="Magento built-in" ;; + *) FPC="Magento built-in (unset)" ;; + esac + HEADERS="$(curl --silent --show-error --insecure --head "${BASE_URL}" 2>&1 | tr -d '\r' || true)" + AGE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Aa]ge: *//p' | head -1)" + XCACHE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Xx]-[Mm]agento-[Cc]ache-[Dd]ebug: *//p' | head -1)" + CACHECONTROL="$(printf '%s' "${HEADERS}" | sed -n 's/^[Cc]ache-[Cc]ontrol: *//p' | head -1)" + # Only the application versions reach the tests. A spec may reasonably # branch on those; none should branch on a Redis patch level. echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT @@ -171,6 +194,10 @@ jobs: echo "| Search | ${SEARCH:-unknown} |" echo "| Redis | ${REDIS:-unknown} |" echo "| Varnish | ${VARNISH:-unknown} |" + echo "| Page cache owner | ${FPC} |" + echo "| Homepage \`Cache-Control\` | ${CACHECONTROL:-none} |" + echo "| Homepage \`Age\` | ${AGE:-none} |" + echo "| Homepage \`X-Magento-Cache-Debug\` | ${XCACHE:-none} |" } >> $GITHUB_STEP_SUMMARY # Magento has no switch for two-factor authentication. There is no enable diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index d929ff25..2d9f8c75 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -168,6 +168,15 @@ remember their filters per admin user in the `ui_bookmark` table. All of that is fine against the throwaway store this workflow installs, and none of it is something to point at a store anyone cares about. +The store is installed with **Varnish owning the page cache** +(`varnish_as_page_cache: 1`). Magento's default is its own built-in cache, +which would leave a Varnish in front of it that Magento never purges -- and +a gate that cannot invalidate its page cache is not testing the store anyone +ships. The run summary records which side owns the cache and what the +homepage's `Cache-Control`, `Age` and `X-Magento-Cache-Debug` headers say, so +that is a line in the report rather than something to re-derive from the +source. + `Magento/backend` is in the `static_content_themes` default for the same reason: an admin spec against an undeployed admin theme waits for every asset to be generated on demand, and reads as a timeout rather than as a missing diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index dd94853a..55dced5f 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -194,6 +194,7 @@ jobs: run_setup_install: 1 run_admin_user_creation: 1 run_magento_config_preset: 1 + varnish_as_page_cache: 1 run_reindex: 1 traefik_domain: ${{ env.TRAEFIK_DOMAIN }} traefik_subdomain: ${{ env.TRAEFIK_SUBDOMAIN }} @@ -238,6 +239,8 @@ jobs: id: stack working-directory: ./_ghamagento shell: bash + env: + BASE_URL: ${{ steps.warden.outputs.base_url }} run: | export WARDEN="$(dirname $(pwd))/warden/bin/warden" # Stderr is captured too: varnishd -V writes its version there. @@ -254,6 +257,26 @@ jobs: REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" + # Which side owns the page cache, and whether it is actually caching. + # + # Magento defaults to its own built-in cache, and only purges Varnish + # when it is configured as the cache. A Varnish serving every request + # that Magento never invalidates passes every spec here today -- each + # one visits a given URL once -- and fails the first spec that + # revisits a page after changing it, in a way that reads like a + # Magento bug. So the run says it outright rather than leaving it to + # be re-derived from the source every time. + FPC="$(probe php-fpm bin/magento config:show system/full_page_cache/caching_application | head -1)" + case "${FPC}" in + 2) FPC="Varnish" ;; + 1) FPC="Magento built-in" ;; + *) FPC="Magento built-in (unset)" ;; + esac + HEADERS="$(curl --silent --show-error --insecure --head "${BASE_URL}" 2>&1 | tr -d '\r' || true)" + AGE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Aa]ge: *//p' | head -1)" + XCACHE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Xx]-[Mm]agento-[Cc]ache-[Dd]ebug: *//p' | head -1)" + CACHECONTROL="$(printf '%s' "${HEADERS}" | sed -n 's/^[Cc]ache-[Cc]ontrol: *//p' | head -1)" + # Only the application versions reach the tests. A spec may reasonably # branch on those; none should branch on a Redis patch level. echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT @@ -271,6 +294,10 @@ jobs: echo "| Search | ${SEARCH:-unknown} |" echo "| Redis | ${REDIS:-unknown} |" echo "| Varnish | ${VARNISH:-unknown} |" + echo "| Page cache owner | ${FPC} |" + echo "| Homepage \`Cache-Control\` | ${CACHECONTROL:-none} |" + echo "| Homepage \`Age\` | ${AGE:-none} |" + echo "| Homepage \`X-Magento-Cache-Debug\` | ${XCACHE:-none} |" } >> $GITHUB_STEP_SUMMARY # A bare setup:install has nothing to buy. The command reindexes itself. diff --git a/warden/setup-environment/README.md b/warden/setup-environment/README.md index 13fb55c1..8ce84c9c 100644 --- a/warden/setup-environment/README.md +++ b/warden/setup-environment/README.md @@ -57,6 +57,7 @@ before one can reach the storefront, and all three are off by default: | `database` | `mariadb:10.6` | `distribution:version` of the database. | | `search` | `opensearch:2.5` | Search engine; `elasticsearch:*` or `opensearch:*`. | | `varnish` | `varnish:7.3` | Varnish version, or `null` to disable. | +| `varnish_as_page_cache` | `0` | Tell Magento the Varnish in front of it is its page cache. Ignored without a Varnish service -- see below. | | `rabbitmq` | `rabbitmq:3.11` | RabbitMQ version, or `null` to disable. | | `redis` | `redis:7.0` | Redis version, or `null` to disable. | | `base_directory` | `./` | Base directory of the Mage-OS codebase. | @@ -78,6 +79,42 @@ before one can reach the storefront, and all three are off by default: | `static_content_languages` | `en_US` | Space separated locales to deploy. | | `static_content_themes` | *(empty)* | Space separated themes, e.g. `Magento/luma`. Empty deploys every theme. | +### Why `varnish_as_page_cache` exists + +`setup:install` is already told where to purge whenever a Varnish service is +requested: + + --http-cache-hosts=varnish:80 + +but that is only half of it. Magento's page cache defaults to its own +built-in implementation, and the purge is sent only when the configured type +is Varnish: + +```php +// Magento\CacheInvalidate\Observer\InvalidateVarnishObserver +if ((int)$this->config->getType() === Config::VARNISH && $this->config->isEnabled()) { + … $this->purgeCache->sendPurgeRequest(array_unique($tags)); +} +``` + +So by default a Warden environment serves every request through a Varnish +that Magento never invalidates. Save a product and the category page keeps +the copy it already had, for the lifetime of the cached object. + +This is quiet rather than loud. A suite whose specs each visit a URL once +never notices -- there is no stale copy to serve. The first spec that changes +something and looks at the same page again fails, and reads as a Magento bug +rather than as an environment that was never told which cache it has. + +Setting this to `1` sets `system/full_page_cache/caching_application` to `2` +and flushes. It installs no VCL: Warden's Varnish image ships a +Magento-compatible one. + +Off by default so existing callers keep the behaviour they have. Browser +suites should turn it on -- a store whose page cache cannot be invalidated is +not a store anyone ships, and cache invalidation is a thing Magento releases +break. + ### Why `traefik_version` exists Warden 0.14.2 pins `traefik:${TRAEFIK_VERSION:-2.2}`, and Traefik 2.2's Docker diff --git a/warden/setup-environment/action.yml b/warden/setup-environment/action.yml index 1cf40d1c..30d6ea36 100644 --- a/warden/setup-environment/action.yml +++ b/warden/setup-environment/action.yml @@ -78,6 +78,33 @@ inputs: default: "0" description: "Whether to run admin user creation or not." + varnish_as_page_cache: + required: false + default: "0" + description: > + Whether to tell Magento that the Varnish service in front of it is its + full page cache (system/full_page_cache/caching_application = 2). + + Ignored when no Varnish service is requested. + + This does not install a VCL -- Warden's Varnish image ships a + Magento-compatible one. What it changes is which side owns the page + cache. Magento defaults to its own built-in cache, and + Magento\CacheInvalidate\Observer\InvalidateVarnishObserver only sends + a PURGE when the configured type is VARNISH: + + if ((int)$this->config->getType() === Config::VARNISH && ...) + + So with the default, a Varnish that serves every request is a Varnish + Magento never invalidates: save a product and the category page keeps + the copy it already had. setup:install is already told where to purge + (--http-cache-hosts=varnish:80, set below whenever Varnish is present); + this is the other half of that. + + Off by default so that existing callers keep the behaviour they have. + Browser-based suites want it on: a store whose page cache cannot be + invalidated is not the store anyone ships. + base_directory: required: true default: "./" @@ -451,6 +478,25 @@ runs: echo "Skipping magento config preset" fi + # Deliberately not folded into the preset above: that preset is a single + # switch over seven unrelated settings, two of which weaken admin + # security, and "serve the page cache the way production does" should not + # arrive bundled with those. + - name: Own the page cache with Varnish + if: inputs.varnish_as_page_cache == '1' && inputs.varnish != 'null' && inputs.varnish != '' + working-directory: ${{ inputs.base_directory }} + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + # --lock-env, like the web/secure settings above: this belongs to the + # environment, not to something a test or an admin can change out from + # under the suite. + ${WARDEN} env exec -T php-fpm bin/magento config:set --lock-env system/full_page_cache/caching_application 2 + # The pages cached before the switch were cached by the other cache. + ${WARDEN} env exec -T php-fpm bin/magento cache:flush + + echo "full page cache: $(${WARDEN} env exec -T php-fpm bin/magento config:show system/full_page_cache/caching_application | tr -d '\r')" + - name: Run Magento Setup Upgrade working-directory: ${{ inputs.base_directory }} shell: bash From 0b9b1b1cd29b62a8f2bfcfb4c70f22d296cf1048 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sun, 15 Nov 2026 18:58:43 -0600 Subject: [PATCH 24/42] test(e2e): do not flake on an aborted view transition The first rehearsal with Varnish owning the page cache reported a finding the local runs never produced: Chrome aborting a cross-document view transition in flight on a category and a product page, first attempt only, retry clean. Transition was aborted because of invalid state. ViewTransition opt-in disabled Mage-OS enables those transitions by default -- MageOS_ThemeOptimization renders @view-transition { navigation: auto; } on every storefront page and system/view_transitions/enable defaults to 1 -- and under automation the navigations arrive faster than a person's. Ignored, narrowly, because a gate that reports a flake is a gate people learn to re-run. Still worth reporting upstream: the module's own source notes that some in-app browsers never finish the transition and leave the page blank, so the feature has failure modes a cosmetic label does not cover. Any other uncaught exception, including any other view-transition failure, remains a finding. --- _test/demo-package/Test/e2e/README.md | 11 +++++++++ _test/demo-package/Test/e2e/fixtures.ts | 31 ++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 4f708781..0dacb6fd 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -317,6 +317,17 @@ That is the single entry in the ignore list, scoped to that path and that status so it cannot hide a cart that 404s while a shopper is still trying to check out. +A third entry was added after the first rehearsal with Varnish owning the +page cache: Mage-OS enables cross-document view transitions by default +(`MageOS_ThemeOptimization`, `system/view_transitions/enable` = 1), and under +automation Chrome intermittently aborts one in flight with `Transition was +aborted because of invalid state. ViewTransition opt-in disabled`. It showed +up on a category and a product page, first attempt only, retry clean. That is +a cosmetic transition aborting, not a broken store -- but it is worth an +upstream report rather than only an ignore entry, because the module's own +source notes that some in-app browsers never finish the transition and leave +the page blank. + The browser's own `Failed to load resource` console line is also ignored, for a different reason: it is a URL-less echo of something the response listener already reports with a status, a method and a full URL. Keeping both counts diff --git a/_test/demo-package/Test/e2e/fixtures.ts b/_test/demo-package/Test/e2e/fixtures.ts index 66aa14f2..149d06f5 100644 --- a/_test/demo-package/Test/e2e/fixtures.ts +++ b/_test/demo-package/Test/e2e/fixtures.ts @@ -43,6 +43,33 @@ import path from 'node:path'; */ const ignoredConsole: RegExp[] = [/^Failed to load resource/]; +/** + * Uncaught exceptions that are not findings. One entry, and it is a judgement + * call rather than an obviously benign one, so it is written out in full. + * + * Mage-OS enables cross-document view transitions by default -- + * MageOS_ThemeOptimization renders `@view-transition { navigation: auto; }` + * on every storefront page, with system/view_transitions/enable defaulting + * to 1. Under automation the navigations come faster than a person's, and + * Chrome intermittently aborts the transition in flight: + * + * Transition was aborted because of invalid state. + * ViewTransition opt-in disabled + * + * Seen in CI on category and product pages, on the first attempt only, with + * the retry clean. It is the abort of a cosmetic transition, not a broken + * store, and the shopper sees a rendered page either way. + * + * It is ignored rather than fixed here because a gate that reports a flake is + * a gate people learn to re-run, which costs more than this error does. It is + * still worth an upstream report: the module's own source notes that some + * in-app browsers "never finish" the transition and leave the page blank, so + * this feature has failure modes that a cosmetic label does not cover. + * Narrow on purpose -- any other uncaught exception, including any other + * view-transition failure, is still a finding. + */ +const ignoredPageErrors: RegExp[] = [/^Transition was aborted because of invalid state\./]; + /** * HTTP responses that are not findings. One entry, and it has to stay this * narrow. @@ -70,7 +97,9 @@ export const test = base.extend({ const findings: Finding[] = []; page.on('pageerror', (error) => { - findings.push({ kind: 'pageerror', detail: error.message.split('\n')[0], where: page.url() }); + const detail = error.message.split('\n')[0]; + if (ignoredPageErrors.some((pattern) => pattern.test(detail))) return; + findings.push({ kind: 'pageerror', detail, where: page.url() }); }); page.on('console', (message) => { From 418b2ddedfa89252be6cef677c0216ee92ee77f3 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 16 Nov 2026 12:48:31 -0600 Subject: [PATCH 25/42] test(e2e): reach the product grid through the admin's own link Every admin spec here navigates by bare route, which only works while admin/security/use_form_key -- "Add Secret Key to URLs", not the POST form key -- is off. module-store/etc/config.xml ships it as 1, and with it on AbstractAction::_processUrlKeys answers a keyless admin GET with _redirect($this->_backendUrl->getStartupPageUrl()): a 302 to a 200 on the dashboard, which no failed-request check can see. So the suite's admin coverage currently depends entirely on a setting a merchant's store does not have. This spec is the hedge. It reads the Catalog > Products href out of the menu Magento rendered -- Block\Menu renders the whole tree server-side, Block\AnchorRenderer emits <a href="{$menuItem->getUrl()}">, so the key is already in it -- and follows that. It passes with the setting either way, and it is the pattern the other admin specs would adopt to drop the setting entirely. Measured, with the setting at 1 on a running store: menu-navigation.spec.ts passed product-grid.spec.ts both tests failed at adminGrid().ready() Which way the store was configured is recorded as an annotation rather than asserted, so a report says what the run proved. It also makes an assertion nothing else here can: every other navigation is a relative path, so this is the only place the suite reads a URL the store generated. An admin building links on the wrong host or scheme fails here and nowhere else. --- .../Test/e2e/admin/menu-navigation.spec.ts | 114 ++++++++++++++++++ _test/demo-package/Test/e2e/admin/support.ts | 6 + 2 files changed, 120 insertions(+) create mode 100644 _test/demo-package/Test/e2e/admin/menu-navigation.spec.ts diff --git a/_test/demo-package/Test/e2e/admin/menu-navigation.spec.ts b/_test/demo-package/Test/e2e/admin/menu-navigation.spec.ts new file mode 100644 index 00000000..5ceb3c0c --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/menu-navigation.spec.ts @@ -0,0 +1,114 @@ +import { expect, test } from '../fixtures'; +import { adminGrid, adminSelectors, adminUrl } from './support'; + +/** + * The one admin spec that does not navigate by URL, and the hedge against the + * config the rest of them need. + * + * `admin/security/use_form_key` is "Add Secret Key to URLs" -- not the POST + * form key, which is validated regardless -- and + * `module-store/etc/config.xml` ships it as `1`. With it on, every admin GET + * URL carries a `/key/<hash>/` segment, and a request without one is answered + * by `AbstractAction::_processUrlKeys` with + * `_redirect($this->_backendUrl->getStartupPageUrl())`: a 302 to a 200 on the + * dashboard. Nothing about that looks like a failure. The suite's other admin + * specs navigate by bare route, so the workflow turns the setting off for + * them, which means they only ever exercise a store configured the way a + * merchant's is not. + * + * This spec navigates the way the setting requires instead: it reads the href + * the admin rendered and follows that. It passes with secret keys on or off, + * so it is the one admin spec that would still hold against a stock store -- + * and the pattern the others would adopt to drop the setting entirely. + * + * It also makes an assertion no other spec can. Every other navigation here is + * a relative path, so the suite never looks at a URL the store generated. This + * one does, and a store building admin links on the wrong host or scheme -- + * `web/secure/base_url`, `web/secure/use_in_adminhtml` -- fails here and + * nowhere else. + */ + +const catalogMenu = { + // The li class comes from the menu id: module-catalog/etc/adminhtml/menu.xml + // declares Magento_Catalog::catalog_products, and Block\Menu turns the part + // after the :: into item-catalog-products. The anchor itself is rendered by + // Block\AnchorRenderer as <a href="{$menuItem->getUrl()}">, server-side, + // for the whole tree -- so the href is readable without opening anything. + productsItem: `${adminSelectors.menu} li.item-catalog-products > a`, + productsRoute: /\/catalog\/product\//, + // Encryptor::getHash, so sha256 hex. Matched only to report which mode the + // store was in, never to require one. + secretKey: /\/key\/[0-9a-f]{16,}\//, + grid: { + bodyClass: /catalog-product-index/, + component: 'product_listing', + }, +}; + +test.describe('Admin menu navigation', () => { + test('@admin reaches the product grid through the links the admin renders', async ({ page }, testInfo) => { + await test.step('the dashboard renders the admin menu', async () => { + // A bare GET to the admin root is safe under either setting: it is + // the startup page, so it is also where a rejected request would + // have been sent. + await page.goto(adminUrl()); + + await expect(page.locator('body')).toHaveClass(adminSelectors.dashboardBodyClass); + }); + + let href = ''; + + await test.step('the menu carries a link to the product grid', async () => { + const link = page.locator(catalogMenu.productsItem); + + // Exactly one: the menu is rendered once, and a duplicate would + // mean every locator in every admin spec is ambiguous. + await expect(link).toHaveCount(1); + + // Attached rather than visible. Products sits two levels down -- + // Catalog > Inventory > Products -- so it is inside a submenu that + // nothing has opened, and on a narrow viewport its whole column can + // sit behind the menu's own overflow handling. The href is in the + // DOM either way, and getAttribute does not need an element to be + // on screen. + await link.waitFor({ state: 'attached' }); + href = (await link.getAttribute('href')) ?? ''; + + expect(href, 'the Catalog > Products menu item should carry a URL').toMatch( + catalogMenu.productsRoute, + ); + + // The store generated this URL. If it names another host or + // another scheme than the one the browser is already on, then + // every link in the admin is wrong, and following it below would + // either fail to resolve or leave the session behind. + expect(new URL(href).origin, 'the admin should link to the host it is served on').toBe( + new URL(page.url()).origin, + ); + + // Which mode the store was in, recorded rather than required, so + // the report says what this run actually proved. + testInfo.annotations.push({ + type: 'admin-url-secret-key', + description: catalogMenu.secretKey.test(href) ? 'present' : 'absent', + }); + }); + + await test.step('following that link lands on the product grid', async () => { + const response = await page.goto(href); + + expect(response?.status(), `the admin should serve ${href}`).toBe(200); + + // The body class, not the URL: a rejected secret key answers 200 + // on the dashboard, and that is precisely the failure this spec + // exists to be able to see. + await expect(page.locator('body')).toHaveClass(catalogMenu.grid.bodyClass); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('Products'); + + // And the page is the grid, not just the right controller: the + // component has to have rendered for the navigation to be worth + // anything to a merchant. + await adminGrid(page, catalogMenu.grid.component).ready(); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/support.ts b/_test/demo-package/Test/e2e/admin/support.ts index 286ff071..6f0ef5f3 100644 --- a/_test/demo-package/Test/e2e/admin/support.ts +++ b/_test/demo-package/Test/e2e/admin/support.ts @@ -13,6 +13,12 @@ export const admin = { // navigate straight to an admin route instead of clicking through menus, // which is the difference between an admin suite that is maintainable and // one that breaks whenever the menu is reordered. + // + // It is not free, though: a bare admin route is only served while + // admin/security/use_form_key is off, and a stock store ships it on. See + // admin/menu-navigation.spec.ts, which navigates the way that setting + // requires, and the step in .github/workflows/e2e.yaml that turns it off + // for everything else here. frontname: process.env.MAGENTO_ADMIN_FRONTNAME ?? 'admin', }; From 68ec68b6fdee5987bded5aac0299265d1f312c17 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 16 Nov 2026 12:48:41 -0600 Subject: [PATCH 26/42] ci(e2e): say which store config the gate needs, and why The e2e workflows asked warden/setup-environment for run_magento_config_preset: 1 -- one boolean over seven config:set calls, two of which move the store away from what it ships as. A gate that does that should say so where the gate is defined. The two workflows now set what they need themselves, after the action: the web/secure pair, admin/security/use_form_key, account sharing and the WYSIWYG setting, each with the reason next to it. web/seo/use_rewrites is dropped -- setup:install already passes --use-rewrites=1 whenever it is given a base URL, which these workflows always do. Values are otherwise unchanged, so this is the same store, described. The suite README was wrong about one of them, in a paragraph telling people what not to copy out of the fixture profile: it called admin/security/use_form_key admin CSRF protection. It is not. Magento\Backend\Model\Url names that path XML_PATH_USE_SECURE_KEY and the admin labels it "Add Secret Key to URLs"; _processUrlKeys validates the POST form key regardless of it. The README now states what the setting does, what it costs this suite to turn it off, and what the measured consequence of turning it on is. Also drops a duplicated web/secure/use_in_frontend from the preset in the action, which set the same value twice. --- .github/workflows/_internal-e2e.yaml | 54 ++++++++++++++++++- .github/workflows/e2e.yaml | 54 ++++++++++++++++++- _test/demo-package/Test/e2e/README.md | 78 +++++++++++++++++++++++++-- warden/setup-environment/action.yml | 1 - 4 files changed, 181 insertions(+), 6 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 4fb84ef0..78f956ed 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -89,7 +89,6 @@ jobs: run_composer_install: 1 run_setup_install: 1 run_admin_user_creation: 1 - run_magento_config_preset: 1 varnish_as_page_cache: 1 run_reindex: 1 traefik_domain: ${{ env.TRAEFIK_DOMAIN }} @@ -104,6 +103,59 @@ jobs: # demand, which reads as a timeout rather than as a missing deploy. static_content_themes: "Magento/luma Magento/backend" + # What run_magento_config_preset used to do, written out. Same values the + # action applies behind that boolean, minus web/seo/use_rewrites: with a + # base URL given, setup:install already passed --use-rewrites=1. + # + # Spelled out here because one of these moves the store away from what it + # ships as, and a gate that does that should say so where the gate is + # defined rather than inside a boolean named after a preset. The preset + # also carries settings this suite has no use for. + # + # Applied after the action rather than inside it, so the config cache is + # already holding the old values -- hence the flush at the end. + - name: Configure the store the suite assumes + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + magento() { ${WARDEN} env exec -T php-fpm bin/magento "$@"; } + + # The browser speaks https to Traefik, so the store has to build https + # links on both sides. --lock-env, because this belongs to the + # environment and not to anything a test should be able to change. + magento config:set --lock-env web/secure/use_in_frontend 1 + magento config:set --lock-env web/secure/use_in_adminhtml 1 + + # "Add Secret Key to URLs" -- Magento\Backend\Model\Url names this + # same path XML_PATH_USE_SECURE_KEY. It is not the POST form key: + # AbstractAction::_processUrlKeys validates that for every logged-in + # POST whatever this is set to, so admin CSRF protection stays on + # either way. What the setting adds is a /key/<hash>/ segment on admin + # GET URLs, and module-store/etc/config.xml ships it as 1. + # + # With it on, a GET to a bare admin route is answered with a redirect + # to the dashboard: a 302 to a 200, which no failed-request check can + # see. Every admin spec here navigates by bare route, so this is off + # until they navigate by the links the admin renders instead -- + # admin/menu-navigation.spec.ts is the first one that does. + magento config:set admin/security/use_form_key 0 + + # Off, a login terminates the account's other sessions + # (Security\Model\AdminSessionsManager), and this suite shares one + # admin account across a saved storageState. Upstream's own integration + # suite sets it for the same reason, in + # dev/tests/integration/etc/config-global.php.dist. + magento config:set admin/security/admin_account_sharing 1 + + # Inherited from the preset, and a hole: the product and category + # description fields ship with TinyMCE, so the gate never loads the + # editor the admin actually renders. Enabling it belongs in its own + # change with its own run, because it is likely to find something. + magento config:set cms/wysiwyg/enabled disabled + + magento cache:flush + # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. # diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 55dced5f..d06685f2 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -193,7 +193,6 @@ jobs: run_composer_install: 1 run_setup_install: 1 run_admin_user_creation: 1 - run_magento_config_preset: 1 varnish_as_page_cache: 1 run_reindex: 1 traefik_domain: ${{ env.TRAEFIK_DOMAIN }} @@ -204,6 +203,59 @@ jobs: run_static_content_deploy: 1 static_content_themes: ${{ inputs.static_content_themes }} + # What run_magento_config_preset used to do, written out. Same values the + # action applies behind that boolean, minus web/seo/use_rewrites: with a + # base URL given, setup:install already passed --use-rewrites=1. + # + # Spelled out here because one of these moves the store away from what it + # ships as, and a gate that does that should say so where the gate is + # defined rather than inside a boolean named after a preset. The preset + # also carries settings this suite has no use for. + # + # Applied after the action rather than inside it, so the config cache is + # already holding the old values -- hence the flush at the end. + - name: Configure the store the suite assumes + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + magento() { ${WARDEN} env exec -T php-fpm bin/magento "$@"; } + + # The browser speaks https to Traefik, so the store has to build https + # links on both sides. --lock-env, because this belongs to the + # environment and not to anything a test should be able to change. + magento config:set --lock-env web/secure/use_in_frontend 1 + magento config:set --lock-env web/secure/use_in_adminhtml 1 + + # "Add Secret Key to URLs" -- Magento\Backend\Model\Url names this + # same path XML_PATH_USE_SECURE_KEY. It is not the POST form key: + # AbstractAction::_processUrlKeys validates that for every logged-in + # POST whatever this is set to, so admin CSRF protection stays on + # either way. What the setting adds is a /key/<hash>/ segment on admin + # GET URLs, and module-store/etc/config.xml ships it as 1. + # + # With it on, a GET to a bare admin route is answered with a redirect + # to the dashboard: a 302 to a 200, which no failed-request check can + # see. Every admin spec here navigates by bare route, so this is off + # until they navigate by the links the admin renders instead -- + # admin/menu-navigation.spec.ts is the first one that does. + magento config:set admin/security/use_form_key 0 + + # Off, a login terminates the account's other sessions + # (Security\Model\AdminSessionsManager), and this suite shares one + # admin account across a saved storageState. Upstream's own integration + # suite sets it for the same reason, in + # dev/tests/integration/etc/config-global.php.dist. + magento config:set admin/security/admin_account_sharing 1 + + # Inherited from the preset, and a hole: the product and category + # description fields ship with TinyMCE, so the gate never loads the + # editor the admin actually renders. Enabling it belongs in its own + # change with its own run, because it is likely to find something. + magento config:set cms/wysiwyg/enabled disabled + + magento cache:flush + # Separate from the test run so that "the store was never reachable" and # "the store rendered the wrong thing" are different red steps. # diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 0dacb6fd..5ae2dfa3 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -20,6 +20,7 @@ every change to it and runs this suite against the result. | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | | `admin/create-category.spec.ts` | yes | category tree -> save -> url rewrite -> category index -> storefront listing + menu | | `admin/create-customer.spec.ts` | no | customer form -> save -> read-back -> the storefront refuses the address twice | +| `admin/menu-navigation.spec.ts` | no | the admin's own rendered link reaches the product grid, secret key or not | Storefront selectors live in `luma.ts`, shared by every spec that looks at a storefront page. A Hyva variant of this suite is that file with a different @@ -280,6 +281,45 @@ if a future release does grow a blocking dialog on first sign-in, the right outcome is a red test with a screenshot of it, not a suite that dismisses it and reports green. +### Secret keys in admin URLs, and the one spec that survives them + +`admin/security/use_form_key` is **Add Secret Key to URLs**, not the POST form +key -- `Magento\Backend\Model\Url` names the same path +`XML_PATH_USE_SECURE_KEY`. `module-store/etc/config.xml` ships it as `1`, so a +stock store appends a `/key/<hash>/` segment to every admin GET URL and +`AbstractAction::_processUrlKeys` answers a request without one with +`_redirect($this->_backendUrl->getStartupPageUrl())`. + +That redirect is the problem. It is a 302 to a **200 on the dashboard**: no +error, no 4xx, nothing the error watching above can see. The only thing that +catches it is an assertion about which page you are on. + +Measured, by setting it to `1` on a store and running: + +| Spec | Navigates by | Result | +| --- | --- | --- | +| `admin/menu-navigation.spec.ts` | the href the admin rendered | passed | +| `admin/product-grid.spec.ts` | a bare admin route | both tests failed | + +The grid specs fail at `adminGrid().ready()` -- "waiting for +`table.data-grid`" -- because they are on the dashboard, which has no grid. +That is the body-class assertions doing their job, and it is also what every +admin spec here would do against a store configured the way stores ship. + +So `.github/workflows/e2e.yaml` sets the value to `0` itself, in a step that +explains it, and this is the gap that buys. `admin/menu-navigation.spec.ts` +exists so the gap is not total: it reads `Catalog > Products` out of the menu +Magento rendered and follows that, which works with the setting either way. It +records which way the store was configured as an annotation -- +`admin-url-secret-key: present` or `absent` -- so a report says what it +proved. It is also the only spec that looks at a URL the **store** generated +rather than a path the suite wrote, which makes it the only one that can fail +when admin links are built on the wrong host or scheme. + +Making the other admin specs navigate that way would let the setting go +entirely. The cost is the usual one: a menu is reordered more often than a +route is renamed. + ## Every page is watched for errors nothing asserts on `fixtures.ts` replaces Playwright's `page` fixture with one that watches three @@ -435,9 +475,41 @@ renamed is a gate people switch off. ### Two things to know about the profile `small.xml` sets `admin/security/use_form_key` to `0` and -`admin_account_sharing` to `1`. Reasonable for load testing, wrong here: a gate -running against a store with admin CSRF protection disabled is not testing the -store we ship. Do not copy those over. +`admin_account_sharing` to `1`. Both are worth understanding rather than +copying, and the first one is not what its name suggests. + +`admin/security/use_form_key` is **Add Secret Key to URLs**: +`Magento\Backend\Model\Url` names the same path `XML_PATH_USE_SECURE_KEY`. It +is not the POST form key, which is validated whatever this is set to -- +`Magento\Backend\App\AbstractAction::_processUrlKeys`: + +```php +if ($this->getRequest()->isPost()) { + $_isValidFormKey = $this->_formKeyValidator->validate($this->getRequest()); +} elseif ($this->_backendUrl->useSecretKey()) { + $_isValidSecretKey = $this->_validateSecretKey(); +} +``` + +So neither setting turns off admin CSRF protection. What the secret key does is +append a `/key/<hash>/` segment to admin GET URLs, and +`module-store/etc/config.xml` ships it as `1` -- on, in a stock store. With it +on, a GET to a bare admin route is answered with `_redirect($this->_backendUrl +->getStartupPageUrl())`: a 302 to a 200 on the dashboard, which no +failed-request check can see, and which only a body-class or URL assertion +catches. + +Every admin spec here except `admin/menu-navigation.spec.ts` navigates by bare +route, so `.github/workflows/e2e.yaml` sets this to `0` itself, in a step that +says why. That is a real gap between the gate and a stock store, and the way to +close it is to navigate the admin by the links the admin renders -- which is +what that one spec exists to prove is possible. + +`admin_account_sharing` at `1` is what upstream's own integration suite sets, +in `dev/tests/integration/etc/config-global.php.dist`. With it off, a login +terminates the account's other sessions +(`Magento\Security\Model\AdminSessionsManager`), and this suite shares one +admin account across a saved `storageState`. `ConfigsApplyFixture` iterates `$configs['config']` as a list, but a single `<config>` element collapses to a flat map, so the fixture iterates that diff --git a/warden/setup-environment/action.yml b/warden/setup-environment/action.yml index 30d6ea36..c9a03097 100644 --- a/warden/setup-environment/action.yml +++ b/warden/setup-environment/action.yml @@ -469,7 +469,6 @@ runs: export WARDEN="$(dirname $(pwd))/warden/bin/warden" ${WARDEN} env exec -T php-fpm bin/magento config:set --lock-env web/secure/use_in_adminhtml 1 ${WARDEN} env exec -T php-fpm bin/magento config:set --lock-env web/secure/use_in_frontend 1 - ${WARDEN} env exec -T php-fpm bin/magento config:set --lock-env web/secure/use_in_frontend 1 ${WARDEN} env exec -T php-fpm bin/magento config:set cms/wysiwyg/enabled disabled ${WARDEN} env exec -T php-fpm bin/magento config:set admin/security/admin_account_sharing 1 ${WARDEN} env exec -T php-fpm bin/magento config:set admin/security/use_form_key 0 From 3506626d7a56f4b2fa6d2518f782ef3c41994f9d Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 16 Nov 2026 13:02:20 -0600 Subject: [PATCH 27/42] fix(e2e): deploy the admin theme Mage-OS actually renders static_content_themes named Magento/backend, which is the parent of the theme the admin runs in: mage-os/theme-adminhtml-m137 registers MageOS/m137-admin-theme, and that is what the admin asks for. The child was never deployed, so Magento materialised it on the first request -- and while it did, the browser's request for the stylesheet was answered with Magento's HTML 404 page. Run 43932819737 is where it surfaced: the error-watching fixture failed the admin session setup with Refused to apply style from '.../MageOS/m137-admin-theme/en_US/css/ styles.css' because its MIME type ('text/html') is not a supported stylesheet first attempt only, clean on retry. So the admin has been rendering unstyled on the first page load of every run so far, and no assertion in the suite has anything to say about CSS. Both admin themes are deployed, the parent included. Naming a theme a store does not have is harmless: nothing validates the list up front, Deploy\Strategy\StandardDeploy::canDeployTheme walks the registered themes and checks each against it, so an unmatched name deploys nothing and fails nothing. That is what lets one default serve a Mage-OS and a Magento caller. --- .github/workflows/_internal-e2e.yaml | 16 ++++++++++++---- .github/workflows/e2e.yaml | 18 ++++++++++++++++-- _test/demo-package/Test/e2e/README.md | 17 +++++++++++++++++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 78f956ed..3cbde4f5 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -98,10 +98,18 @@ jobs: configure_host_resolution: 1 backend_frontname: ${{ env.ADMIN_FRONTNAME }} run_static_content_deploy: 1 - # Magento/backend as well as the storefront theme: the admin specs - # would otherwise have to wait for every asset to be generated on - # demand, which reads as a timeout rather than as a missing deploy. - static_content_themes: "Magento/luma Magento/backend" + # The admin themes as well as the storefront one: the admin specs would + # otherwise wait for every asset to be generated on demand, which reads + # as a timeout, or as an unstyled page, rather than as a missing deploy. + # + # Both admin themes, because Mage-OS does not render the admin in + # Magento/backend. mage-os/theme-adminhtml-m137 registers + # MageOS/m137-admin-theme, and deploying only the parent left the child + # to be materialised on the first request: run 43932819737 answered the + # login page's own stylesheet with Magento's HTML 404 while it built it, + # and the browser reported "Refused to apply style ... MIME type + # ('text/html')" -- a flaky red on the admin session setup. + static_content_themes: "Magento/luma Magento/backend MageOS/m137-admin-theme" # What run_magento_config_preset used to do, written out. Same values the # action applies behind that boolean, minus web/seo/use_rewrites: with a diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index d06685f2..203b68dd 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -58,8 +58,22 @@ on: static_content_themes: required: false type: string - default: "Magento/luma Magento/backend" - description: "Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. Magento/backend is in the default because an admin spec against an undeployed admin theme reads as a timeout rather than as a missing deploy." + default: "Magento/luma Magento/backend MageOS/m137-admin-theme" + description: > + Space separated themes to deploy static content for. Empty deploys + every theme, which is considerably slower. + + The admin themes are in the default because an admin spec against an + undeployed admin theme reads as a timeout, or as an unstyled page, + rather than as a missing deploy. Both of them, because Mage-OS does + not render the admin in Magento/backend: mage-os/theme-adminhtml-m137 + registers MageOS/m137-admin-theme and that is what the admin asks for. + + Naming a theme the store does not have is harmless. Nothing validates + this list up front -- Deploy\Strategy\StandardDeploy::canDeployTheme + walks the themes that are registered and checks each against it -- so + an unmatched name deploys nothing and fails nothing, which is what + lets one default cover Mage-OS and Magento. backend_frontname: required: false type: string diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 5ae2dfa3..e296223c 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -368,6 +368,23 @@ upstream report rather than only an ignore entry, because the module's own source notes that some in-app browsers never finish the transition and leave the page blank. +Not everything it finds becomes an ignore entry. The rehearsal that added +`admin/menu-navigation.spec.ts` came back with one finding on the admin +sign-in page: `Refused to apply style from +'.../adminhtml/MageOS/m137-admin-theme/en_US/css/styles.css' because its MIME +type ('text/html') is not a supported stylesheet`. The workflow was deploying +static content for `Magento/backend`, which is the *parent* of the theme +Mage-OS renders the admin in -- `mage-os/theme-adminhtml-m137` registers +`MageOS/m137-admin-theme` -- so the admin's own stylesheet was materialised on +the first request instead, and while Magento built it the browser's request +for it was answered with Magento's HTML 404 page. + +That means the admin had been rendering unstyled on the first page load of +every run, and nothing in this suite has anything to say about CSS. It showed +up as a flaky red on the session setup, which is the shape these findings +usually have: real, cheap to fix, invisible to every assertion. The fix went +in the workflow's theme list, not in the ignore list here. + The browser's own `Failed to load resource` console line is also ignored, for a different reason: it is a URL-less echo of something the response listener already reports with a status, a method and a full URL. Keeping both counts From 98f2a35909db5c9ee01b10021cac66d97673a356 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 16 Nov 2026 14:17:39 -0600 Subject: [PATCH 28/42] test(e2e): buy from a product page, keep an account, take an order Three specs, one per thing a store does that nothing here covered. product-page.spec.ts looks closely at what guest-checkout walks past. It asserts the product page's own details -- a sku, a stock status, a price -- and then the cart's arithmetic: unit price times quantity is the row subtotal, the rows are the subtotal, subtotal plus shipping is the order total. Totals are assembled by collectors any module can replace, so that is an assertion about the release. Every amount is compared against another amount the store rendered, never against a number in the spec. customer-account.spec.ts covers the account itself: register, the session that registering opens, sign out, sign in again, and a credential that is not an account. Luma renders every login field twice with the same ids -- the authentication popup ships a hidden copy of the form on every page -- so #send2 matches two elements and #pass matches the invisible one. Everything is scoped to .login-container, and the README has the measured table. admin/create-order.spec.ts places an order the way a merchant takes one by phone: new customer, product off the search grid, address, flat rate, check / money order, submit. That is a different code path from the storefront's REST quote, through the same quote model and method pools. What that page taught, all of it measured: - Every interaction is a POST to sales/order_create/loadBlock that re-renders part of the form, and there is no ready state. Waiting on timeouts reads the items grid before it re-renders and reports "No ordered items" for a product that was added. The spec counts those requests and waits for them to stop. - The row checkbox needs click(), not check(): the legacy grid's selection hangs off the click handler, so check() silently adds nothing. - A shipped store has exactly one payment method, so the admin applies it and collapses the block -- the radio is in the DOM, checked, and hidden. The spec asserts attached, expands if needed, clicks only if nothing is chosen. - The order grid is asserted here and the customer grid is not asserted in create-customer: sales/general/async_indexing is 0, so sales_order_grid is written in the same request, while customer_grid waits for an indexer no CI store has cron for. Two fixes the new specs surfaced: - The checkout's post-order 404 has a second form. Measured over six repeats: payment-information returns 200 and then, 76ms later, POST estimate-shipping-methods 404s against the quote that call consumed -- the same race as the /totals 404 already ignored, three clean, two on totals, one on estimate. Second ignore entry, scoped the same way. - The storefront half of an admin spec now runs as a visitor (asShopper). It inherited the admin cookie jar, including a form key the admin area controls, and create-customer failed twice with "Invalid Form Key" where it expected the duplicate-email refusal. selectRequiredOptions moves out of guest-checkout into storefront.ts, with parseMoney, so the storefront behaviour that is not theme-specific is shared rather than copied. --- _test/demo-package/Test/e2e/README.md | 200 ++++++++- .../Test/e2e/admin/create-customer.spec.ts | 4 + .../Test/e2e/admin/create-order.spec.ts | 392 ++++++++++++++++++ .../Test/e2e/admin/create-product.spec.ts | 6 + .../Test/e2e/customer-account.spec.ts | 144 +++++++ _test/demo-package/Test/e2e/fixtures.ts | 40 +- .../Test/e2e/guest-checkout.spec.ts | 30 +- _test/demo-package/Test/e2e/luma.ts | 52 +++ .../Test/e2e/product-page.spec.ts | 142 +++++++ _test/demo-package/Test/e2e/storefront.ts | 84 ++++ 10 files changed, 1040 insertions(+), 54 deletions(-) create mode 100644 _test/demo-package/Test/e2e/admin/create-order.spec.ts create mode 100644 _test/demo-package/Test/e2e/customer-account.spec.ts create mode 100644 _test/demo-package/Test/e2e/product-page.spec.ts create mode 100644 _test/demo-package/Test/e2e/storefront.ts diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index e296223c..7f2c7575 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -15,16 +15,21 @@ every change to it and runs this suite against the result. | --- | --- | --- | | `hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | | `guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | +| `product-page.spec.ts` | yes | the product page's own details, and a cart whose arithmetic adds up | +| `customer-account.spec.ts` | no | register -> signed in -> sign out -> sign in, and a refused credential | | `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | | `admin/product-grid.spec.ts` | yes | the product grid renders through Magento_Ui and filters server-side | | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | | `admin/create-category.spec.ts` | yes | category tree -> save -> url rewrite -> category index -> storefront listing + menu | | `admin/create-customer.spec.ts` | no | customer form -> save -> read-back -> the storefront refuses the address twice | +| `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid | | `admin/menu-navigation.spec.ts` | no | the admin's own rendered link reaches the product grid, secret key or not | Storefront selectors live in `luma.ts`, shared by every spec that looks at a storefront page. A Hyva variant of this suite is that file with a different -map, not a rewrite of the specs. +map, not a rewrite of the specs. `storefront.ts` holds the behaviour that goes +with them -- choosing whatever options a product requires, and reading the +number out of a rendered price -- because that part is not theme-specific. ## Running it against a store @@ -51,6 +56,80 @@ npx playwright test --project=admin # pulls in admin-session itself There is no default base URL. A suite that silently falls back to some public demo store reports green about a store nobody asked about. +## The storefront specs + +### Luma renders every login field twice, with the same ids + +Magento renders the authentication popup -- the one checkout opens -- into +every page, and it carries a second copy of the sign-in form. Measured on the +login page of Mage-OS 4.0.0: + +| Selector | `name` | Visible | Which copy | +| --- | --- | --- | --- | +| `#pass` | `password` | no | the popup | +| `#password` | `login[password]` | yes | the form | +| `#customer-email` | `username` | no | the popup | +| `#email` | `login[username]` | yes | the form | +| `#send2` | - | no | the popup | +| `#send2` | - | yes | the form | + +So `#send2` matches two elements and `#pass` matches the invisible one. A spec +that uses either waits thirty seconds for a hidden element to become +clickable and then reports a timeout, which reads as a broken store rather +than as a selector that found the wrong copy. Everything in `luma.ts` under +sign-in is scoped to `.login-container`, which holds only the real form. + +This is the storefront twin of the `#login-form` collision the admin sign-in +spec documents below -- and the same popup is what causes it. + +### Registering signs the customer in + +`CreatePost` calls `setCustomerDataAsLoggedIn` unless +`customer/create_account/confirm` is set, and it is `0`. Two consequences for +a spec: + +- The login page is only reachable after signing out. Visiting it while + signed in redirects to the dashboard -- where the only password field left + in the DOM is the popup's hidden copy, so the symptom is the timeout above + rather than a wrong URL. +- The sign-out link is rendered **four times** and every copy is hidden until + the header's `.customer-welcome` switch is clicked. Clicking that switch is + part of the assertion: a header that never renders its customer menu is a + broken header. + +The account dashboard's Contact Information box is server rendered, so that is +what the spec reads the saved customer back out of. The header greeting +arrives with private content and is a worse thing to assert on. + +A password needs 8 characters and 3 of the 4 character classes +(`customer/password/minimum_password_length`, +`required_character_classes_number`). + +### The storefront CAPTCHA is on, for two forms + +`customer/captcha/enable` is `1`, for `user_login` and `user_forgotpassword`, +in `after_fail` mode, after **three failures per login name**. So the refusal +test signs in as an address generated per run, which can never be the third +failure for anything -- the same trick the admin sign-in spec uses, for the +same reason. + +Registration has no CAPTCHA: `user_create` appears in `always_for` but not in +`customer/captcha/forms`, and the `forms` list is what decides. + +### Why a second cart spec + +`guest-checkout.spec.ts` walks past the product page and the cart on its way +to an order, and it has to -- its subject is the whole path. `product-page` +looks closely at both instead, and asserts the thing nothing else does: that +the arithmetic holds. Unit price times quantity is the row subtotal, the rows +are the cart subtotal, subtotal plus shipping is the order total. Totals are +assembled by collectors that any module can replace, so that is an assertion +about the release. + +Every amount is compared against another amount the store rendered, never +against a number in the spec. A gate that goes red because a fixture +product's price changed is a gate people switch off. + ## The admin specs The storefront is a thin skin over the catalog; the admin is where the @@ -281,6 +360,84 @@ if a future release does grow a blocking dialog on first sign-in, the right outcome is a red test with a screenshot of it, not a suite that dismisses it and reports green. +### The create-order form rebuilds itself, and that is the whole problem + +`admin/create-order.spec.ts` drives a page from before Magento_Ui. Every +interaction -- choosing a customer, adding a product, changing the country, +asking for rates, picking a payment method -- is a POST to +`sales/order_create/loadBlock` that returns fresh HTML for part of the form. +There is no "ready" state, no loading mask that is reliably present, and the +next action's target often does not exist until the previous reload lands. + +Waiting on timeouts does not work, and it fails in the worst way. Measured +while writing the spec: add a product, read the items grid 700ms later, and it +says **"No ordered items"** -- the add had been accepted, the grid had not +re-rendered. A spec written that way then picks a shipping method for an empty +order, gets no rates, and goes red three steps away from anything that is +wrong. + +So the spec counts those requests and waits for them to stop -- in flight +count at zero and nothing new for a quiet period. The quiet period matters: +one action can trigger two reloads, so awaiting "the next response" returns on +the first and reads a half-built form. + +Three more traps on that page, each of which cost a red run to find: + +- **The row checkbox needs `click()`, not `check()`.** It is the legacy grid + widget, whose selection is wired to the checkbox's click handler. + `check()` sets the property, the handler never runs, and the product is + silently not added. Same family as the category spec's product grid. +- **The sku filter is a `LIKE`.** Filtering for `product_dynamic` returns + every fixture simple, so the spec reads the sku, name and price out of the + row it picked instead of assuming which row it got. +- **One payment method means the radio is checked and hidden.** A shipped + store has exactly one active method, so the admin applies it as soon as the + order has a total and collapses the block to a summary line. The input is + in the DOM, `checked`, and invisible. Insisting on clicking it fails with + `42 x locator resolved to <input ... id="p_method_checkmo" + checked="checked"> - unexpected value "hidden"`, which reads as a missing + payment method rather than as one already chosen. The spec asserts + *attached*, expands the summary if it is collapsed, and only clicks if + nothing has been chosen -- so it works on a store with one method and on a + store with six. + +### The storefront half of an admin spec is a different visitor + +Three admin specs cross into the storefront to prove the save reached a +shopper. They do it from a fresh session, by `asShopper(page)` in +`storefront.ts`, and that is not tidiness either. + +The admin specs reuse a saved admin session, which is a cookie jar the +storefront requests inherit: an `admin` cookie, a PHPSESSID created in the +adminhtml area, and a `form_key` cookie that belongs to it. Magento renders +the storefront form with that session's form key, and Magento_PageCache's +form-key-provider rewrites the hidden input from the cookie -- so a storefront +POST is validated against a form key the admin area also controls. + +Observed: `admin/create-customer.spec.ts` failed its registration step twice +with `Invalid Form Key. Please refresh the page.` where it expected `There is +already an account with this email address`, then passed five times in a row. +Anything else touching that admin session -- a second run against the same +store, a human signed in as the same account, a retry -- can rotate the key +under a page that has already rendered it. CI has never seen it, because a +gate's store is used once and by one run. + +Rather than chase that race: a shopper is not an administrator. Clearing the +cookies costs one request's worth of session and removes the class. + +### One grid a save does update + +`admin/create-order.spec.ts` asserts the order appears in the order grid. +`admin/create-customer.spec.ts` deliberately does not assert the customer +grid. The difference is in the shipped configuration, not in the specs: +`sales/general/async_indexing` is `0`, so `sales_order_grid` is written in the +same request that saves the order, while `customer_grid` is a scheduled +indexer that this store has no cron to run. + +One is a fair assertion. The other would be a red test against a store that is +working correctly, which is the worst kind to put in front of someone deciding +whether to ship. + ### Secret keys in admin URLs, and the one spec that survives them `admin/security/use_form_key` is **Add Secret Key to URLs**, not the POST form @@ -348,17 +505,29 @@ outright. The gap is everything requested in the background, which is most of what a Magento page does after it renders. It was committed strict only after a report-only run of the whole suite. -Eleven specs produced exactly one recurring finding: `GET -/guest-carts/<id>/totals` answering 404 about 460ms after -`payment-information` returned 200. The checkout refreshes the cart totals -after the order is placed, by which point the quote it is asking about has -been consumed -- the shopper is on the success page and nothing is broken. -That is the single entry in the ignore list, scoped to that path and that -status so it cannot hide a cart that 404s while a shopper is still trying to -check out. - -A third entry was added after the first rehearsal with Varnish owning the -page cache: Mage-OS enables cross-document view transitions by default +Eleven specs produced exactly one recurring finding: a request the checkout +issues against the quote that placing the order has just consumed. The masked +id of a guest cart stops resolving the moment the quote becomes an order, so +anything still in flight comes back 404. Which request it is, is a race. +Measured by logging every `/rest/` response with its offset from the start of +the test and repeating the checkout spec six times -- three clean, two on +totals, one on estimate-shipping-methods: + +``` ++10164ms 200 POST .../payment-information ++10645ms 404 GET .../totals (+481ms) + + +7633ms 200 POST .../payment-information + +7709ms 404 POST .../estimate-shipping-methods (+76ms) +``` + +The shopper is on the success page by then and nothing is broken. Those are +two entries in the ignore list, each scoped to one path, one method and one +status -- not to 404s, not to `/rest/` 404s, and not to `/guest-carts/` 404s. +A cart that 404s while a shopper is still checking out has to stay a finding. + +A third kind of entry was added after the first rehearsal with Varnish owning +the page cache: Mage-OS enables cross-document view transitions by default (`MageOS_ThemeOptimization`, `system/view_transitions/enable` = 1), and under automation Chrome intermittently aborts one in flight with `Transition was aborted because of invalid state. ViewTransition opt-in disabled`. It showed @@ -539,3 +708,10 @@ least two in the `<configs>` block. Registered-customer checkout, a real payment gateway, taxes, discounts and multi-address shipping. Each wants fixtures of its own, and none of them is on the path between "we tagged a release" and "a shopper can buy something". + +Two of those gaps are now smaller from the other side. `customer-account` +covers the account itself -- registration, the session it opens, sign-out and +sign-in -- without checking out as that customer, and `admin/create-order` +places an order against a quote built in the admin, which is the same quote +model, carrier pool and payment pool through a different front end. What is +still missing is a shopper who signs in and then buys something. diff --git a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts index cdbf5790..4bcacb63 100644 --- a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -1,5 +1,6 @@ import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; +import { asShopper } from '../storefront'; import { luma } from '../luma'; /** @@ -122,6 +123,9 @@ test.describe('Creating a customer in the admin', () => { // the address up within the website the admin form assigned, so a // customer saved to the wrong website -- or not committed at all // -- registers happily here and the spec goes red. + // As a visitor, not as the signed-in administrator this spec + // has been so far. See asShopper(). + await asShopper(page); await page.goto('/customer/account/create/'); await expect(page.locator(luma.registerForm)).toBeVisible(); diff --git a/_test/demo-package/Test/e2e/admin/create-order.spec.ts b/_test/demo-package/Test/e2e/admin/create-order.spec.ts new file mode 100644 index 00000000..9a230bdb --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -0,0 +1,392 @@ +import { type Page, type Request } from '@playwright/test'; +import { expect, test } from '../fixtures'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +import { parseMoney } from '../storefront'; + +/** + * Placing an order from the admin, which is how a merchant takes a phone + * order and the only part of the sales flow a storefront spec cannot reach. + * + * It is a different code path from guest-checkout.spec.ts, not a second run + * at the same one. The storefront builds a quote through the REST API and + * Magento_Checkout's knockout components; this page builds one through + * Magento\Sales\Controller\Adminhtml\Order\Create and a Prototype-era form + * that re-renders itself on the server after every change. They share the + * quote model, the shipping and payment method pools and the order placement, + * and nothing else. + * + * ## The one thing that makes this page testable + * + * Every interaction here -- choosing a customer, adding a product, changing + * the country, asking for shipping rates, picking a payment method -- is a + * POST to sales/order_create/loadBlock that returns fresh HTML for part of + * the form. There is no "the page is ready" state, no loading mask that is + * reliably present, and the next action's target often does not exist until + * the previous reload lands. + * + * Waiting on timeouts does not work, and fails in the worst possible way. + * Measured while writing this spec: adding a product, reading the items grid + * 700ms later and asserting on it produced "No ordered items" -- the add had + * been accepted, the grid had not re-rendered yet. A spec written that way + * would then select a shipping method for an empty order, get no rates, and + * fail three steps away from the thing that was actually fine. + * + * So this spec tracks those requests and waits for them to stop. That is what + * formReloads() below is, and it is the only reason the rest of this reads as + * simply as it does. + */ + +const orderForm = { + // sales-order_create-index, with the underscore: the body class is the + // full action name, and the route is sales/order_create. + startBodyClass: /sales-order_create-index/, + viewBodyClass: /sales-order-view/, + createNewCustomer: '#order-customer-selector .actions button.primary', + email: '#email', + group: '#group_id', + addProducts: '#order-items button', + searchGrid: '#sales_order_create_search_grid', + searchGridTable: '#sales_order_create_search_grid_table > tbody tr', + skuFilter: '#sales_order_create_search_grid_filter_sku', + applyFilter: '#sales_order_create_search_grid [data-action="grid-filter-apply"]', + addSelected: '#order-search .admin__page-section-title .actions button.action-add', + itemsGrid: '#order-items_grid', + billing: { + country: '#order-billing_address_country_id', + firstName: '#order-billing_address_firstname', + lastName: '#order-billing_address_lastname', + street: '#order-billing_address_street0', + city: '#order-billing_address_city', + regionSelect: '#order-billing_address_region_id', + regionInput: '#order-billing_address_region', + postcode: '#order-billing_address_postcode', + telephone: '#order-billing_address_telephone', + }, + getShippingRates: '#order-shipping_method a.action-default', + flatRate: '#s_method_flatrate_flatrate', + shippingSection: '#order-shipping_method', + paymentSection: '#order-billing_method', + // Expands the payment block when it has collapsed to a summary line. + paymentSummaryLink: '#order-billing_method_summary > a', + checkMoneyOrder: '#p_method_checkmo', + totals: '#order-totals', + // Relative to `totals`, and by label rather than by row position: a + // store with tax or a discount renders extra rows between these two. + subtotalRow: 'tr.row-totals:has-text("Subtotal") .price', + grandTotalRow: 'tr.row-totals:has-text("Grand Total") .price', + submit: '#submit_order_top_button', + saved: '.message-success', + orderStatus: '#order_status', + // The saved order's own items table, which is a different block from the + // form's: Order\View\Items renders .edit-order-table, with the sku in + // its own element and the quantity as a breakdown ("Ordered 2"). + orderedItems: '.edit-order-table', +}; + +const buyer = { + firstName: 'Mage-OS', + street: '1 Open Source Way', + city: 'Austin', + // Texas. Overridable for the same reason guest-checkout's is: a store + // installed for another country has different region ids. + regionId: process.env.E2E_REGION_ID ?? '57', + region: 'Texas', + postcode: '78701', + telephone: '5125550123', + countryId: process.env.E2E_COUNTRY_ID ?? 'US', +}; + +/** + * Watches the form's own reloads so a step can wait for the page to stop + * rebuilding itself before it touches the result. + * + * Counting requests rather than awaiting one named response, because a single + * action can trigger more than one -- filling the address fires a reload on + * change, and the click that follows fires another -- and awaiting "the next + * one" then returns on the wrong reload and reads a half-built form. + */ +function formReloads(page: Page) { + const isReload = (request: Request) => /order_create\/(loadBlock|addProducts)/i.test(request.url()); + let pending = 0; + let lastFinished = Date.now(); + + page.on('request', (request) => { + if (isReload(request)) pending += 1; + }); + const finish = (request: Request) => { + if (isReload(request)) { + pending = Math.max(0, pending - 1); + lastFinished = Date.now(); + } + }; + page.on('requestfinished', finish); + page.on('requestfailed', finish); + + return { + /** Resets the clock, for the first wait after a full page load. */ + restart(): void { + pending = 0; + lastFinished = Date.now(); + }, + + /** + * Resolves once nothing is in flight and nothing new has started for + * a short quiet period. The quiet period is what catches the second + * reload an action triggers after the first one finished. + */ + async settled(quietFor = 1_000): Promise<void> { + await expect + .poll(() => pending === 0 && Date.now() - lastFinished > quietFor, { + message: 'the order form should stop reloading itself', + timeout: 120_000, + intervals: [200], + }) + .toBe(true); + }, + }; +} + +test.describe('Creating an order in the admin', () => { + // Long by design: a dozen server round trips, each re-rendering part of + // the form, on a store that may also be building static assets. + test.setTimeout(300_000); + + test('@admin places an order for a new customer', async ({ page }) => { + const form = formReloads(page); + const stamp = `${Date.now()}`; + const customer = { + lastName: `Order ${stamp}`, + email: `mageos-e2e-order-${stamp}@example.test`, + }; + const quantity = 2; + + let sku = ''; + let productName = ''; + let unitPrice = 0; + + await test.step('the create-order page opens on a new customer', async () => { + await page.goto(adminUrl('sales/order_create/start/')); + form.restart(); + + await expect(page.locator('body')).toHaveClass(orderForm.startBodyClass); + // "Create New Order in Default Store View" on a single-store + // install. A store with more than one view asks which one first, + // which this spec would have to answer -- so the title is worth + // asserting: it is how that difference shows up. + await expect(page.locator(adminSelectors.pageTitle)).toContainText('Create New Order'); + + await page.locator(orderForm.createNewCustomer).first().click(); + await form.settled(); + + // The account section is what the new-customer choice renders. + await expect(page.locator(orderForm.email)).toBeVisible(); + await expect(page.locator(orderForm.group)).not.toHaveValue(''); + }); + + await test.step('a fixture product goes on the order', async () => { + await page.locator(orderForm.addProducts).filter({ hasText: 'Add Products' }).first().click(); + await form.settled(); + + await expect(page.locator(orderForm.searchGrid)).toBeVisible(); + + // The sku filter is a LIKE, so this narrows the grid rather than + // selecting a row: product_dynamic matches every fixture simple. + await page.fill(orderForm.skuFilter, 'product_dynamic'); + await page.locator(orderForm.applyFilter).click(); + await form.settled(); + + const rows = page.locator(orderForm.searchGridTable); + await expect(rows.first(), 'the fixture catalog should fill this grid').toBeVisible(); + + // Read the row rather than assume a sku. Which fixture product + // comes first is not this spec's business, and the numbering is + // not contiguous -- the profile's first simple is + // product_dynamic_2. + const row = rows.first(); + const cells = (await row.locator('td').allInnerTexts()).map((cell) => cell.trim()); + sku = cells.find((cell) => /^product_dynamic_\d+$/.test(cell)) ?? ''; + productName = cells.find((cell) => /^Simple Product/.test(cell)) ?? ''; + unitPrice = parseMoney(cells.find((cell) => /^\$/.test(cell)) ?? ''); + + expect(sku, `the row should carry a fixture sku; it reads: ${cells.join(' | ')}`).not.toBe(''); + expect(unitPrice, 'the row should carry a price').toBeGreaterThan(0); + + // click(), not check(): this is the legacy grid widget, whose + // selection is wired to the checkbox's click handler. check() + // sets the property, the handler never runs, and the product is + // not added -- with no error anywhere. + await row.locator('td.col-select input[type="checkbox"]').click(); + await row.locator('td.col-qty input[name="qty"]').fill(String(quantity)); + + await page.locator(orderForm.addSelected).click(); + await form.settled(); + + const items = page.locator(orderForm.itemsGrid); + await expect(items).toContainText(sku); + await expect(items, 'the items grid should report what it holds').toContainText( + '1 product(s)', + ); + }); + + await test.step('the order gets an account and an address', async () => { + await page.fill(orderForm.email, customer.email); + + // The country goes first and on its own: changing it reloads the + // address block to swap the region field between a select and a + // free-text input, which discards anything typed before it. + await page.selectOption(orderForm.billing.country, buyer.countryId); + await form.settled(); + + await page.fill(orderForm.billing.firstName, buyer.firstName); + await page.fill(orderForm.billing.lastName, customer.lastName); + await page.fill(orderForm.billing.street, buyer.street); + await page.fill(orderForm.billing.city, buyer.city); + + const regionSelect = page.locator(orderForm.billing.regionSelect); + if (await regionSelect.isVisible()) { + await regionSelect.selectOption(buyer.regionId); + } else { + await page.fill(orderForm.billing.regionInput, buyer.region); + } + + await page.fill(orderForm.billing.postcode, buyer.postcode); + await page.fill(orderForm.billing.telephone, buyer.telephone); + + // The address reaches the quote when a field loses focus, and the + // shipping rates below are quoted against the quote. Without this + // the rates are requested for an address the server has not been + // told about yet. + await page.locator(orderForm.billing.telephone).blur(); + await form.settled(); + }); + + let shipping = 0; + + await test.step('the carrier quotes a rate and the method is chosen', async () => { + await page.locator(orderForm.getShippingRates).first().click(); + await form.settled(); + + // Flat Rate is active in a shipped store + // (OfflineShipping's config.xml: carriers/flatrate/active = 1), + // which is what makes it the right method for a release gate: no + // credentials, no external service, and it still goes through the + // carrier pool and the rate request. + await expect( + page.locator(orderForm.flatRate), + 'flat rate should be offered for a complete address', + ).toBeVisible(); + await page.locator(orderForm.flatRate).check(); + await form.settled(); + + await expect(page.locator(orderForm.shippingSection)).toContainText('Flat Rate'); + }); + + await test.step('check / money order takes the payment', async () => { + const checkMoneyOrder = page.locator(orderForm.checkMoneyOrder); + + // Attached, not visible. A store that offers exactly one payment + // method -- which a shipped store does: check / money order is + // the only active one -- has the admin apply it as soon as the + // order has a total, and the block collapses to a summary line + // with the radio still in the DOM, checked and hidden. + // + // So this cannot assert visibility and cannot insist on clicking. + // Measured: it fails with `42 x locator resolved to <input ... + // id="p_method_checkmo" checked="checked"> - unexpected value + // "hidden"`, which reads as a missing payment method rather than + // as one that was already chosen. + await expect( + checkMoneyOrder, + 'check / money order should be offered; it is active in a shipped store', + ).toBeAttached(); + + const summary = page.locator(orderForm.paymentSummaryLink); + if (!(await checkMoneyOrder.isVisible()) && (await summary.count())) { + await summary.first().click(); + await form.settled(); + } + + // Only if the store has not already decided. On a store with + // several active methods this is the real choice; on a shipped + // one it is a no-op, and both have to work. + if (!(await checkMoneyOrder.isChecked())) { + await checkMoneyOrder.check(); + await form.settled(); + } + + await expect(checkMoneyOrder).toBeChecked(); + await expect(page.locator(orderForm.paymentSection)).toContainText('Check / Money order'); + + const totals = page.locator(orderForm.totals); + const subtotal = parseMoney(await totals.locator(orderForm.subtotalRow).first().innerText()); + const grandTotal = parseMoney(await totals.locator(orderForm.grandTotalRow).first().innerText()); + shipping = grandTotal - subtotal; + + // The same arithmetic the cart spec checks on the storefront, + // against the same collectors through a different front end. + expect(subtotal, `${unitPrice} x ${quantity} should be the order subtotal`).toBeCloseTo( + unitPrice * quantity, + 2, + ); + expect(grandTotal, 'the grand total should include shipping').toBeGreaterThan(subtotal); + expect(shipping, 'flat rate should charge for the shipment').toBeGreaterThan(0); + }); + + let incrementId = ''; + + await test.step('submitting it creates the order', async () => { + await page.locator(orderForm.submit).click(); + + await expect(page.locator(orderForm.saved)).toContainText('You created the order.'); + await expect(page).toHaveURL(/\/sales\/order\/view\/order_id\/\d+/); + await expect(page.locator('body')).toHaveClass(orderForm.viewBodyClass); + + // Pending is what an offline payment method leaves an order on. + // A store whose order status mapping is broken reaches this page + // and shows something else. + await expect(page.locator(orderForm.orderStatus)).toHaveText('Pending'); + + incrementId = (await page.locator(adminSelectors.pageTitle).innerText()).trim().replace(/^#/, ''); + expect(incrementId, 'the order view is titled with the increment id').toMatch(/^\d+$/); + + // The persisted order item, read from the saved order rather than + // from the form that created it. Scoped to the row that carries + // the sku, because the column classes are on the header cells + // too: an unscoped .col-ordered-qty matches the "Qty" heading + // first, and the failure then quotes the heading at you. + const item = page + .locator(`${orderForm.orderedItems} tbody tr`) + .filter({ hasText: sku }) + .first(); + await expect(item, 'the saved order should hold the product that was added').toBeVisible(); + await expect(item).toContainText(productName); + await expect(item.locator('.col-ordered-qty')).toContainText(String(quantity)); + }); + + await test.step('the order grid lists it', async () => { + // Asserted here, and deliberately not asserted in + // create-customer.spec.ts, because the two grids behave + // differently and the difference is in the shipped + // configuration: sales/general/async_indexing is 0, so + // sales_order_grid is written in the same request that saves the + // order, while the customer grid waits for an indexer that this + // store has no cron to run. One is a fair assertion and the other + // is a red test against a working store. + await page.goto(adminUrl('sales/order/')); + + const grid = adminGrid(page, 'sales_order_grid'); + await grid.ready(); + await grid.startUnfiltered(); + await grid.filterBy('increment_id', incrementId); + + await expect(grid.rows).toHaveCount(1); + await expect(grid.rows.first()).toContainText(incrementId); + await expect(grid.rows.first()).toContainText('Pending'); + + // Left clean: grid filters are saved per admin user in + // ui_bookmark, so a filter this spec leaves behind is a filter + // the next spec inherits. + await grid.clearFilters(); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts index a1a19400..32f6970b 100644 --- a/_test/demo-package/Test/e2e/admin/create-product.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -1,6 +1,7 @@ import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; import { luma, productUrl } from '../luma'; +import { asShopper } from '../storefront'; /** * The spec that crosses the most seams in the application, and the reason the @@ -185,6 +186,11 @@ test.describe('Creating a product in the admin', () => { // category listing would additionally depend on the category // assignment and the catalog search index, and would report all // three as one red. + // From here on this is a shopper, not the administrator who + // saved the product: the add-to-cart below posts a form key, and + // the admin session's is not the one to post. See asShopper(). + await asShopper(page); + const response = await page.goto(productUrl(product.urlKey)); expect(response?.status(), 'the url rewrite for a saved product should resolve').toBe(200); diff --git a/_test/demo-package/Test/e2e/customer-account.spec.ts b/_test/demo-package/Test/e2e/customer-account.spec.ts new file mode 100644 index 00000000..0252d9db --- /dev/null +++ b/_test/demo-package/Test/e2e/customer-account.spec.ts @@ -0,0 +1,144 @@ +import { expect, test } from './fixtures'; +import { luma } from './luma'; + +/** + * The storefront half of having customers: register, sign out, sign back in. + * + * admin/create-customer.spec.ts creates a customer in the admin and proves the + * storefront knows about it by being refused a second account for the same + * address. This is the other direction -- an account the shopper creates -- and + * it covers what that one cannot: the registration form's own validation, the + * session the registration opens, the sign-out that closes it and the sign-in + * that opens it again. Four separate pieces of Magento_Customer, none of them + * exercised by anything else in this suite. + * + * Three things about the store this spec relies on, each read from the shipped + * configuration rather than assumed: + * + * - A password needs 8 characters and 3 of the 4 character classes + * (customer/password/minimum_password_length, + * required_character_classes_number). The one below has all four. + * - Registration signs the customer in. CreatePost calls + * setCustomerDataAsLoggedIn unless customer/create_account/confirm is set, + * and it is 0. So the login page is only reachable after signing out -- + * visiting it while signed in redirects to the dashboard, where the only + * password field left in the DOM is the authentication popup's hidden copy. + * That looks exactly like a hung page. See luma.ts. + * - The storefront CAPTCHA is on (customer/captcha/enable = 1) for + * user_login and user_forgotpassword, in after_fail mode, after 3 failures + * *per login name*. The refusal test below signs in as an address that is + * generated per run, so it can never be the third failure for anything. + * Registration has no CAPTCHA: user_create is in always_for but not in + * customer/captcha/forms. + */ + +const password = 'Mage0s-E2E-pass1'; + +function shopper() { + const stamp = Date.now(); + + return { + firstName: 'Mage-OS', + lastName: `Shopper ${stamp}`, + email: `mageos-e2e-shopper-${stamp}@example.test`, + }; +} + +test.describe('Storefront customer account', () => { + test('creates an account and signs back into it', { tag: ['@customer'] }, async ({ page }) => { + const customer = shopper(); + + await test.step('the registration form accepts a new account', async () => { + const response = await page.goto('/customer/account/create/'); + + expect(response?.status(), 'the registration page should be served').toBe(200); + await expect(page.locator('body')).toHaveClass(/customer-account-create/); + + await page.fill(luma.registerFirstName, customer.firstName); + await page.fill(luma.registerLastName, customer.lastName); + await page.fill(luma.registerEmail, customer.email); + await page.fill(luma.registerPassword, password); + await page.fill(luma.registerPasswordConfirm, password); + + // Read back before submitting. A form that silently dropped a + // field fails here, where the cause is visible, rather than as a + // validation error whose text is about something else. + await expect(page.locator(luma.registerEmail)).toHaveValue(customer.email); + + await page.locator(luma.registerSubmit).click(); + }); + + await test.step('registering signs the customer in', async () => { + await expect(page.locator(luma.successMessage)).toContainText( + 'Thank you for registering with', + ); + await expect(page).toHaveURL(/\/customer\/account\/?$/); + await expect(page.locator('body')).toHaveClass(/customer-account-index/); + + // The dashboard's Contact Information box, which the server + // renders from the saved entity -- so this is the registration + // read back out of the database, not out of the form. + const information = page.locator(luma.accountInformation).first(); + await expect(information).toContainText(customer.email); + await expect(information).toContainText(customer.lastName); + }); + + await test.step('signing out ends the session', async () => { + // The link is in the DOM four times and every copy is hidden + // until the header's switch is clicked. Clicking the switch is + // therefore part of the assertion: a header that never renders + // its customer menu is a broken header. + const toggle = page.locator(luma.customerWelcomeToggle).first(); + await expect(toggle, 'the header should greet a signed-in customer').toBeVisible(); + await toggle.click(); + + const signOut = page.locator(luma.signOut).first(); + await expect(signOut).toBeVisible(); + await signOut.click(); + + await expect(page).toHaveURL(/\/customer\/account\/logoutSuccess/); + await expect(page.locator('body')).toHaveClass(/customer-account-logoutsuccess/); + await expect(page.locator(luma.pageTitle)).toContainText('You are signed out'); + }); + + await test.step('the account signs back in', async () => { + await page.goto('/customer/account/login/'); + + await expect(page.locator('body')).toHaveClass(/customer-account-login/); + // Scoped to .login-container: there is a second, hidden copy of + // every field on this page. An unscoped selector finds it. + await expect(page.locator(luma.loginContainer)).toBeVisible(); + + await page.fill(luma.loginEmail, customer.email); + await page.fill(luma.loginPassword, password); + await page.locator(luma.loginSubmit).click(); + + await expect(page).toHaveURL(/\/customer\/account\/?$/); + await expect(page.locator('body')).toHaveClass(/customer-account-index/); + await expect(page.locator(luma.accountInformation).first()).toContainText(customer.email); + }); + }); + + test('refuses a credential that is not an account', { tag: ['@customer'] }, async ({ page }) => { + // Generated per run, so these failures are counted against a login + // name nobody will ever use again -- the same reason the admin + // sign-in spec does it. The storefront CAPTCHA arms after three + // failures per login name, and the count outlives the run. + const unknown = `mageos-e2e-nobody-${Date.now()}@example.test`; + + await page.goto('/customer/account/login/'); + await expect(page.locator('body')).toHaveClass(/customer-account-login/); + + await page.fill(luma.loginEmail, unknown); + await page.fill(luma.loginPassword, 'not-the-password-1A'); + await page.locator(luma.loginSubmit).click(); + + // Magento deliberately says the same thing for a wrong password and + // an address that has no account, so this asserts the refusal and not + // which of the two reasons it was. + await expect(page.locator(luma.errorMessage)).toContainText( + 'The account sign-in was incorrect or your account is disabled temporarily', + ); + await expect(page.locator('body')).toHaveClass(/customer-account-login/); + }); +}); diff --git a/_test/demo-package/Test/e2e/fixtures.ts b/_test/demo-package/Test/e2e/fixtures.ts index 149d06f5..ef182ec8 100644 --- a/_test/demo-package/Test/e2e/fixtures.ts +++ b/_test/demo-package/Test/e2e/fixtures.ts @@ -71,22 +71,36 @@ const ignoredConsole: RegExp[] = [/^Failed to load resource/]; const ignoredPageErrors: RegExp[] = [/^Transition was aborted because of invalid state\./]; /** - * HTTP responses that are not findings. One entry, and it has to stay this - * narrow. + * HTTP responses that are not findings. Two entries, and they are the same + * phenomenon: a request Magento's checkout issues against the quote that + * placing the order has just consumed. * - * Magento's checkout refreshes the cart totals after the order is placed. - * Measured on Mage-OS 4.0.0: payment-information returns 200 at T, and - * GET /guest-carts/<id>/totals returns 404 at T+460ms, because the quote the - * place-order call just consumed is no longer an active guest cart. The - * shopper is on the success page by then and nothing is broken. + * The masked id of a guest cart stops resolving the moment the quote becomes + * an order, so anything still in flight -- or fired by a component reacting to + * the last change -- comes back 404. Measured on Mage-OS 4.0.0, by logging + * every /rest/ response with its offset from the start of the test and + * repeating the checkout spec: * - * Scoped to that one path and that one status rather than to 404s, or to - * /rest/ 404s, so it cannot hide a cart that 404s while the shopper is still - * trying to check out. That failure would also break the spec's own - * assertions -- totals would not render and the order would not be placed -- - * which is what makes an ignore this narrow safe to carry. + * +10164ms 200 POST .../payment-information + * +10645ms 404 GET .../totals (+481ms) + * + * +7633ms 200 POST .../payment-information + * +7709ms 404 POST .../estimate-shipping-methods (+76ms) + * + * Which of the two happens is a race -- in six repeats, three were clean, two + * ended on totals and one on estimate-shipping-methods. The shopper is on the + * success page by then and nothing is broken. + * + * Each entry is scoped to one path and one method and one status, rather than + * to 404s, to /rest/ 404s, or to /guest-carts/ 404s. That matters: a cart that + * 404s while the shopper is still checking out has to stay a finding. It would + * also break the spec's own assertions -- no totals, no order -- which is what + * makes ignores this narrow safe to carry. */ -const ignoredHttp: RegExp[] = [/^404 GET xhr \/rest\/\S+\/guest-carts\/\w+\/totals/]; +const ignoredHttp: RegExp[] = [ + /^404 GET xhr \/rest\/\S+\/guest-carts\/\w+\/totals/, + /^404 POST xhr \/rest\/\S+\/guest-carts\/\w+\/estimate-shipping-methods/, +]; const logFile = path.resolve(__dirname, 'test-results/js-errors.jsonl'); diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/guest-checkout.spec.ts index a45d2c3d..d601825c 100644 --- a/_test/demo-package/Test/e2e/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/guest-checkout.spec.ts @@ -1,6 +1,7 @@ import { type Page } from '@playwright/test'; import { expect, test } from './fixtures'; import { luma } from './luma'; +import { selectRequiredOptions } from './storefront'; // The deepest path a storefront check can walk: catalog -> product -> cart -> // shipping -> payment -> order. It touches the layered navigation, the price @@ -23,35 +24,6 @@ const shopper = { countryId: process.env.E2E_COUNTRY_ID ?? 'US', }; -// A configurable product will not go into the cart until every attribute has a -// value, and which product the catalog lists first is not ours to decide. So -// pick the first available value for whatever the page asks for, and let the -// spec work on a simple product, a configurable, or a merchant's own catalog. -async function selectRequiredOptions(page: Page) { - const swatchGroups = page.locator(luma.swatchGroup); - for (let i = 0; i < (await swatchGroups.count()); i++) { - const option = swatchGroups.nth(i).locator(luma.swatchOption).first(); - if (await option.count()) { - await option.click(); - } - } - - // Configurables render dropdowns instead of swatches when the attribute - // has no swatch values, which is what the fixture profile produces. - const selects = page.locator(luma.optionSelect); - for (let i = 0; i < (await selects.count()); i++) { - const select = selects.nth(i); - const values = await select - .locator('option') - .evaluateAll((options) => - options.map((option) => (option as HTMLOptionElement).value).filter(Boolean), - ); - if (values.length) { - await select.selectOption(values[0]); - } - } -} - async function fillShippingAddress(page: Page) { const form = page.locator(luma.shippingForm); diff --git a/_test/demo-package/Test/e2e/luma.ts b/_test/demo-package/Test/e2e/luma.ts index accceab1..b7ffe6f6 100644 --- a/_test/demo-package/Test/e2e/luma.ts +++ b/_test/demo-package/Test/e2e/luma.ts @@ -16,6 +16,16 @@ export const luma = { productItemLink: 'a.product-item-link', pageTitle: '.page-title', productPrice: '.product-info-main .price', + // The sku Luma prints under the product's details. On a configurable this + // starts as the parent sku and is rewritten by JS once an option is + // chosen, so a spec asserts that it is there and not what it says. + productSku: '.product.attribute.sku .value', + // Luma's availability block. `.available` is the in-stock variant -- the + // out-of-stock one is `.unavailable` -- so the selector matching at all + // is the assertion, and a product the price index has not reached renders + // neither. + productStock: '.stock.available', + productQty: '#qty', addToCart: '#product-addtocart-button', swatchGroup: '.swatch-attribute', swatchOption: '.swatch-option:not(.disabled)', @@ -23,6 +33,15 @@ export const luma = { cartSuccess: '.message-success', minicartCounter: '.minicart-wrapper .counter-number', cartItemName: '.cart.item .product-item-name', + cartItem: '.cart.item', + cartItemQty: '.cart.item input.qty', + cartItemPrice: '.cart.item .col.price .price', + cartItemSubtotal: '.cart.item .col.subtotal .price', + // The totals block, by row class rather than by position: a store with + // tax or a discount renders extra rows between these three. + cartSubtotal: '.cart-totals .totals.sub .price', + cartShipping: '.cart-totals .totals.shipping .price', + cartGrandTotal: '.cart-totals .grand .price', proceedToCheckout: 'button[data-role="proceed-to-checkout"]', checkoutEmail: '#customer-email', shippingForm: '#co-shipping-form', @@ -44,6 +63,39 @@ export const luma = { registerPasswordConfirm: '#password-confirmation', registerSubmit: '#form-validate button[type="submit"]', errorMessage: '.message-error', + successMessage: '.message-success', + + // Sign-in. Every selector here is scoped to .login-container, and that is + // not tidiness. Magento renders the authentication popup -- the one + // checkout opens -- into every page, and it carries a second copy of this + // form with the SAME ids. Measured on the login page of Mage-OS 4.0.0: + // + // #pass name=password hidden (the popup) + // #password name=login[password] visible (the form) + // #customer-email name=username hidden (the popup) + // #email name=login[username] visible (the form) + // #send2 .action-login.secondary hidden (the popup) + // #send2 .login.primary visible (the form) + // + // So an unscoped #send2 or #pass resolves to a hidden element and the + // spec times out waiting for it to become clickable -- which reads as a + // broken page rather than as a selector that matched the wrong copy. + // .login-container holds only the real form. + loginContainer: '.login-container', + loginEmail: '.login-container input[name="login[username]"]', + loginPassword: '.login-container input[name="login[password]"]', + loginSubmit: '.login-container button#send2', + + // The account dashboard's Contact Information box. Server rendered, + // unlike the header greeting, which arrives with private content and is + // therefore a worse thing to assert on. + accountInformation: '.box-information .box-content', + // Luma renders the sign-out link four times -- header panel, account + // menu, and the two copies the authentication popup brings -- and hides + // every one of them until the header's customer-welcome switch is + // clicked. + customerWelcomeToggle: '.panel.header .customer-welcome button.action.switch', + signOut: 'a[href*="customer/account/logout"]', }; /** diff --git a/_test/demo-package/Test/e2e/product-page.spec.ts b/_test/demo-package/Test/e2e/product-page.spec.ts new file mode 100644 index 00000000..0a69478c --- /dev/null +++ b/_test/demo-package/Test/e2e/product-page.spec.ts @@ -0,0 +1,142 @@ +import { expect, test } from './fixtures'; +import { luma } from './luma'; +import { parseMoney, selectRequiredOptions } from './storefront'; + +/** + * A product page and the cart it fills, asserted properly. + * + * guest-checkout.spec.ts walks past both on its way to an order, and it has + * to: its subject is the whole path, so it checks that a price is on the page + * and that something reached the cart. What it cannot afford to do is look + * closely. This spec does that instead, and the difference is worth a + * separate red light: + * + * - A product page that renders without a sku, without a stock status or + * without a price is a broken catalog, and the checkout spec would still + * pass if the quantity it added was silently 1 instead of 3. + * - The cart's arithmetic is a release-sensitive thing that nothing else + * here checks. Totals are assembled by collectors, each of which can be + * replaced by a module, so "unit price times quantity equals the row + * subtotal, and the rows add up to the order total" is a real assertion + * about this release and not about this catalog. + * + * Every amount is compared against another amount the store rendered. None of + * them is compared against a number written in this file: a gate that goes + * red because a fixture product's price changed is a gate people switch off. + */ + +const quantity = 3; + +test.describe('Product page', () => { + test('adds a product to the cart from its own page', { tag: ['@catalog', '@cart'] }, async ({ page }) => { + let productName = ''; + + await test.step('the catalog lists a product', async () => { + await page.goto('/'); + + const category = page.locator(luma.navCategory).first(); + await expect(category, 'the fixture categories should appear in the main navigation').toBeVisible(); + await category.click(); + + await expect(page.locator('body')).toHaveClass(/catalog-category-view/); + + // Read the name from the listing so the product page can be + // checked against what the listing promised. A page that renders + // a different product than the link said is a url rewrite bug, + // and nothing else in this suite would see it. + const link = page.locator(luma.productList).locator(luma.productItemLink).first(); + await expect(link).toBeVisible(); + productName = (await link.innerText()).trim(); + + await link.click(); + }); + + let unitPrice = 0; + + await test.step(`the product page offers ${productName} for sale`, async () => { + await expect(page.locator('body')).toHaveClass(/catalog-product-view/); + await expect(page.locator(luma.pageTitle)).toContainText(productName); + + // A sku on the page means the attribute was loaded, not just the + // url rewrite resolved. Asserted as "not empty" rather than + // against a value: on a configurable this is the parent's sku + // until an option is chosen. + await expect(page.locator(luma.productSku).first()).not.toBeEmpty(); + + // The in-stock variant of the availability block. An unsalable + // product renders the page and no add-to-cart button, which is a + // far more confusing failure three steps later. + await expect(page.locator(luma.productStock).first()).toBeVisible(); + + const price = page.locator(luma.productPrice).first(); + await expect(price, 'a priced product means the price index ran').toBeVisible(); + unitPrice = parseMoney(await price.innerText()); + expect(unitPrice, 'the product page should render a price').toBeGreaterThan(0); + + await selectRequiredOptions(page); + }); + + await test.step(`the cart accepts ${quantity} of it`, async () => { + // Not the default quantity: 1 is what the field already says, so + // a spec that leaves it alone cannot tell a quantity that was + // applied from one that was ignored. + const qty = page.locator(luma.productQty); + await qty.fill(String(quantity)); + await expect(qty).toHaveValue(String(quantity)); + + await page.locator(luma.addToCart).click(); + + // Magento names the product in the message, which is the cheapest + // proof that what reached the quote is what was on screen. + await expect(page.locator(luma.cartSuccess)).toContainText( + `You added ${productName} to your shopping cart.`, + ); + + // The counter is private content, fetched separately from the + // page, so it is polled rather than read once. It is also the + // only place the suite sees the quote through a different request + // than the one that filled it. + await expect + .poll(async () => (await page.locator(luma.minicartCounter).innerText()).trim(), { + message: 'the minicart should count the quantity that was added', + }) + .toBe(String(quantity)); + }); + + await test.step('the cart page agrees with itself', async () => { + await page.goto('/checkout/cart/'); + + await expect(page.locator('body')).toHaveClass(/checkout-cart-index/); + await expect(page.locator(luma.cartItem)).toHaveCount(1); + await expect(page.locator(luma.cartItemName)).toContainText(productName); + await expect(page.locator(luma.cartItemQty).first()).toHaveValue(String(quantity)); + + const rowPrice = parseMoney(await page.locator(luma.cartItemPrice).first().innerText()); + const rowSubtotal = parseMoney(await page.locator(luma.cartItemSubtotal).first().innerText()); + + // The row against itself. A quote item whose quantity and row + // total disagree is the shape of every pricing regression worth + // stopping a release for, and it renders perfectly happily. + expect(rowSubtotal, `${rowPrice} x ${quantity} should be the row subtotal`).toBeCloseTo( + rowPrice * quantity, + 2, + ); + + const subtotal = parseMoney(await page.locator(luma.cartSubtotal).first().innerText()); + expect(subtotal, 'one row means the cart subtotal is that row').toBeCloseTo(rowSubtotal, 2); + + // Shipping is quoted on the cart page before checkout, so the + // grand total has at least two parts to add up. A store with tax + // or a discount renders more rows, which is why this reads the + // ones it needs by class instead of adding up every row it finds. + const shipping = parseMoney(await page.locator(luma.cartShipping).first().innerText()); + const grandTotal = parseMoney(await page.locator(luma.cartGrandTotal).first().innerText()); + + expect(shipping, 'the cart should quote a shipping amount').not.toBeNaN(); + expect(grandTotal, 'subtotal plus shipping should be the order total').toBeCloseTo( + subtotal + shipping, + 2, + ); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/storefront.ts b/_test/demo-package/Test/e2e/storefront.ts new file mode 100644 index 00000000..529ca487 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront.ts @@ -0,0 +1,84 @@ +import { type Page } from '@playwright/test'; +import { luma } from './luma'; + +/** + * Storefront behaviour shared between specs, as opposed to luma.ts, which is + * only the selectors. + */ + +/** + * A configurable product will not go into the cart until every attribute has + * a value, and which product the catalog lists first is not ours to decide. + * So pick the first available value for whatever the page asks for, and let a + * spec work on a simple product, a configurable, or a merchant's own catalog. + */ +export async function selectRequiredOptions(page: Page): Promise<void> { + const swatchGroups = page.locator(luma.swatchGroup); + for (let i = 0; i < (await swatchGroups.count()); i++) { + const option = swatchGroups.nth(i).locator(luma.swatchOption).first(); + if (await option.count()) { + await option.click(); + } + } + + // Configurables render dropdowns instead of swatches when the attribute + // has no swatch values, which is what the fixture profile produces. + const selects = page.locator(luma.optionSelect); + for (let i = 0; i < (await selects.count()); i++) { + const select = selects.nth(i); + const values = await select + .locator('option') + .evaluateAll((options) => + options.map((option) => (option as HTMLOptionElement).value).filter(Boolean), + ); + if (values.length) { + await select.selectOption(values[0]); + } + } +} + +/** + * The number inside a rendered price, e.g. '$1,234.56' -> 1234.56. + * + * Specs use this to compare amounts the store rendered against each other -- + * a row subtotal against its unit price and quantity, a grand total against + * its parts -- never against a literal. What a fixture product costs is not + * something a release gate should have an opinion about; that the arithmetic + * holds is. + * + * Returns NaN rather than throwing when there is no number in the text, so + * the caller's assertion is the thing that fails, with its own message. + * Assumes the group separator is ',' and the decimal separator is '.', which + * is en_US -- the locale this gate installs. + */ +export function parseMoney(text: string): number { + return Number.parseFloat(text.replace(/[^\d.,-]/g, '').replace(/,/g, '')); +} + +/** + * Drops the cookies an admin spec is carrying, so the storefront half of it + * runs as a visitor. + * + * The admin specs reuse a saved admin session, and that session is a cookie + * jar the storefront requests inherit: an `admin` cookie, a PHPSESSID created + * in the adminhtml area, and a `form_key` cookie that belongs to it. Magento + * then renders the storefront form with that session's form key, and + * Magento_PageCache's form-key-provider rewrites the input from the cookie -- + * so a storefront POST is validated against a form key the admin area also + * controls. + * + * Observed consequence: `admin/create-customer.spec.ts` failed its + * registration step twice with `Invalid Form Key. Please refresh the page.` + * where it expected `There is already an account with this email address`, + * and then passed five times in a row. Anything else touching that admin + * session -- another run against the same store, a human signed in as the + * same account, a retry -- can rotate the key underneath a page that has + * already rendered it. CI never saw it, because a gate's store is used once. + * + * So rather than chase the race: a shopper is not an administrator, and the + * specs that cross over say so here. It costs one request's worth of session + * and removes the whole class. + */ +export async function asShopper(page: Page): Promise<void> { + await page.context().clearCookies(); +} From 96c9f08f8a4b7997ecf82fa5adf643919fdccfad Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Mon, 16 Nov 2026 17:50:09 -0600 Subject: [PATCH 29/42] docs(e2e): name the release gate example for what it covers The example called the job storefront-check, which undersells a suite that is ten admin tests to five storefront ones, and did not say why the job sits between the deploy and the tag push. --- .github/workflows/e2e-README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 2d9f8c75..74085752 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -226,17 +226,21 @@ jobs: magento_version: "mage-os/project-community-edition:4.0.0" ``` -Gating a release on the artifact that is about to be tagged: +Gating a release on the artifact that is about to be tagged. It has to run +after the packages are deployed, because that is where it installs them from, +and before the tag is pushed, because the tag is the half of a release that is +expensive to retract: ```yaml jobs: - storefront-check: + e2e-check: + name: "storefront & admin check" needs: [ deploy ] uses: mage-os/github-actions/.github/workflows/e2e.yaml@main with: magento_repository: ${{ inputs.repo }} magento_version: "mage-os/project-community-edition:${{ inputs.mageos_release }}" - artifact_name: "storefront-check-${{ inputs.mageos_release }}" + artifact_name: "e2e-report-${{ inputs.mageos_release }}" ``` Running a suite of your own: From 0357c71e74836a457df9c8c9b3412963fcb9dc7d Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Tue, 17 Nov 2026 07:57:55 -0600 Subject: [PATCH 30/42] docs(e2e): cut the comments down to what the code does not say The workflows carried a paragraph where a sentence does. Each comment keeps the fact a reader cannot get from the file next to it -- that use_form_key is the secret-key setting, that there is no 2FA flag, that the admin CAPTCHA is on by default -- and the reasoning behind each one stays in e2e-README.md. Also moves the fixture-profile comment back above the step it describes, where an earlier edit had left it stranded above the admin step, and names both admin themes in the README's static content paragraph. --- .github/workflows/_internal-e2e.yaml | 189 ++++++++---------------- .github/workflows/e2e-README.md | 6 +- .github/workflows/e2e.yaml | 212 +++++++++------------------ 3 files changed, 142 insertions(+), 265 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 3cbde4f5..1a35dd37 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -39,32 +39,27 @@ jobs: TRAEFIK_DOMAIN: mageos.test TRAEFIK_SUBDOMAIN: app E2E_DIRECTORY: actions/_test/demo-package/Test/e2e - # Pinned rather than taken from supported-version: this workflow is here - # to tell us whether the action still serves a store, so a service bump - # elsewhere should not change what it reports. The release pipeline picks - # its own versions. + # Pinned rather than taken from supported-version: this workflow reports + # whether the action still serves a store, so a service bump elsewhere + # should not change what it says. The release pipeline picks its own. PHP_VERSION: "8.4" COMPOSER_VERSION: "2.10.2" - # Declared once and handed to both the install and the suite. Two places - # holding separate opinions about the admin URL is a silent 404 that - # looks like a broken admin. + # Declared once and handed to both the install and the suite: two + # opinions about the admin URL is a 404 that looks like a broken admin. ADMIN_FRONTNAME: "admin" - # What warden/setup-environment's admin:user:create step makes. Not a - # secret: it is a throwaway store that exists for the length of the job. + # Hardcoded by warden/setup-environment. Not a secret: a throwaway store + # that exists for the length of the job. ADMIN_USER: "admin" ADMIN_PASSWORD: "abcABC123" steps: - # Not at the workspace root: warden/setup-environment checks the Warden - # CLI out into warden/ there, which is where this repository keeps that - # action, and the checkout would land on top of it. + # Not at the workspace root: warden/setup-environment puts the Warden CLI + # in warden/ there, which is where this repository keeps that action. - uses: actions/checkout@v6 with: path: actions - # mode: extension is how the other internal workflows get a project onto - # disk -- composer create-project --no-install, into ./_ghamagento. The - # dependencies are then installed inside the container, by the PHP version - # that will serve them. + # mode: extension, like the other internal workflows: create-project + # --no-install into ./_ghamagento, then install inside the container. - name: Create the Mage-OS project uses: ./actions/setup-magento with: @@ -98,30 +93,18 @@ jobs: configure_host_resolution: 1 backend_frontname: ${{ env.ADMIN_FRONTNAME }} run_static_content_deploy: 1 - # The admin themes as well as the storefront one: the admin specs would - # otherwise wait for every asset to be generated on demand, which reads - # as a timeout, or as an unstyled page, rather than as a missing deploy. - # - # Both admin themes, because Mage-OS does not render the admin in - # Magento/backend. mage-os/theme-adminhtml-m137 registers - # MageOS/m137-admin-theme, and deploying only the parent left the child - # to be materialised on the first request: run 43932819737 answered the - # login page's own stylesheet with Magento's HTML 404 while it built it, - # and the browser reported "Refused to apply style ... MIME type - # ('text/html')" -- a flaky red on the admin session setup. + # The admin themes as well as the storefront one, or the admin specs + # wait for each asset to be built on demand. Both, because Mage-OS + # renders the admin in MageOS/m137-admin-theme: deploying only the + # parent left run 43932819737 serving the login page's own stylesheet + # as a 404 while it built it -- "Refused to apply style ... MIME type + # ('text/html')", a flaky red on the session setup. static_content_themes: "Magento/luma Magento/backend MageOS/m137-admin-theme" - # What run_magento_config_preset used to do, written out. Same values the - # action applies behind that boolean, minus web/seo/use_rewrites: with a - # base URL given, setup:install already passed --use-rewrites=1. - # - # Spelled out here because one of these moves the store away from what it - # ships as, and a gate that does that should say so where the gate is - # defined rather than inside a boolean named after a preset. The preset - # also carries settings this suite has no use for. - # - # Applied after the action rather than inside it, so the config cache is - # already holding the old values -- hence the flush at the end. + # What run_magento_config_preset used to do, written out: one of these + # moves the store away from what it ships as, which a gate should say + # where the gate is defined. web/seo/use_rewrites is dropped -- + # setup:install already passed --use-rewrites=1 with a base URL given. - name: Configure the store the suite assumes working-directory: ./_ghamagento shell: bash @@ -130,50 +113,33 @@ jobs: magento() { ${WARDEN} env exec -T php-fpm bin/magento "$@"; } # The browser speaks https to Traefik, so the store has to build https - # links on both sides. --lock-env, because this belongs to the - # environment and not to anything a test should be able to change. + # links on both sides. --lock-env: this belongs to the environment. magento config:set --lock-env web/secure/use_in_frontend 1 magento config:set --lock-env web/secure/use_in_adminhtml 1 - # "Add Secret Key to URLs" -- Magento\Backend\Model\Url names this - # same path XML_PATH_USE_SECURE_KEY. It is not the POST form key: - # AbstractAction::_processUrlKeys validates that for every logged-in - # POST whatever this is set to, so admin CSRF protection stays on - # either way. What the setting adds is a /key/<hash>/ segment on admin - # GET URLs, and module-store/etc/config.xml ships it as 1. - # - # With it on, a GET to a bare admin route is answered with a redirect - # to the dashboard: a 302 to a 200, which no failed-request check can - # see. Every admin spec here navigates by bare route, so this is off - # until they navigate by the links the admin renders instead -- - # admin/menu-navigation.spec.ts is the first one that does. + # "Add Secret Key to URLs" (XML_PATH_USE_SECURE_KEY), not the POST + # form key -- _processUrlKeys validates that either way, so admin CSRF + # protection stays on. With it on, as it ships, a GET to a bare admin + # route 302s to the dashboard: a 200 no failed-request check can see. + # Every admin spec but menu-navigation navigates by bare route. magento config:set admin/security/use_form_key 0 # Off, a login terminates the account's other sessions - # (Security\Model\AdminSessionsManager), and this suite shares one - # admin account across a saved storageState. Upstream's own integration - # suite sets it for the same reason, in - # dev/tests/integration/etc/config-global.php.dist. + # (AdminSessionsManager), and the suite shares one account across a + # saved storageState. Upstream's integration suite sets it too. magento config:set admin/security/admin_account_sharing 1 - # Inherited from the preset, and a hole: the product and category - # description fields ship with TinyMCE, so the gate never loads the - # editor the admin actually renders. Enabling it belongs in its own - # change with its own run, because it is likely to find something. + # Inherited from the preset, and a hole: the description fields ship + # with TinyMCE, so the gate never loads the editor the admin renders. + # Enabling it belongs in its own change, with its own run. magento config:set cms/wysiwyg/enabled disabled magento cache:flush - # Separate from the test run so that "the store was never reachable" and - # "the store rendered the wrong thing" are different red steps. - # - # The status is captured and compared rather than piped into head. This - # step used to be `curl --fail ... | head -1`, which reported a 404 and - # passed anyway: a GitHub `run:` without `shell: bash` gets `bash -e` - # without `-o pipefail`, so the pipeline took head's exit status and - # discarded curl's. The whole point of the step is to be the one red that - # says "nothing was served", and for one run it was a green that said the - # opposite. + # Separate from the test run so "never reachable" and "rendered the wrong + # thing" are different red steps. The status is captured rather than piped + # into head: a `run:` without `shell: bash` has no pipefail, so + # `curl --fail | head` once reported a 404 and passed anyway. - name: Confirm the store answers on the resolved hostname shell: bash env: @@ -187,14 +153,10 @@ jobs: exit 1 fi - # What the gate ran against, probed from the running stack rather than - # echoed back from the inputs: a version input can be a constraint, the - # repository can resolve it differently than expected, and a service tag - # does not carry its patch level. A failing release gate has to be able to - # say "it broke on OpenSearch 3.3.2", not "we asked for 3.3". - # - # Nothing here can fail the job. A probe that comes back empty reports - # "unknown" -- a disabled service is not a broken store. + # Probed from the running stack, not echoed back from the inputs: a + # version input can be a constraint, and a service tag carries no patch + # level. A failing gate has to be able to say "it broke on OpenSearch + # 3.3.2". Nothing here fails the job; an empty probe reports "unknown". - name: Record the stack under test id: stack working-directory: ./_ghamagento @@ -217,15 +179,10 @@ jobs: REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" - # Which side owns the page cache, and whether it is actually caching. - # - # Magento defaults to its own built-in cache, and only purges Varnish - # when it is configured as the cache. A Varnish serving every request - # that Magento never invalidates passes every spec here today -- each - # one visits a given URL once -- and fails the first spec that - # revisits a page after changing it, in a way that reads like a - # Magento bug. So the run says it outright rather than leaving it to - # be re-derived from the source every time. + # Which side owns the page cache, and whether it is caching. Magento + # only purges Varnish when Varnish is configured as the cache, and one + # it never invalidates passes every spec that visits a URL once, then + # fails the first that revisits a changed page -- looking like a bug. FPC="$(probe php-fpm bin/magento config:show system/full_page_cache/caching_application | head -1)" case "${FPC}" in 2) FPC="Varnish" ;; @@ -237,8 +194,8 @@ jobs: XCACHE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Xx]-[Mm]agento-[Cc]ache-[Dd]ebug: *//p' | head -1)" CACHECONTROL="$(printf '%s' "${HEADERS}" | sed -n 's/^[Cc]ache-[Cc]ontrol: *//p' | head -1)" - # Only the application versions reach the tests. A spec may reasonably - # branch on those; none should branch on a Redis patch level. + # Only the application versions reach the tests. No spec should branch + # on a Redis patch level. echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT echo "magento=${MAGENTO:-unknown}" >> $GITHUB_OUTPUT @@ -260,17 +217,11 @@ jobs: echo "| Homepage \`X-Magento-Cache-Debug\` | ${XCACHE:-none} |" } >> $GITHUB_STEP_SUMMARY - # Magento has no switch for two-factor authentication. There is no enable - # flag, and leaving twofactorauth/general/force_providers empty does not - # help: ControllerActionPredispatch still routes a fresh admin user to - # tfa/tfa/index, which redirects to tfa/tfa/requestconfig. Disabling the - # module is the only way in. MageOS_PasskeyAuth requires it and registers - # an admin 2FA provider, so both have to go in one command or dependency - # validation refuses it. - # - # The cost is stated rather than hidden: this gate does not cover admin - # 2FA. Covering it means driving a TOTP provider from its shared secret, - # which is worth doing, as its own spec. + # Magento has no switch for 2FA: force_providers is empty by default and + # ControllerActionPredispatch still routes a fresh admin user to + # tfa/tfa/index. Disabling the module is the only way in, and + # MageOS_PasskeyAuth requires it, so both go in one command. The cost is + # explicit: this gate does not cover admin 2FA. - name: Open the admin to the test suite working-directory: ./_ghamagento shell: bash @@ -279,9 +230,8 @@ jobs: MODULES=() for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do - # module:status exits 0 even for a module that is not installed, so - # its output is the only signal. MageOS_PasskeyAuth is Mage-OS only, - # and this workflow should still work against a Magento install. + # module:status exits 0 for a module that is not installed, so its + # output is the only signal. MageOS_PasskeyAuth is Mage-OS only. if ${WARDEN} env exec -T php-fpm bin/magento module:status "${MODULE}" 2>&1 | grep -q 'does not exist'; then echo "${MODULE} is not installed" else @@ -289,25 +239,21 @@ jobs: fi done - # An array, not a string: module:disable takes the names as separate - # arguments and reads a single space-joined string as one unknown - # module name. Re-running it changes nothing and still exits 0. + # An array, not a string: module:disable reads a space-joined string + # as one unknown module name. Re-running it changes nothing, exits 0. if [ ${#MODULES[@]} -gt 0 ]; then ${WARDEN} env exec -T php-fpm bin/magento module:disable "${MODULES[@]}" fi - # Already the default. Pinned so the suite does not rely on one: - # it gates Magento_AdminAnalytics' usage-data modal, which would - # otherwise cover the dashboard on first sign-in. + # Already the default. Pinned because it gates Magento_AdminAnalytics' + # usage-data modal, which would cover the dashboard on first sign-in. ${WARDEN} env exec -T php-fpm bin/magento config:set admin/usage/enabled 0 - # The admin login CAPTCHA is on by default (admin/captcha/enable 1) in - # after_fail mode, and asks for one after three failed attempts per - # login name -- counted in the captcha_log table, which survives - # across runs against a long-lived store. A suite that asserts a bad - # credential is refused produces exactly those failures, so leaving - # this on lets the negative control poison the positive one, and the - # symptom is an "Incorrect CAPTCHA" that looks nothing like the cause. + # On by default, in after_fail mode, after three failed attempts per + # login name -- counted in captcha_log, which survives across runs + # against a long-lived store. A suite that asserts a bad credential is + # refused makes exactly those failures, and the symptom is an + # "Incorrect CAPTCHA" on a password that is correct. ${WARDEN} env exec -T php-fpm bin/magento config:set admin/captcha/enable 0 ${WARDEN} env exec -T php-fpm bin/magento cache:flush @@ -347,14 +293,9 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ env.ADMIN_FRONTNAME }} run: npx playwright test - # What the stack was doing when something went wrong. Without this, "the - # store answered 404" is where the investigation stops: the containers go - # away with the runner, and nothing in the log says whether nginx was up, - # whether Varnish had a backend at all, or whether Traefik had a route to - # send the request to. - # - # Nothing in here may fail the job -- it only runs because something else - # already did. + # What the stack was doing when something went wrong: the containers go + # away with the runner, and nothing in the log says whether nginx was up + # or whether Traefik had a route. Nothing here may fail the job. - name: Report what the stack was doing if: failure() working-directory: ./_ghamagento diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 74085752..3aa76bb4 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -177,10 +177,12 @@ homepage's `Cache-Control`, `Age` and `X-Magento-Cache-Debug` headers say, so that is a line in the report rather than something to re-derive from the source. -`Magento/backend` is in the `static_content_themes` default for the same +Both admin themes are in the `static_content_themes` default for the same reason: an admin spec against an undeployed admin theme waits for every asset to be generated on demand, and reads as a timeout rather than as a missing -deploy. +deploy. Both, because Mage-OS renders the admin in +`MageOS/m137-admin-theme` (from `mage-os/theme-adminhtml-m137`), not in its +parent `Magento/backend`. Both versions are **probed from the running store** (`bin/magento --version`), not echoed back from `magento_version`. A version input can be a constraint, the repository can resolve it differently than expected, and a gate should diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 203b68dd..3663d7f0 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -1,16 +1,11 @@ name: E2E Tests # A reusable workflow that stands a Mage-OS store up, serves it, and points a -# browser-based test runner at it. +# browser-based test runner at it. It does not know what runner that is: +# test_command is an input. # -# It does not know what runner that is: test_command is an input, so a caller -# can pass grep filters, shards, a different reporter, or something that is not -# Playwright at all, without this workflow growing an input per flag. -# -# Own-repo actions are referenced by full ref rather than by "./", as -# integration.yaml and full-integration-tests.yaml do. A relative path in a -# reusable workflow resolves against the caller's checkout, which is not this -# repository when the caller is the release pipeline. +# Own-repo actions are referenced by full ref, not "./": a relative path in a +# reusable workflow resolves against the caller's checkout, not this one. on: workflow_call: @@ -63,17 +58,11 @@ on: Space separated themes to deploy static content for. Empty deploys every theme, which is considerably slower. - The admin themes are in the default because an admin spec against an - undeployed admin theme reads as a timeout, or as an unstyled page, - rather than as a missing deploy. Both of them, because Mage-OS does - not render the admin in Magento/backend: mage-os/theme-adminhtml-m137 - registers MageOS/m137-admin-theme and that is what the admin asks for. - - Naming a theme the store does not have is harmless. Nothing validates - this list up front -- Deploy\Strategy\StandardDeploy::canDeployTheme - walks the themes that are registered and checks each against it -- so - an unmatched name deploys nothing and fails nothing, which is what - lets one default cover Mage-OS and Magento. + Both admin themes are in the default: Mage-OS renders the admin in + MageOS/m137-admin-theme, Magento in Magento/backend, and an + undeployed admin theme reads as a timeout or an unstyled page rather + than as a missing deploy. A theme the store does not have deploys + nothing and fails nothing, so one default covers both. backend_frontname: required: false type: string @@ -83,7 +72,7 @@ on: required: false type: boolean default: true - description: "Disable Magento_TwoFactorAuth and MageOS_PasskeyAuth so a suite can sign in to the admin. Magento offers no configuration flag for this; see the step for why. Set false for a storefront-only run, which then leaves 2FA in place." + description: "Disable Magento_TwoFactorAuth and MageOS_PasskeyAuth so a suite can sign in to the admin; see the step for why there is no config flag. Set false for a storefront-only run." # Where the suite comes from. The default is the suite this repository # carries for its own canary; a caller with a suite of its own overrides @@ -109,10 +98,8 @@ on: default: "npx playwright test" description: > Run from test_directory with PLAYWRIGHT_BASE_URL set. Keep evidence - policy (trace, video, screenshot) in the suite's own config rather - than in flags here: a CLI flag overrides the config, and a gate that - records a trace for every passing test uploads a large artifact for - no benefit. + policy (trace, video, screenshot) in the suite's own config, not in + flags here: a CLI flag overrides the config. node_version: required: false type: string @@ -123,9 +110,8 @@ on: default: "_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml" description: > A performance-toolkit profile, relative to the root of - suite_repository, seeded before the tests run. Empty skips seeding, - which is right for a suite that asserts only on what a bare - setup:install provides. + suite_repository, seeded before the tests run. Empty skips seeding -- + right for a suite that only asserts on what setup:install provides. # Housekeeping. timeout_minutes: @@ -164,17 +150,14 @@ jobs: TRAEFIK_SUBDOMAIN: app # The suite is checked out here, and the tests run in SUITE/<dir>. SUITE: suite - # What warden/setup-environment's admin:user:create step makes. The - # action hardcodes these, so they are not inputs: an input a caller - # could change without the store changing would only ever be a lie. - # Not a secret either -- a throwaway store for the length of the job. + # Hardcoded by warden/setup-environment's admin:user:create step, so not + # inputs. Not secrets either -- a throwaway store for one job. ADMIN_USER: "admin" ADMIN_PASSWORD: "abcABC123" steps: - # Not at the workspace root: warden/setup-environment checks the Warden CLI - # out into warden/ there, and base_directory has to sit exactly one level - # below it. + # Not at the workspace root: warden/setup-environment puts the Warden CLI + # in warden/ there, and base_directory sits exactly one level below it. - name: Check out the test suite uses: actions/checkout@v6 with: @@ -217,17 +200,10 @@ jobs: run_static_content_deploy: 1 static_content_themes: ${{ inputs.static_content_themes }} - # What run_magento_config_preset used to do, written out. Same values the - # action applies behind that boolean, minus web/seo/use_rewrites: with a - # base URL given, setup:install already passed --use-rewrites=1. - # - # Spelled out here because one of these moves the store away from what it - # ships as, and a gate that does that should say so where the gate is - # defined rather than inside a boolean named after a preset. The preset - # also carries settings this suite has no use for. - # - # Applied after the action rather than inside it, so the config cache is - # already holding the old values -- hence the flush at the end. + # What run_magento_config_preset used to do, written out: one of these + # moves the store away from what it ships as, which a gate should say + # where the gate is defined. web/seo/use_rewrites is dropped -- + # setup:install already passed --use-rewrites=1 with a base URL given. - name: Configure the store the suite assumes working-directory: ./_ghamagento shell: bash @@ -236,50 +212,34 @@ jobs: magento() { ${WARDEN} env exec -T php-fpm bin/magento "$@"; } # The browser speaks https to Traefik, so the store has to build https - # links on both sides. --lock-env, because this belongs to the - # environment and not to anything a test should be able to change. + # links on both sides. --lock-env: this belongs to the environment. magento config:set --lock-env web/secure/use_in_frontend 1 magento config:set --lock-env web/secure/use_in_adminhtml 1 - # "Add Secret Key to URLs" -- Magento\Backend\Model\Url names this - # same path XML_PATH_USE_SECURE_KEY. It is not the POST form key: - # AbstractAction::_processUrlKeys validates that for every logged-in - # POST whatever this is set to, so admin CSRF protection stays on - # either way. What the setting adds is a /key/<hash>/ segment on admin - # GET URLs, and module-store/etc/config.xml ships it as 1. - # - # With it on, a GET to a bare admin route is answered with a redirect - # to the dashboard: a 302 to a 200, which no failed-request check can - # see. Every admin spec here navigates by bare route, so this is off - # until they navigate by the links the admin renders instead -- - # admin/menu-navigation.spec.ts is the first one that does. + # "Add Secret Key to URLs" (XML_PATH_USE_SECURE_KEY), not the POST + # form key -- _processUrlKeys validates that either way, so admin CSRF + # protection stays on. With it on, as it ships, a GET to a bare admin + # route 302s to the dashboard: a 200 no failed-request check can see. + # Every admin spec but menu-navigation navigates by bare route. magento config:set admin/security/use_form_key 0 # Off, a login terminates the account's other sessions - # (Security\Model\AdminSessionsManager), and this suite shares one - # admin account across a saved storageState. Upstream's own integration - # suite sets it for the same reason, in - # dev/tests/integration/etc/config-global.php.dist. + # (AdminSessionsManager), and the suite shares one account across a + # saved storageState. Upstream's integration suite sets it too. magento config:set admin/security/admin_account_sharing 1 - # Inherited from the preset, and a hole: the product and category - # description fields ship with TinyMCE, so the gate never loads the - # editor the admin actually renders. Enabling it belongs in its own - # change with its own run, because it is likely to find something. + # Inherited from the preset, and a hole: the description fields ship + # with TinyMCE, so the gate never loads the editor the admin renders. + # Enabling it belongs in its own change, with its own run. magento config:set cms/wysiwyg/enabled disabled + # The config cache was loaded before any of this was set. magento cache:flush - # Separate from the test run so that "the store was never reachable" and - # "the store rendered the wrong thing" are different red steps. - # - # The status is captured and compared rather than piped into head. This - # step used to be `curl --fail ... | head -1`, which reported a 404 and - # passed anyway: a GitHub `run:` without `shell: bash` gets `bash -e` - # without `-o pipefail`, so the pipeline took head's exit status and - # discarded curl's. The whole point of the step is to be the one red that - # says "nothing was served", and for one run it was a green that said the - # opposite. + # Separate from the test run so "never reachable" and "rendered the wrong + # thing" are different red steps. The status is captured rather than piped + # into head: a `run:` without `shell: bash` has no pipefail, so + # `curl --fail | head` once reported a 404 and passed anyway. - name: Confirm the store answers on the resolved hostname shell: bash env: @@ -293,14 +253,10 @@ jobs: exit 1 fi - # What the gate ran against, probed from the running stack rather than - # echoed back from the inputs: a version input can be a constraint, the - # repository can resolve it differently than expected, and a service tag - # does not carry its patch level. A failing release gate has to be able to - # say "it broke on OpenSearch 3.3.2", not "we asked for 3.3". - # - # Nothing here can fail the job. A probe that comes back empty reports - # "unknown" -- a disabled service is not a broken store. + # Probed from the running stack, not echoed back from the inputs: a + # version input can be a constraint, and a service tag carries no patch + # level. A failing gate has to be able to say "it broke on OpenSearch + # 3.3.2". Nothing here fails the job; an empty probe reports "unknown". - name: Record the stack under test id: stack working-directory: ./_ghamagento @@ -323,15 +279,10 @@ jobs: REDIS="$(probe redis redis-server --version | sed -n 's/.*v=\([0-9][0-9.]*\).*/\1/p' | head -1)" VARNISH="$(probe varnish varnishd -V | sed -n 's/.*varnish-\([0-9][0-9.]*\).*/\1/p' | head -1)" - # Which side owns the page cache, and whether it is actually caching. - # - # Magento defaults to its own built-in cache, and only purges Varnish - # when it is configured as the cache. A Varnish serving every request - # that Magento never invalidates passes every spec here today -- each - # one visits a given URL once -- and fails the first spec that - # revisits a page after changing it, in a way that reads like a - # Magento bug. So the run says it outright rather than leaving it to - # be re-derived from the source every time. + # Which side owns the page cache, and whether it is caching. Magento + # only purges Varnish when Varnish is configured as the cache, and one + # it never invalidates passes every spec that visits a URL once, then + # fails the first that revisits a changed page -- looking like a bug. FPC="$(probe php-fpm bin/magento config:show system/full_page_cache/caching_application | head -1)" case "${FPC}" in 2) FPC="Varnish" ;; @@ -343,8 +294,8 @@ jobs: XCACHE="$(printf '%s' "${HEADERS}" | sed -n 's/^[Xx]-[Mm]agento-[Cc]ache-[Dd]ebug: *//p' | head -1)" CACHECONTROL="$(printf '%s' "${HEADERS}" | sed -n 's/^[Cc]ache-[Cc]ontrol: *//p' | head -1)" - # Only the application versions reach the tests. A spec may reasonably - # branch on those; none should branch on a Redis patch level. + # Only the application versions reach the tests. No spec should branch + # on a Redis patch level. echo "mageos=${MAGEOS:-unknown}" >> $GITHUB_OUTPUT echo "magento=${MAGENTO:-unknown}" >> $GITHUB_OUTPUT @@ -366,20 +317,11 @@ jobs: echo "| Homepage \`X-Magento-Cache-Debug\` | ${XCACHE:-none} |" } >> $GITHUB_STEP_SUMMARY - # A bare setup:install has nothing to buy. The command reindexes itself. - # Streamed in rather than copied: the project directories are owned by the - # container's user. - # Magento has no switch for two-factor authentication. There is no enable - # flag, and leaving twofactorauth/general/force_providers empty does not - # help: ControllerActionPredispatch still routes a fresh admin user to - # tfa/tfa/index, which redirects to tfa/tfa/requestconfig. Disabling the - # module is the only way in. MageOS_PasskeyAuth requires it and registers - # an admin 2FA provider, so both have to go in one command or dependency - # validation refuses it. - # - # The cost is stated rather than hidden: a run with this on does not cover - # admin 2FA. Covering it means driving a TOTP provider from its shared - # secret, which is worth doing, as its own spec. + # Magento has no switch for 2FA: force_providers is empty by default and + # ControllerActionPredispatch still routes a fresh admin user to + # tfa/tfa/index. Disabling the module is the only way in, and + # MageOS_PasskeyAuth requires it, so both go in one command. The cost is + # explicit: a run with this on does not cover admin 2FA. - name: Open the admin to the test suite if: inputs.disable_admin_auth_modules working-directory: ./_ghamagento @@ -389,9 +331,8 @@ jobs: MODULES=() for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do - # module:status exits 0 even for a module that is not installed, so - # its output is the only signal. MageOS_PasskeyAuth is Mage-OS only, - # and this workflow should still work against a Magento install. + # module:status exits 0 for a module that is not installed, so its + # output is the only signal. MageOS_PasskeyAuth is Mage-OS only. if ${WARDEN} env exec -T php-fpm bin/magento module:status "${MODULE}" 2>&1 | grep -q 'does not exist'; then echo "${MODULE} is not installed" else @@ -399,28 +340,27 @@ jobs: fi done - # An array, not a string: module:disable takes the names as separate - # arguments and reads a single space-joined string as one unknown - # module name. Re-running it changes nothing and still exits 0. + # An array, not a string: module:disable reads a space-joined string + # as one unknown module name. Re-running it changes nothing, exits 0. if [ ${#MODULES[@]} -gt 0 ]; then ${WARDEN} env exec -T php-fpm bin/magento module:disable "${MODULES[@]}" fi - # Already the default. Pinned so the suite does not rely on one: it - # gates Magento_AdminAnalytics' usage-data modal, which would - # otherwise cover the dashboard on first sign-in. + # Already the default. Pinned because it gates Magento_AdminAnalytics' + # usage-data modal, which would cover the dashboard on first sign-in. ${WARDEN} env exec -T php-fpm bin/magento config:set admin/usage/enabled 0 - # The admin login CAPTCHA is on by default (admin/captcha/enable 1) in - # after_fail mode, and asks for one after three failed attempts per - # login name -- counted in the captcha_log table, which survives - # across runs against a long-lived store. A suite that asserts a bad - # credential is refused produces exactly those failures, so leaving - # this on lets the negative control poison the positive one, and the - # symptom is an "Incorrect CAPTCHA" that looks nothing like the cause. + # On by default, in after_fail mode, after three failed attempts per + # login name -- counted in captcha_log, which survives across runs + # against a long-lived store. A suite that asserts a bad credential is + # refused makes exactly those failures, and the symptom is an + # "Incorrect CAPTCHA" on a password that is correct. ${WARDEN} env exec -T php-fpm bin/magento config:set admin/captcha/enable 0 ${WARDEN} env exec -T php-fpm bin/magento cache:flush + # A bare setup:install has nothing to buy. The command reindexes itself. + # Streamed in rather than copied: the project directories are owned by the + # container's user. - name: Seed the catalog if: inputs.fixture_profile != '' working-directory: ./_ghamagento @@ -444,9 +384,8 @@ jobs: npm ci npx playwright install --with-deps chromium - # The command arrives through the environment rather than interpolated into - # the script, so its quoting is bash's problem and not the expression - # engine's. + # Through the environment rather than interpolated into the script, so the + # quoting is bash's problem and not the expression engine's. - name: Run the tests working-directory: ${{ env.SUITE }}/${{ inputs.test_directory }} env: @@ -459,14 +398,9 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ inputs.backend_frontname }} run: bash -c "$TEST_COMMAND" - # What the stack was doing when something went wrong. Without this, "the - # store answered 404" is where the investigation stops: the containers go - # away with the runner, and nothing in the log says whether nginx was up, - # whether Varnish had a backend at all, or whether Traefik had a route to - # send the request to. - # - # Nothing in here may fail the job -- it only runs because something else - # already did. + # What the stack was doing when something went wrong: the containers go + # away with the runner, and nothing in the log says whether nginx was up + # or whether Traefik had a route. Nothing here may fail the job. - name: Report what the stack was doing if: failure() working-directory: ./_ghamagento @@ -491,7 +425,7 @@ jobs: echo "::endgroup::" # A failing gate is read by someone deciding whether to ship, so the - # evidence has to outlive the run. + # evidence outlives the run. - name: Upload the test report if: ${{ !cancelled() }} uses: actions/upload-artifact@v4 From 737f9590bbd19010d1c03dd5d7b64d602caf261d Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 08:20:15 -0600 Subject: [PATCH 31/42] refactor(e2e): give the storefront specs a directory of its own The admin specs had admin/ and the storefront specs had the root, so the storefront project had to be defined as "not admin". A spec dropped anywhere outside admin/ joined it silently, including a helper that happened to be named *.spec.ts. Both areas now match positively by their own directory, and each owns its support module: admin/support.ts beside storefront/luma.ts and storefront/support.ts. A spec that lands outside both runs in no project, which is louder than the storefront project adopting it. No test changed. 16 tests in 12 files, same as before. --- _test/demo-package/Test/e2e/README.md | 45 +++++++++++++------ .../Test/e2e/admin/create-category.spec.ts | 2 +- .../Test/e2e/admin/create-customer.spec.ts | 4 +- .../Test/e2e/admin/create-order.spec.ts | 2 +- .../Test/e2e/admin/create-product.spec.ts | 4 +- .../Test/e2e/playwright.config.ts | 5 ++- .../{ => storefront}/customer-account.spec.ts | 2 +- .../{ => storefront}/guest-checkout.spec.ts | 4 +- .../{ => storefront}/hello-magento.spec.ts | 2 +- .../Test/e2e/{ => storefront}/luma.ts | 0 .../e2e/{ => storefront}/product-page.spec.ts | 4 +- .../{storefront.ts => storefront/support.ts} | 0 12 files changed, 47 insertions(+), 27 deletions(-) rename _test/demo-package/Test/e2e/{ => storefront}/customer-account.spec.ts (99%) rename _test/demo-package/Test/e2e/{ => storefront}/guest-checkout.spec.ts (98%) rename _test/demo-package/Test/e2e/{ => storefront}/hello-magento.spec.ts (97%) rename _test/demo-package/Test/e2e/{ => storefront}/luma.ts (100%) rename _test/demo-package/Test/e2e/{ => storefront}/product-page.spec.ts (98%) rename _test/demo-package/Test/e2e/{storefront.ts => storefront/support.ts} (100%) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 7f2c7575..7e3f825f 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -13,10 +13,10 @@ every change to it and runs this suite against the result. | Spec | Needs fixtures | Asserts | | --- | --- | --- | -| `hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | -| `guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | -| `product-page.spec.ts` | yes | the product page's own details, and a cart whose arithmetic adds up | -| `customer-account.spec.ts` | no | register -> signed in -> sign out -> sign in, and a refused credential | +| `storefront/hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | +| `storefront/guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | +| `storefront/product-page.spec.ts` | yes | the product page's own details, and a cart whose arithmetic adds up | +| `storefront/customer-account.spec.ts` | no | register -> signed in -> sign out -> sign in, and a refused credential | | `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | | `admin/product-grid.spec.ts` | yes | the product grid renders through Magento_Ui and filters server-side | | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | @@ -25,11 +25,26 @@ every change to it and runs this suite against the result. | `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid | | `admin/menu-navigation.spec.ts` | no | the admin's own rendered link reaches the product grid, secret key or not | -Storefront selectors live in `luma.ts`, shared by every spec that looks at a -storefront page. A Hyva variant of this suite is that file with a different -map, not a rewrite of the specs. `storefront.ts` holds the behaviour that goes -with them -- choosing whatever options a product requires, and reading the -number out of a rendered price -- because that part is not theme-specific. +Each area owns a directory, and the Playwright project of the same name +matches it: + +``` +fixtures.ts the page fixture both areas use +admin/support.ts admin helpers, selectors, the saved session +admin/*.spec.ts +storefront/luma.ts storefront selectors +storefront/support.ts storefront behaviour +storefront/*.spec.ts +``` + +Storefront selectors live in `storefront/luma.ts`, shared by every spec that +looks at a storefront page. A Hyva variant of this suite is that file with a +different map, not a rewrite of the specs. `storefront/support.ts` holds the +behaviour that goes with them -- choosing whatever options a product requires, +and reading the number out of a rendered price -- because that part is not +theme-specific. Three admin specs import from both, which is the point: an +admin spec that proves a save reached a shopper is looking at a storefront +page, and should read it the way the storefront specs do. ## Running it against a store @@ -40,8 +55,8 @@ npx playwright install --with-deps chromium npm test ``` -`guest-checkout.spec.ts` needs a salable product, which a bare `setup:install` -does not have. Seed one first -- see [Fixtures](#fixtures). +`storefront/guest-checkout.spec.ts` needs a salable product, which a bare +`setup:install` does not have. Seed one first -- see [Fixtures](#fixtures). The admin specs need an admin account and a reachable admin URL. Set `MAGENTO_ADMIN_USER`, `MAGENTO_ADMIN_PASSWORD` and `MAGENTO_ADMIN_FRONTNAME` @@ -76,7 +91,8 @@ login page of Mage-OS 4.0.0: So `#send2` matches two elements and `#pass` matches the invisible one. A spec that uses either waits thirty seconds for a hidden element to become clickable and then reports a timeout, which reads as a broken store rather -than as a selector that found the wrong copy. Everything in `luma.ts` under +than as a selector that found the wrong copy. Everything in +`storefront/luma.ts` under sign-in is scoped to `.login-container`, which holds only the real form. This is the storefront twin of the `#login-form` collision the admin sign-in @@ -118,7 +134,8 @@ Registration has no CAPTCHA: `user_create` appears in `always_for` but not in ### Why a second cart spec -`guest-checkout.spec.ts` walks past the product page and the cart on its way +`storefront/guest-checkout.spec.ts` walks past the product page and the cart +on its way to an order, and it has to -- its subject is the whole path. `product-page` looks closely at both instead, and asserts the thing nothing else does: that the arithmetic holds. Unit price times quantity is the row subtotal, the rows @@ -405,7 +422,7 @@ Three more traps on that page, each of which cost a red run to find: Three admin specs cross into the storefront to prove the save reached a shopper. They do it from a fresh session, by `asShopper(page)` in -`storefront.ts`, and that is not tidiness either. +`storefront/support.ts`, and that is not tidiness either. The admin specs reuse a saved admin session, which is a cookie jar the storefront requests inherit: an `admin` cookie, a PHPSESSID created in the diff --git a/_test/demo-package/Test/e2e/admin/create-category.spec.ts b/_test/demo-package/Test/e2e/admin/create-category.spec.ts index f457cd2c..9286e8b1 100644 --- a/_test/demo-package/Test/e2e/admin/create-category.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-category.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from '../fixtures'; import { adminSelectors, adminUrl } from './support'; -import { categoryUrl, luma } from '../luma'; +import { categoryUrl, luma } from '../storefront/luma'; /** * A category is the other half of the catalog write path, and almost none of diff --git a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts index 4bcacb63..911d459d 100644 --- a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -1,7 +1,7 @@ import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; -import { asShopper } from '../storefront'; -import { luma } from '../luma'; +import { asShopper } from '../storefront/support'; +import { luma } from '../storefront/luma'; /** * Creating a customer exercises a write path the product and category specs diff --git a/_test/demo-package/Test/e2e/admin/create-order.spec.ts b/_test/demo-package/Test/e2e/admin/create-order.spec.ts index 9a230bdb..a65a38b5 100644 --- a/_test/demo-package/Test/e2e/admin/create-order.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -1,7 +1,7 @@ import { type Page, type Request } from '@playwright/test'; import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; -import { parseMoney } from '../storefront'; +import { parseMoney } from '../storefront/support'; /** * Placing an order from the admin, which is how a merchant takes a phone diff --git a/_test/demo-package/Test/e2e/admin/create-product.spec.ts b/_test/demo-package/Test/e2e/admin/create-product.spec.ts index 32f6970b..f3894efe 100644 --- a/_test/demo-package/Test/e2e/admin/create-product.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -1,7 +1,7 @@ import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; -import { luma, productUrl } from '../luma'; -import { asShopper } from '../storefront'; +import { luma, productUrl } from '../storefront/luma'; +import { asShopper } from '../storefront/support'; /** * The spec that crosses the most seams in the application, and the reason the diff --git a/_test/demo-package/Test/e2e/playwright.config.ts b/_test/demo-package/Test/e2e/playwright.config.ts index c2ea40e8..d3b90636 100644 --- a/_test/demo-package/Test/e2e/playwright.config.ts +++ b/_test/demo-package/Test/e2e/playwright.config.ts @@ -50,9 +50,12 @@ export default defineConfig({ testMatch: /admin[\\/]session\.setup\.ts$/, use: { ...devices['Desktop Chrome'] }, }, + // Both areas match positively, by their own directory. A spec that + // lands anywhere else runs in no project at all, which is a louder + // failure than the storefront project silently adopting it. { name: 'storefront', - testIgnore: /admin[\\/]/, + testMatch: /storefront[\\/].*\.spec\.ts$/, use: { ...devices['Desktop Chrome'] }, }, { diff --git a/_test/demo-package/Test/e2e/customer-account.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts similarity index 99% rename from _test/demo-package/Test/e2e/customer-account.spec.ts rename to _test/demo-package/Test/e2e/storefront/customer-account.spec.ts index 0252d9db..fea28fcf 100644 --- a/_test/demo-package/Test/e2e/customer-account.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from './fixtures'; +import { expect, test } from '../fixtures'; import { luma } from './luma'; /** diff --git a/_test/demo-package/Test/e2e/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts similarity index 98% rename from _test/demo-package/Test/e2e/guest-checkout.spec.ts rename to _test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts index d601825c..de84d688 100644 --- a/_test/demo-package/Test/e2e/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts @@ -1,7 +1,7 @@ import { type Page } from '@playwright/test'; -import { expect, test } from './fixtures'; +import { expect, test } from '../fixtures'; import { luma } from './luma'; -import { selectRequiredOptions } from './storefront'; +import { selectRequiredOptions } from './support'; // The deepest path a storefront check can walk: catalog -> product -> cart -> // shipping -> payment -> order. It touches the layered navigation, the price diff --git a/_test/demo-package/Test/e2e/hello-magento.spec.ts b/_test/demo-package/Test/e2e/storefront/hello-magento.spec.ts similarity index 97% rename from _test/demo-package/Test/e2e/hello-magento.spec.ts rename to _test/demo-package/Test/e2e/storefront/hello-magento.spec.ts index e57e856a..9d4ca2b5 100644 --- a/_test/demo-package/Test/e2e/hello-magento.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/hello-magento.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from './fixtures'; +import { expect, test } from '../fixtures'; // A 200 proves very little on its own: the admin login page, a CMS no-route // page and a Magento error page all answer 200 and all carry a header, a diff --git a/_test/demo-package/Test/e2e/luma.ts b/_test/demo-package/Test/e2e/storefront/luma.ts similarity index 100% rename from _test/demo-package/Test/e2e/luma.ts rename to _test/demo-package/Test/e2e/storefront/luma.ts diff --git a/_test/demo-package/Test/e2e/product-page.spec.ts b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts similarity index 98% rename from _test/demo-package/Test/e2e/product-page.spec.ts rename to _test/demo-package/Test/e2e/storefront/product-page.spec.ts index 0a69478c..e341e726 100644 --- a/_test/demo-package/Test/e2e/product-page.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts @@ -1,6 +1,6 @@ -import { expect, test } from './fixtures'; +import { expect, test } from '../fixtures'; import { luma } from './luma'; -import { parseMoney, selectRequiredOptions } from './storefront'; +import { parseMoney, selectRequiredOptions } from './support'; /** * A product page and the cart it fills, asserted properly. diff --git a/_test/demo-package/Test/e2e/storefront.ts b/_test/demo-package/Test/e2e/storefront/support.ts similarity index 100% rename from _test/demo-package/Test/e2e/storefront.ts rename to _test/demo-package/Test/e2e/storefront/support.ts From 92ede2275728431dc3b49daf892bafb464f10190 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 08:25:48 -0600 Subject: [PATCH 32/42] fix(e2e): correct what the profile says about the admin settings The header claimed leaving use_form_key out kept admin CSRF protection on. It is the "Add Secret Key to URLs" setting, and _processUrlKeys validates POST form keys whatever it is set to, so that sentence was wrong about the mechanism. The workflow now sets both settings anyway, so what the comment has to explain is why they are set there and not here. --- _test/demo-package/Test/e2e/fixtures/mageos-e2e.xml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml index b5965c09..d7cb36bc 100644 --- a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml +++ b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml @@ -22,10 +22,12 @@ transport, and nothing here generates customers or orders, so nothing tries to send mail. The smtp/disable config below covers the rest. - Also deliberately absent: small.xml sets admin/security/use_form_key to 0 and - admin_account_sharing to 1. That is reasonable for load testing and wrong - here. A gate that runs against a store with admin CSRF protection disabled is - not testing the store we ship. + Also absent: the two admin settings small.xml carries, + admin/security/use_form_key and admin_account_sharing. The gate does need + both, and the workflow sets them with the reasons written next to them. They + are not here because a fixture profile is not where a gate's store config + belongs -- a suite run against a hand-seeded store would otherwise get a + different store than CI. --> <config xmlns:xi="http://www.w3.org/2001/XInclude"> <profile> From 871b401918ec6b9e22b07fc04ff6b2bdcd35ef74 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 11:07:46 -0600 Subject: [PATCH 33/42] ci(e2e): keep what Magento logged, even when a retry saves the run Playwright exits 0 when a retry passes, so the failure() step that dumps the stack never runs. A rehearsal flaked with a 500 from mui/index/render?namespace=notification_area -- Magento raised its error modal, the modal covered the grid's filter button, and the click timed out. The 500 was in the report; the exception behind it was gone with the containers. This prints var/report and the tails of exception.log and system.log on every run, so the next occurrence arrives with its cause attached. Ten repeats in CI did not reproduce it, and forcing Redis session concurrency to 1 locally produced lock-wait timeouts rather than 500s, so the cause is still unknown. --- .github/workflows/_internal-e2e.yaml | 34 ++++++++++++++++++++++++++++ .github/workflows/e2e-README.md | 7 ++++++ .github/workflows/e2e.yaml | 34 ++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 1a35dd37..00a0e5ef 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -293,6 +293,40 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ env.ADMIN_FRONTNAME }} run: npx playwright test + # A test that fails and then passes on its retry leaves the job green, so + # the failure() step below never runs and whatever Magento threw is lost + # with the containers. That is how one rehearsal recorded a 500 from the + # admin notification area with no exception to go with it. This runs + # either way, and says so when there is nothing to report. + - name: Report what Magento logged + if: ${{ !cancelled() }} + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + in_php() { ${WARDEN} env exec -T php-fpm bash -c "$1" 2>/dev/null || true; } + + REPORTS="$(in_php 'ls -1 var/report 2>/dev/null | head -20')" + if [ -n "${REPORTS}" ]; then + for REPORT in ${REPORTS}; do + echo "::group::var/report/${REPORT}" + in_php "head -c 4000 var/report/${REPORT}" + echo + echo "::endgroup::" + done + else + echo "Magento wrote no exception reports." + fi + + for LOG in exception system; do + LINES="$(in_php "tail -n 50 var/log/${LOG}.log 2>/dev/null")" + if [ -n "${LINES}" ]; then + echo "::group::var/log/${LOG}.log (last 50 lines)" + printf '%s\n' "${LINES}" + echo "::endgroup::" + fi + done + # What the stack was doing when something went wrong: the containers go # away with the runner, and nothing in the log says whether nginx was up # or whether Traefik had a route. Nothing here may fail the job. diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 3aa76bb4..2a0a7c51 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -207,6 +207,13 @@ The step also writes the full stack -- PHP, database, search, Redis and Varnish patch levels, probed from the containers -- to the job summary, so a red gate says what it ran against without anyone reading the log. +A test that fails and then passes on its retry leaves the job green, so a +`failure()` step would never run and whatever Magento threw would go away with +the containers. The run therefore always prints `var/report` and the tails of +`var/log/exception.log` and `system.log`, and says when there is nothing to +report. One rehearsal recorded a `500` from the admin notification area with +no exception to go with it; that is the gap this closes. + ## Fixtures `fixture_profile` is a [performance diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 3663d7f0..5c86428a 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -398,6 +398,40 @@ jobs: MAGENTO_ADMIN_FRONTNAME: ${{ inputs.backend_frontname }} run: bash -c "$TEST_COMMAND" + # A test that fails and then passes on its retry leaves the job green, so + # the failure() step below never runs and whatever Magento threw is lost + # with the containers. That is how one rehearsal recorded a 500 from the + # admin notification area with no exception to go with it. This runs + # either way, and says so when there is nothing to report. + - name: Report what Magento logged + if: ${{ !cancelled() }} + working-directory: ./_ghamagento + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + in_php() { ${WARDEN} env exec -T php-fpm bash -c "$1" 2>/dev/null || true; } + + REPORTS="$(in_php 'ls -1 var/report 2>/dev/null | head -20')" + if [ -n "${REPORTS}" ]; then + for REPORT in ${REPORTS}; do + echo "::group::var/report/${REPORT}" + in_php "head -c 4000 var/report/${REPORT}" + echo + echo "::endgroup::" + done + else + echo "Magento wrote no exception reports." + fi + + for LOG in exception system; do + LINES="$(in_php "tail -n 50 var/log/${LOG}.log 2>/dev/null")" + if [ -n "${LINES}" ]; then + echo "::group::var/log/${LOG}.log (last 50 lines)" + printf '%s\n' "${LINES}" + echo "::endgroup::" + fi + done + # What the stack was doing when something went wrong: the containers go # away with the runner, and nothing in the log says whether nginx was up # or whether Traefik had a route. Nothing here may fail the job. From f9e17ec9acc988e79aac931b8d57ffec076af694 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 11:08:53 -0600 Subject: [PATCH 34/42] ci(e2e): read system.log by severity, not by tail Any Magento install writes hundreds of INFO "Broken reference" lines, so a plain tail would print those on every green run and bury the entry worth reading. exception.log needs no filter -- nothing but exceptions goes there. --- .github/workflows/_internal-e2e.yaml | 24 ++++++++++++++++-------- .github/workflows/e2e.yaml | 24 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 00a0e5ef..4d507d9d 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -318,14 +318,22 @@ jobs: echo "Magento wrote no exception reports." fi - for LOG in exception system; do - LINES="$(in_php "tail -n 50 var/log/${LOG}.log 2>/dev/null")" - if [ -n "${LINES}" ]; then - echo "::group::var/log/${LOG}.log (last 50 lines)" - printf '%s\n' "${LINES}" - echo "::endgroup::" - fi - done + EXCEPTIONS="$(in_php 'tail -n 50 var/log/exception.log 2>/dev/null')" + if [ -n "${EXCEPTIONS}" ]; then + echo "::group::var/log/exception.log (last 50 lines)" + printf '%s\n' "${EXCEPTIONS}" + echo "::endgroup::" + fi + + # Severity-filtered: system.log is mostly INFO "Broken reference" + # lines on any Magento install, and printing those every run would + # bury the one entry worth reading. + ERRORS="$(in_php 'grep -hE "\.(ERROR|CRITICAL|ALERT|EMERGENCY):" var/log/system.log 2>/dev/null | tail -n 50')" + if [ -n "${ERRORS}" ]; then + echo "::group::var/log/system.log (errors only)" + printf '%s\n' "${ERRORS}" + echo "::endgroup::" + fi # What the stack was doing when something went wrong: the containers go # away with the runner, and nothing in the log says whether nginx was up diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 5c86428a..5e388412 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -423,14 +423,22 @@ jobs: echo "Magento wrote no exception reports." fi - for LOG in exception system; do - LINES="$(in_php "tail -n 50 var/log/${LOG}.log 2>/dev/null")" - if [ -n "${LINES}" ]; then - echo "::group::var/log/${LOG}.log (last 50 lines)" - printf '%s\n' "${LINES}" - echo "::endgroup::" - fi - done + EXCEPTIONS="$(in_php 'tail -n 50 var/log/exception.log 2>/dev/null')" + if [ -n "${EXCEPTIONS}" ]; then + echo "::group::var/log/exception.log (last 50 lines)" + printf '%s\n' "${EXCEPTIONS}" + echo "::endgroup::" + fi + + # Severity-filtered: system.log is mostly INFO "Broken reference" + # lines on any Magento install, and printing those every run would + # bury the one entry worth reading. + ERRORS="$(in_php 'grep -hE "\.(ERROR|CRITICAL|ALERT|EMERGENCY):" var/log/system.log 2>/dev/null | tail -n 50')" + if [ -n "${ERRORS}" ]; then + echo "::group::var/log/system.log (errors only)" + printf '%s\n' "${ERRORS}" + echo "::endgroup::" + fi # What the stack was doing when something went wrong: the containers go # away with the runner, and nothing in the log says whether nginx was up From c85005af4ca37f9850143a67bd3d5605816aa052 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 11:14:14 -0600 Subject: [PATCH 35/42] fix(e2e): do not put a double hyphen inside an XML comment 92ede22 rewrote the profile's header and used "--" as punctuation, which is not legal inside an XML comment. simplexml then refused the whole profile and the seeding step failed with a libxml warning that prints the comment text where the message should be, naming only "line: 29". The rehearsal caught it on the step that owns seeding, before any spec ran, which is what the separate steps are for. --- _test/demo-package/Test/e2e/fixtures/mageos-e2e.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml index d7cb36bc..a673cf0c 100644 --- a/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml +++ b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml @@ -26,7 +26,7 @@ admin/security/use_form_key and admin_account_sharing. The gate does need both, and the workflow sets them with the reasons written next to them. They are not here because a fixture profile is not where a gate's store config - belongs -- a suite run against a hand-seeded store would otherwise get a + belongs; a suite run against a hand-seeded store would otherwise get a different store than CI. --> <config xmlns:xi="http://www.w3.org/2001/XInclude"> From da440183fcb937a3cc5765a4f3c17b2b302ca187 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 12:25:37 -0600 Subject: [PATCH 36/42] test(e2e): ask the search engine a question The gate installs OpenSearch, probes its version and prints it in the run summary, and no test ever sent it a query. A release that shipped a client that could not reach the engine, an unbuilt catalogsearch_fulltext index or a changed result template passed all sixteen other tests. The spec reads a sku off a product page and searches for that, so it cannot go stale when the fixture profile renames anything, and it asserts the first result rather than the only one: a sku with a space in it tokenises into an OR query and returns the catalogue, while the exact match ranks first either way. The no-results test is the control that gives the first one its meaning. Two things the specs found while being written, both in the README: - The absent term has to be one nonsense token. "zzz-mageos-no-such-product-zzz" splits on the hyphens and matches everything on "product". - Luma's search button is dead ~400ms after typing stops: form-mini's debounced input handler disables it and the re-enable does not stick. Measured with it disabled, Enter submits and a click does not, forced or not. The spec types and presses Enter. --- _test/demo-package/Test/e2e/README.md | 31 ++++ .../demo-package/Test/e2e/storefront/luma.ts | 14 ++ .../Test/e2e/storefront/search.spec.ts | 140 ++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 _test/demo-package/Test/e2e/storefront/search.spec.ts diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 7e3f825f..7934a0ef 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -17,6 +17,7 @@ every change to it and runs this suite against the result. | `storefront/guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | | `storefront/product-page.spec.ts` | yes | the product page's own details, and a cart whose arithmetic adds up | | `storefront/customer-account.spec.ts` | no | register -> signed in -> sign out -> sign in, and a refused credential | +| `storefront/search.spec.ts` | yes | a sku read off a product page is found by full-text search, and an absent term is not | | `admin/login.spec.ts` | no | the admin sign-in form refuses a bad credential and accepts a good one | | `admin/product-grid.spec.ts` | yes | the product grid renders through Magento_Ui and filters server-side | | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | @@ -121,6 +122,36 @@ A password needs 8 characters and 3 of the 4 character classes (`customer/password/minimum_password_length`, `required_character_classes_number`). +### Luma's quick search can only be submitted by keyboard + +`Magento_Search`'s `form-mini` widget binds a `_.debounce`d handler to the +search field's `input` event. That handler sets `submitBtn.disabled = true` +and the re-enable beside it does not stick, so roughly 400ms after typing +stops the search button is dead for the rest of the page's life. + +Measured against a seeded store, with the button already disabled: + +| submission | result | +| --- | --- | +| `press('Enter')` | submits | +| `click()` on the button | does not submit | +| `click({ force: true })` | does not submit | +| `form.requestSubmit()` | submits | + +So the spec types and presses Enter. Clicking the button works only inside +that 400ms window, which is why doing it looks fine on an idle machine and +fails on a busy one. Worth reporting upstream: a shopper who types, pauses, +then reaches for the button gets nothing. + +### An absent search term has to be one token + +The query is tokenised and matched as an OR, so a hyphenated phrase is not an +absent term. `zzz-mageos-no-such-product-zzz` splits and matches the entire +catalogue on `product` alone -- which is how the no-results test failed the +first time it ran. The term is a single nonsense token, and fixed rather than +random, because a gate that reports a different failure every run is one +nobody can triage. + ### The storefront CAPTCHA is on, for two forms `customer/captcha/enable` is `1`, for `user_login` and `user_forgotpassword`, diff --git a/_test/demo-package/Test/e2e/storefront/luma.ts b/_test/demo-package/Test/e2e/storefront/luma.ts index b7ffe6f6..ab3121aa 100644 --- a/_test/demo-package/Test/e2e/storefront/luma.ts +++ b/_test/demo-package/Test/e2e/storefront/luma.ts @@ -20,6 +20,20 @@ export const luma = { // starts as the parent sku and is rewritten by JS once an option is // chosen, so a spec asserts that it is there and not what it says. productSku: '.product.attribute.sku .value', + + // Quick search, as Luma renders it in the header. Typing into it fires no + // XHR on a default store -- measured: only Magento_Search/js/form-mini.js + // loads -- so a search spec has no suggest request to wait for. + searchInput: '#search', + // The results count, as the toolbar renders it ("1 Item", "Items 1-12 of + // 41"). One toolbar renders on a single page of results and two when + // there is a second page, so this is read through .first(). + searchResultsCount: '.toolbar-amount', + // The empty-result message. On a no-results page .products.wrapper is not + // rendered at all, which is why the result count is read through it: + // unscoped, .product-item-info matches 2 elements for one result and 1 + // element for none. + searchNoResults: '.message.notice', // Luma's availability block. `.available` is the in-stock variant -- the // out-of-stock one is `.unavailable` -- so the selector matching at all // is the assertion, and a product the price index has not reached renders diff --git a/_test/demo-package/Test/e2e/storefront/search.spec.ts b/_test/demo-package/Test/e2e/storefront/search.spec.ts new file mode 100644 index 00000000..3b948679 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/search.spec.ts @@ -0,0 +1,140 @@ +import { expect, test } from '../fixtures'; +import { luma } from './luma'; + +/** + * Full-text search: the one service this gate installs and never questioned. + * + * The workflow stands OpenSearch up, probes its version and prints it in the + * run summary -- and until this spec, no test ever sent it a query. A release + * that shipped a client which could not speak to the engine, an unbuilt + * catalogsearch_fulltext index, or a changed result template passed all + * sixteen of the other tests here. + * + * It searches for a sku it reads off a product page rather than one written + * in this file. That costs two navigations and buys two things: the spec + * cannot go stale when the fixture profile changes its naming, and the + * assertion becomes one about this release rather than this catalogue -- + * "the catalogue has this product, so search can find it". + * + * It asserts the *first* result rather than the only one. A sku with a space + * in it tokenises into an OR query: measured on a seeded store, the sku + * "Configurable Product 1" returns 41 results while "product_dynamic_5" + * returns exactly 1. What holds for both is that the exact match ranks first, + * so that is what gets checked -- which also means relevance ordering is + * covered, and no assertion here depends on which product the catalogue + * happens to list first. + * + * The no-results test is not decoration. A search that ignored its query and + * listed the whole catalogue would satisfy every assertion in the first test. + * It is the control that gives the first one its meaning. + */ + +// A term no catalogue should match: one token, no separators, no word a +// product could carry. The query is tokenised and matched as an OR, so a +// hyphenated phrase is not an absent term -- "zzz-mageos-no-such-product-zzz" +// splits and matches the whole catalogue on "product" alone, which this spec +// found the first time it ran. Fixed rather than random, because a gate that +// reports a different failure every run is one nobody can triage. +const absentTerm = 'zzzqxvnomatch'; + +test.describe('Storefront search', () => { + test('finds a product by the sku the catalogue gave it', { tag: ['@catalog', '@search'] }, async ({ page }) => { + let sku = ''; + let productName = ''; + + await test.step('the catalogue offers a product to look for', async () => { + await page.goto('/'); + + const category = page.locator(luma.navCategory).first(); + await expect(category, 'the fixture categories should appear in the main navigation').toBeVisible(); + await category.click(); + await expect(page.locator('body')).toHaveClass(/catalog-category-view/); + + const firstProduct = page + .locator(luma.productList) + .locator(luma.productItem) + .first() + .locator(luma.productItemLink); + await expect(firstProduct, 'the category should list at least one product').toBeVisible(); + productName = ((await firstProduct.textContent()) ?? '').trim(); + await firstProduct.click(); + + const skuValue = page.locator(luma.productSku); + await expect(skuValue, 'a product page should render its sku').toBeVisible(); + sku = ((await skuValue.textContent()) ?? '').trim(); + expect(sku, 'the sku should not be empty').not.toBe(''); + }); + + await test.step('the search form takes that sku', async () => { + // Through the form rather than by building the url: the form is + // part of what a storefront has to render, and a release that + // breaks its route should fail here rather than silently never be + // tested. + await page.goto('/'); + + const search = page.locator(luma.searchInput); + await expect(search, 'Luma should render its quick-search field').toBeVisible(); + await search.fill(sku); + + // By keyboard, not by clicking the button, and that is a measured + // decision rather than a preference. Magento_Search's form-mini + // widget runs a debounced 'input' handler about 400ms after + // typing stops, which sets submitBtn.disabled = true; the + // re-enable alongside it does not stick, so from then on the + // button is dead. Measured against this store, with the button + // already disabled: Enter submits, a click does not, and not even + // a forced click does. Enter works whether the widget has settled + // or not, so it is the only submission this spec can rely on. + await search.press('Enter'); + + await expect(page).toHaveURL(/catalogsearch\/result/); + await expect(page.locator('body')).toHaveClass(/catalogsearch-result-index/); + await expect( + page.locator(luma.pageTitle), + 'the results page should name what was searched for', + ).toContainText(sku); + }); + + await test.step('the product is the first result', async () => { + const results = page.locator(luma.productList).locator(luma.productItem); + await expect( + results, + 'searching a sku the catalogue just showed should return at least one result', + ).not.toHaveCount(0); + + await expect( + page.locator(luma.searchResultsCount).first(), + 'the toolbar should report how many results there were', + ).not.toBeEmpty(); + + const top = results.first().locator(luma.productItemLink); + await expect(top, 'the exact match should rank first').toHaveText(productName); + + await top.click(); + await expect( + page.locator(luma.productSku), + 'the result should lead back to the product whose sku was searched', + ).toHaveText(sku); + }); + }); + + test('returns no results for a term the catalogue does not contain', { tag: ['@catalog', '@search'] }, async ({ page }) => { + await page.goto(`/catalogsearch/result/?q=${encodeURIComponent(absentTerm)}`); + + // Still the search controller, not an error page or a redirect to the + // homepage: an empty result is a normal answer and has to look like + // one. + await expect(page.locator('body')).toHaveClass(/catalogsearch-result-index/); + await expect( + page.locator(luma.searchNoResults), + 'an unmatched term should be reported, not answered with products', + ).toContainText('Your search returned no results.'); + + // The list block is not rendered at all on this page, so this counts + // zero rather than finding an empty wrapper. + await expect( + page.locator(luma.productList).locator(luma.productItem), + 'nothing should be listed for a term nothing matches', + ).toHaveCount(0); + }); +}); From 3a2d339e52e2236af0834b4db1068e339548bd75 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 13:40:10 -0600 Subject: [PATCH 37/42] test(e2e): buy something as a signed-in customer The suite could register an account and it could place an order, but never as the same person. This covers the path between them: an address saved through the account's own form, a checkout that arrives already knowing who is shopping and which address to ship to, and the order showing up in My Orders afterwards. Three measured differences from the guest path, each an assertion the guest spec cannot make: #customer-email absent from the page, not hidden #co-shipping-form present and hidden; the saved address is preselected a.order-number a link to the order, where a guest gets a bare span That link is the order-to-customer association, so the spec follows it: the increment id the success page gave it is asserted again on My Orders and on the order page, together with the sku read off the product page before it was added to the cart. The shared pieces move into storefront/support.ts -- the shopper, the password, the address, the address-form fill and the registration -- so guest-checkout and customer-account now use them too. One new entry on the page fixture's ignore list: a signed-in shopper's quote is carts/mine rather than guest-carts/{maskedId}, so placing the order leaves the same post-order 404 on a different path. Measured over six runs; the estimate-shipping-methods counterpart never appeared and is deliberately not ignored. Local run: 19 passed. The new spec 5/5 at --retries=0, ~10.5s each. --- _test/demo-package/Test/e2e/README.md | 68 +++++- _test/demo-package/Test/e2e/fixtures.ts | 22 +- .../e2e/storefront/customer-account.spec.ts | 40 +--- .../e2e/storefront/customer-checkout.spec.ts | 220 ++++++++++++++++++ .../e2e/storefront/guest-checkout.spec.ts | 28 +-- .../demo-package/Test/e2e/storefront/luma.ts | 41 ++++ .../Test/e2e/storefront/search.spec.ts | 4 +- .../Test/e2e/storefront/support.ts | 105 ++++++++- 8 files changed, 448 insertions(+), 80 deletions(-) create mode 100644 _test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 7934a0ef..4914c954 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -15,6 +15,7 @@ every change to it and runs this suite against the result. | --- | --- | --- | | `storefront/hello-magento.spec.ts` | no | the Luma homepage renders with static content deployed | | `storefront/guest-checkout.spec.ts` | yes | catalog -> product -> cart -> shipping -> payment -> order | +| `storefront/customer-checkout.spec.ts` | yes | address book -> preselected address -> order -> My Orders -> the order page | | `storefront/product-page.spec.ts` | yes | the product page's own details, and a cart whose arithmetic adds up | | `storefront/customer-account.spec.ts` | no | register -> signed in -> sign out -> sign in, and a refused credential | | `storefront/search.spec.ts` | yes | a sku read off a product page is found by full-text search, and an absent term is not | @@ -42,8 +43,8 @@ Storefront selectors live in `storefront/luma.ts`, shared by every spec that looks at a storefront page. A Hyva variant of this suite is that file with a different map, not a rewrite of the specs. `storefront/support.ts` holds the behaviour that goes with them -- choosing whatever options a product requires, -and reading the number out of a rendered price -- because that part is not -theme-specific. Three admin specs import from both, which is the point: an +reading the number out of a rendered price, registering an account, filling an +address form -- because that part is not theme-specific. Three admin specs import from both, which is the point: an admin spec that proves a save reached a shopper is looking at a storefront page, and should read it the way the storefront specs do. @@ -163,6 +164,44 @@ same reason. Registration has no CAPTCHA: `user_create` appears in `always_for` but not in `customer/captcha/forms`, and the `forms` list is what decides. +### What a signed-in checkout sees that a guest does not + +`storefront/customer-checkout.spec.ts` is not the guest spec with a session +attached. Checkout renders differently for someone it knows, and all three +differences below were measured on this store rather than assumed -- each one +is an assertion the guest spec cannot make: + +| | guest | signed in | +| --- | --- | --- | +| email | `#customer-email`, the first field to fill | not in the page at all | +| address | `#co-shipping-form`, empty | the default address, preselected; the form is in the DOM but hidden | +| success page | the increment id in a bare `<span>` | `a.order-number`, linking to the order | + +So the email check is `toHaveCount(0)` and the address-form check is +`not.toBeVisible()`. Neither could be the other way round: the form *is* +present -- it belongs to the New Address popup -- and the email field is +absent rather than hidden. + +The order link is what the rest of the spec rests on. A guest order is +attached to an email address and a signed-in one to a customer id, and that +association is why the order then appears in My Orders and opens from it. The +spec carries the increment id the success page gave it to both of those pages, +so what it proves is that one order moved through, not that three pages each +rendered something plausible. + +One selector trap on the way: the My Orders grid and the order's own items +table are both `#my-orders-table`. `sales_order_history.phtml` and +`order_items.phtml` give them the same id, on different pages. The grid is +therefore addressed through its cells (`td.col.id`, `td.col.status`) and the +order through `.table-order-items`. + +The first address a customer saves becomes the default for billing *and* +shipping, which is what lets checkout preselect it -- an account with no +address gets the empty form instead, which is the guest spec's path again. +The spec also asserts the new-address form arrives carrying the customer's +name before it types anything into it: a form reading the wrong entity saves +the address either way, so nothing else would notice. + ### Why a second cart spec `storefront/guest-checkout.spec.ts` walks past the product page and the cart @@ -751,15 +790,20 @@ element's own values and fatals with `Cannot access offset of type string on string`. `small.xml` carries four entries, so upstream never sees it. Keep at least two in the `<configs>` block. -## What the checkout spec does not cover +## What the checkout specs do not cover + +A real payment gateway, taxes, discounts, multi-address shipping, and the +order's life after it is placed -- invoice, shipment, credit memo. Each wants +fixtures or credentials of its own, and none of them is on the path between +"we tagged a release" and "a shopper can buy something". -Registered-customer checkout, a real payment gateway, taxes, discounts and -multi-address shipping. Each wants fixtures of its own, and none of them is on -the path between "we tagged a release" and "a shopper can buy something". +Both ways of buying are covered: `guest-checkout` as a visitor and +`customer-checkout` as a shopper with an account, an address book entry and an +order history. `admin/create-order` covers the third front end onto the same +quote model, carrier pool and payment pool. -Two of those gaps are now smaller from the other side. `customer-account` -covers the account itself -- registration, the session it opens, sign-out and -sign-in -- without checking out as that customer, and `admin/create-order` -places an order against a quote built in the admin, which is the same quote -model, carrier pool and payment pool through a different front end. What is -still missing is a shopper who signs in and then buys something. +The nearest remaining gap is the order state machine. Every order this suite +places stays Pending, because Check / Money order is the only payment method +on a store with no gateway credentials, and nothing here invoices or ships +one. An invoice-and-ship spec against the order `admin/create-order` already +places would cover it without needing a single new fixture. diff --git a/_test/demo-package/Test/e2e/fixtures.ts b/_test/demo-package/Test/e2e/fixtures.ts index ef182ec8..18460917 100644 --- a/_test/demo-package/Test/e2e/fixtures.ts +++ b/_test/demo-package/Test/e2e/fixtures.ts @@ -71,15 +71,16 @@ const ignoredConsole: RegExp[] = [/^Failed to load resource/]; const ignoredPageErrors: RegExp[] = [/^Transition was aborted because of invalid state\./]; /** - * HTTP responses that are not findings. Two entries, and they are the same - * phenomenon: a request Magento's checkout issues against the quote that - * placing the order has just consumed. + * HTTP responses that are not findings. Every entry is the same phenomenon: a + * request Magento's checkout issues against the quote that placing the order + * has just consumed. * * The masked id of a guest cart stops resolving the moment the quote becomes - * an order, so anything still in flight -- or fired by a component reacting to - * the last change -- comes back 404. Measured on Mage-OS 4.0.0, by logging - * every /rest/ response with its offset from the start of the test and - * repeating the checkout spec: + * an order, and a signed-in shopper's carts/mine stops resolving for the same + * reason -- there is no active quote left to be anyone's. So anything still in + * flight -- or fired by a component reacting to the last change -- comes back + * 404. Measured on Mage-OS 4.0.0, by logging every /rest/ response with its + * offset from the start of the test and repeating the checkout specs: * * +10164ms 200 POST .../payment-information * +10645ms 404 GET .../totals (+481ms) @@ -92,7 +93,7 @@ const ignoredPageErrors: RegExp[] = [/^Transition was aborted because of invalid * success page by then and nothing is broken. * * Each entry is scoped to one path and one method and one status, rather than - * to 404s, to /rest/ 404s, or to /guest-carts/ 404s. That matters: a cart that + * to 404s, to /rest/ 404s, or to cart 404s. That matters: a cart that * 404s while the shopper is still checking out has to stay a finding. It would * also break the spec's own assertions -- no totals, no order -- which is what * makes ignores this narrow safe to carry. @@ -100,6 +101,11 @@ const ignoredPageErrors: RegExp[] = [/^Transition was aborted because of invalid const ignoredHttp: RegExp[] = [ /^404 GET xhr \/rest\/\S+\/guest-carts\/\w+\/totals/, /^404 POST xhr \/rest\/\S+\/guest-carts\/\w+\/estimate-shipping-methods/, + // The signed-in shopper's quote, same race on a different resource. + // Measured over six runs of customer-checkout.spec.ts: this is the only + // variant that appeared, so the estimate-shipping-methods counterpart is + // deliberately not ignored for carts/mine until something sees it. + /^404 GET xhr \/rest\/\S+\/carts\/mine\/totals/, ]; const logFile = path.resolve(__dirname, 'test-results/js-errors.jsonl'); diff --git a/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts index fea28fcf..2812bf74 100644 --- a/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts @@ -1,5 +1,6 @@ import { expect, test } from '../fixtures'; import { luma } from './luma'; +import { customerPassword, newShopper, registerCustomer } from './support'; /** * The storefront half of having customers: register, sign out, sign back in. @@ -15,9 +16,8 @@ import { luma } from './luma'; * Three things about the store this spec relies on, each read from the shipped * configuration rather than assumed: * - * - A password needs 8 characters and 3 of the 4 character classes - * (customer/password/minimum_password_length, - * required_character_classes_number). The one below has all four. + * - A password needs 8 characters and 3 of the 4 character classes. See + * customerPassword in support.ts. * - Registration signs the customer in. CreatePost calls * setCustomerDataAsLoggedIn unless customer/create_account/confirm is set, * and it is 0. So the login page is only reachable after signing out -- @@ -32,40 +32,12 @@ import { luma } from './luma'; * customer/captcha/forms. */ -const password = 'Mage0s-E2E-pass1'; - -function shopper() { - const stamp = Date.now(); - - return { - firstName: 'Mage-OS', - lastName: `Shopper ${stamp}`, - email: `mageos-e2e-shopper-${stamp}@example.test`, - }; -} - test.describe('Storefront customer account', () => { test('creates an account and signs back into it', { tag: ['@customer'] }, async ({ page }) => { - const customer = shopper(); + const customer = newShopper(); await test.step('the registration form accepts a new account', async () => { - const response = await page.goto('/customer/account/create/'); - - expect(response?.status(), 'the registration page should be served').toBe(200); - await expect(page.locator('body')).toHaveClass(/customer-account-create/); - - await page.fill(luma.registerFirstName, customer.firstName); - await page.fill(luma.registerLastName, customer.lastName); - await page.fill(luma.registerEmail, customer.email); - await page.fill(luma.registerPassword, password); - await page.fill(luma.registerPasswordConfirm, password); - - // Read back before submitting. A form that silently dropped a - // field fails here, where the cause is visible, rather than as a - // validation error whose text is about something else. - await expect(page.locator(luma.registerEmail)).toHaveValue(customer.email); - - await page.locator(luma.registerSubmit).click(); + await registerCustomer(page, customer); }); await test.step('registering signs the customer in', async () => { @@ -110,7 +82,7 @@ test.describe('Storefront customer account', () => { await expect(page.locator(luma.loginContainer)).toBeVisible(); await page.fill(luma.loginEmail, customer.email); - await page.fill(luma.loginPassword, password); + await page.fill(luma.loginPassword, customerPassword); await page.locator(luma.loginSubmit).click(); await expect(page).toHaveURL(/\/customer\/account\/?$/); diff --git a/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts new file mode 100644 index 00000000..d7ff6cea --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts @@ -0,0 +1,220 @@ +import { expect, test } from '../fixtures'; +import { luma } from './luma'; +import { + fillAddressFields, + newShopper, + registerCustomer, + selectRequiredOptions, + shopperAddress, +} from './support'; + +/** + * Checkout as a signed-in customer, which is not the guest path with a + * session attached. + * + * guest-checkout.spec.ts already walks catalog -> cart -> shipping -> payment + * -> order, so this spec is written around the four things that only happen + * when the shopper has an account, each measured on this store rather than + * assumed: + * + * - The address book. A customer saves an address through + * Magento_Customer's own form, and the first one saved becomes the default + * for billing and shipping. Nothing else in this suite touches + * customer_address_entity from the storefront. + * - Checkout reading it. The saved address arrives preselected and the email + * step is not rendered at all -- #customer-email is not in the page, where + * a guest gets it as the first thing to fill. So checkout is proving it + * knows who is shopping, which is a different code path from the guest + * quote entirely. + * - The order belonging to someone. A guest order is attached to an email + * address; this one is attached to a customer id, and that association is + * what makes the next two assertions possible. + * - The account keeping it. My Orders lists the increment id, and the order + * page renders the sku that was bought. A release where orders place but do + * not appear in the customer's account passes every other test here. + * + * It asserts the increment id the success page gave it on all three pages, so + * what is being checked is that one order moved through, not that each page + * renders something plausible. + */ + +test.describe('Signed-in checkout', () => { + test( + 'places an order on a saved address and keeps it in the account', + { tag: ['@checkout', '@customer'] }, + async ({ page }) => { + const customer = newShopper(); + let sku = ''; + let productName = ''; + let orderNumber = ''; + + await test.step('a shopper has an account', async () => { + await registerCustomer(page, customer); + + // Registration signs the customer in, so there is no sign-in + // step here. customer-account.spec.ts owns the form itself; + // this only needs the session it opens. + await expect(page).toHaveURL(/\/customer\/account\/?$/); + await expect(page.locator(luma.successMessage)).toContainText( + 'Thank you for registering with', + ); + }); + + await test.step('the address book takes a shipping address', async () => { + await page.goto('/customer/address/new/'); + await expect(page.locator('body')).toHaveClass(/customer-address-form/); + + const form = page.locator(luma.addressForm); + + // The form arrives knowing whose it is. Asserted before + // anything is typed: a new-address form that does not carry + // the customer's name is reading the wrong entity, and that + // would otherwise be invisible -- the address saves either + // way. + await expect( + form.locator(luma.registerFirstName), + 'the account form should prefill the customer name', + ).toHaveValue(customer.firstName); + await expect(form.locator(luma.registerLastName)).toHaveValue(customer.lastName); + + await fillAddressFields(form); + await page.locator(luma.addressSubmit).click(); + + await expect(page.locator('body')).toHaveClass(/customer-address-index/); + await expect(page.locator(luma.successMessage)).toContainText('You saved the address.'); + + // Read back out of the database, through the Address Book's + // own rendering of it. The first address a customer saves is + // made default for billing and shipping, which is why + // checkout can preselect it below. + const defaultBilling = page.locator(luma.defaultBillingAddress); + await expect( + defaultBilling, + 'the first saved address should become the default billing address', + ).toContainText(shopperAddress.street); + await expect(defaultBilling).toContainText(shopperAddress.city); + }); + + await test.step('the signed-in shopper fills a cart', async () => { + await page.goto('/'); + + const category = page.locator(luma.navCategory).first(); + await expect(category, 'the fixture categories should appear in the main navigation').toBeVisible(); + await category.click(); + await page.locator(luma.productItemLink).first().click(); + + await expect(page.locator('body')).toHaveClass(/catalog-product-view/); + productName = ((await page.locator(luma.pageTitle).textContent()) ?? '').trim(); + sku = ((await page.locator(luma.productSku).textContent()) ?? '').trim(); + expect(sku, 'a product page should render a sku').not.toBe(''); + + await selectRequiredOptions(page); + await page.locator(luma.addToCart).click(); + + await expect(page.locator(luma.cartSuccess)).toContainText('to your shopping cart'); + // The counter comes from customer-data, which for a signed-in + // shopper is a different section payload than a guest's. + await expect(page.locator(luma.minicartCounter)).toHaveText('1'); + }); + + await test.step('checkout already knows the shopper and the address', async () => { + await page.goto('/checkout/'); + + // Not a visibility check: for a signed-in shopper the email + // step is not rendered at all. Measured on this store, zero + // copies of it in the page, where a guest gets one. + await expect( + page.locator(luma.checkoutEmail), + 'checkout should not ask a signed-in customer for an email address', + ).toHaveCount(0); + + const selected = page.locator(luma.checkoutSelectedAddress); + await expect( + selected, + 'the default address should arrive preselected, not as an empty form', + ).toBeVisible(); + await expect(selected).toContainText(shopperAddress.street); + await expect(selected).toContainText(shopperAddress.postcode); + + // The new-address form is in the DOM and hidden -- it is the + // New Address popup. Hidden is the assertion; absent would be + // wrong and present would mean nothing. + await expect( + page.locator(luma.shippingForm), + 'a shopper with a saved address should not be shown an empty address form', + ).not.toBeVisible(); + + const flatRate = page.locator(luma.shippingMethod); + await expect(flatRate, 'Flat Rate should be offered for the saved address').toBeVisible(); + await flatRate.check(); + await page.locator(luma.nextButton).click(); + }); + + await test.step('the payment step places the order', async () => { + await expect(page.locator(luma.paymentSection)).toBeVisible(); + + // The recap the payment step renders, which is the server's + // view of the address the quote now carries rather than the + // selection made a moment ago. + await expect(page.locator(luma.checkoutShipTo).first()).toContainText(shopperAddress.street); + + await expect( + page.locator('input[value="checkmo"]'), + 'Check / Money order should be available', + ).toBeChecked(); + await page.locator(luma.placeOrder).click(); + }); + + await test.step('the order confirms with a link to itself', async () => { + await expect(page).toHaveURL(/checkout\/onepage\/success/); + await expect(page.locator(luma.successPageTitle)).toContainText('Thank you for your purchase'); + + // A guest gets a bare span here. A customer who can open the + // order gets a link to it, and that link is the association + // between the order and the account being asserted -- so the + // href is checked, not just the digits. + const number = page.locator(luma.successOrderNumber); + await expect(number, 'a signed-in shopper should get a link to the order').toBeVisible(); + await expect(number).toHaveAttribute('href', /sales\/order\/view\/order_id\/\d+/); + + orderNumber = ((await number.textContent()) ?? '').trim(); + expect(orderNumber, 'the success page should name an increment id').toMatch(/^\d{9}$/); + }); + + await test.step('My Orders lists the order', async () => { + await page.goto('/sales/order/history/'); + await expect(page.locator('body')).toHaveClass(/sales-order-history/); + + // One row, because the account was created in this test: a + // grid that showed another customer's orders would be a + // serious defect and this is where it would show. + const rows = page.locator(luma.orderHistoryRow); + await expect(rows, 'a new account should list exactly the order it just placed').toHaveCount(1); + + const row = rows.first(); + await expect(row.locator(luma.orderHistoryId)).toHaveText(orderNumber); + await expect( + row.locator(luma.orderHistoryStatus), + 'a Check / Money order order should be Pending', + ).toHaveText('Pending'); + + await row.locator(luma.orderHistoryView).click(); + }); + + await test.step('the order page renders what was bought', async () => { + await expect(page.locator('body')).toHaveClass(/sales-order-view/); + await expect(page.locator(luma.pageTitle)).toContainText(orderNumber); + await expect(page.locator(luma.orderStatus)).toHaveText('Pending'); + + // The sku read off the product page before it was added to + // the cart: the catalogue, the quote and the order all + // agreeing on which product this was. + await expect( + page.locator(luma.orderItemSku), + 'the order should carry the sku that was added to the cart', + ).toHaveText(sku); + await expect(page.locator(luma.orderItemName)).toContainText(productName); + }); + }, + ); +}); diff --git a/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts index de84d688..3b790e0b 100644 --- a/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts @@ -1,7 +1,7 @@ import { type Page } from '@playwright/test'; import { expect, test } from '../fixtures'; import { luma } from './luma'; -import { selectRequiredOptions } from './support'; +import { fillAddressFields, selectRequiredOptions } from './support'; // The deepest path a storefront check can walk: catalog -> product -> cart -> // shipping -> payment -> order. It touches the layered navigation, the price @@ -16,35 +16,17 @@ const shopper = { email: `mageos-e2e-${Date.now()}@example.com`, firstname: 'Mage', lastname: 'Tester', - street: '1 Open Source Way', - city: 'Austin', - regionId: process.env.E2E_REGION_ID ?? '57', // Texas - postcode: '78701', - telephone: '5125550123', - countryId: process.env.E2E_COUNTRY_ID ?? 'US', }; async function fillShippingAddress(page: Page) { const form = page.locator(luma.shippingForm); - // The country select repopulates the region field, so it goes first. - await form.locator('select[name="country_id"]').selectOption(shopper.countryId); + // The name is this spec's -- a guest's name is whatever they type -- and + // the address is the suite's, shared with the account that + // customer-checkout.spec.ts saves one on. await form.locator('input[name="firstname"]').fill(shopper.firstname); await form.locator('input[name="lastname"]').fill(shopper.lastname); - await form.locator('input[name="street[0]"]').fill(shopper.street); - await form.locator('input[name="city"]').fill(shopper.city); - - // Magento renders either a region select or a free-text input depending on - // the country. Handle whichever is actually on the page. - const regionSelect = form.locator('select[name="region_id"]'); - if (await regionSelect.isVisible()) { - await regionSelect.selectOption(shopper.regionId); - } else { - await form.locator('input[name="region"]').fill('Texas'); - } - - await form.locator('input[name="postcode"]').fill(shopper.postcode); - await form.locator('input[name="telephone"]').fill(shopper.telephone); + await fillAddressFields(form); } test.describe('Guest checkout', () => { diff --git a/_test/demo-package/Test/e2e/storefront/luma.ts b/_test/demo-package/Test/e2e/storefront/luma.ts index ab3121aa..19ddacf4 100644 --- a/_test/demo-package/Test/e2e/storefront/luma.ts +++ b/_test/demo-package/Test/e2e/storefront/luma.ts @@ -65,6 +65,22 @@ export const luma = { placeOrder: '#checkout-payment-method-load button.action.checkout.primary', successPageTitle: '.page-title', successBlock: '.checkout-success', + // The increment id on the success page, as a link. success.phtml wraps it + // in a.order-number only when the viewer can open the order, so this + // matches for a signed-in shopper and not for a guest -- which is why the + // guest spec matches the digits in the block instead. + successOrderNumber: '.checkout-success a.order-number', + + // Checkout with an address already on the account. Measured on this store + // with one saved address: the address is preselected in + // .shipping-address-item.selected-item, and #co-shipping-form is still in + // the DOM but hidden -- it is the New Address popup's form. So a spec + // asserts that form is not *visible*; neither its absence nor its + // presence says anything. + checkoutSelectedAddress: '.shipping-address-item.selected-item', + // The Ship To / shipping-method recap the payment step renders, in that + // order: two blocks with the same class. + checkoutShipTo: '.opc-block-shipping-information .shipping-information-content', // Account registration. Luma's own form, so it belongs in Luma's map: // firstname and lastname come from a shared name fieldset template, which @@ -76,6 +92,17 @@ export const luma = { registerPassword: '#password', registerPasswordConfirm: '#password-confirmation', registerSubmit: '#form-validate button[type="submit"]', + + // The address book's own form, which is #form-validate too -- the same id + // the registration form uses, on a different page. Named separately so a + // spec reads as what it is doing rather than as which template Magento + // happened to reuse. + addressForm: '#form-validate', + addressSubmit: '#form-validate button[type="submit"]', + // The Default Billing Address box on the Address Book page. The first + // address a customer saves becomes the default for both billing and + // shipping, so this is where a just-saved first address shows up. + defaultBillingAddress: '.box-address-billing .box-content', errorMessage: '.message-error', successMessage: '.message-success', @@ -110,6 +137,20 @@ export const luma = { // clicked. customerWelcomeToggle: '.panel.header .customer-welcome button.action.switch', signOut: 'a[href*="customer/account/logout"]', + + // My Orders, and the order page it links to. The grid and the order's own + // items table are both #my-orders-table -- sales_order_history.phtml and + // order_items.phtml give them the same id -- so the grid is addressed + // through its cells and the order through .table-order-items. + orderHistoryRow: '#my-orders-table tbody tr', + orderHistoryId: 'td.col.id', + orderHistoryStatus: 'td.col.status', + orderHistoryView: 'a.action.view', + orderStatus: '.order-status', + orderItems: '.table-order-items', + // td, not th: the items table repeats every column label in its header. + orderItemSku: '.table-order-items td.col.sku', + orderItemName: '.table-order-items .product-item-name', }; /** diff --git a/_test/demo-package/Test/e2e/storefront/search.spec.ts b/_test/demo-package/Test/e2e/storefront/search.spec.ts index 3b948679..54eee54f 100644 --- a/_test/demo-package/Test/e2e/storefront/search.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/search.spec.ts @@ -7,8 +7,8 @@ import { luma } from './luma'; * The workflow stands OpenSearch up, probes its version and prints it in the * run summary -- and until this spec, no test ever sent it a query. A release * that shipped a client which could not speak to the engine, an unbuilt - * catalogsearch_fulltext index, or a changed result template passed all - * sixteen of the other tests here. + * catalogsearch_fulltext index, or a changed result template passed every + * other test here. * * It searches for a sku it reads off a product page rather than one written * in this file. That costs two navigations and buys two things: the spec diff --git a/_test/demo-package/Test/e2e/storefront/support.ts b/_test/demo-package/Test/e2e/storefront/support.ts index 529ca487..5bccc920 100644 --- a/_test/demo-package/Test/e2e/storefront/support.ts +++ b/_test/demo-package/Test/e2e/storefront/support.ts @@ -1,4 +1,4 @@ -import { type Page } from '@playwright/test'; +import { expect, type Locator, type Page } from '@playwright/test'; import { luma } from './luma'; /** @@ -82,3 +82,106 @@ export function parseMoney(text: string): number { export async function asShopper(page: Page): Promise<void> { await page.context().clearCookies(); } + +/** + * The password every spec here registers with. + * + * Magento wants 8 characters and 3 of the 4 character classes + * (customer/password/minimum_password_length, + * required_character_classes_number, both read from the shipped config). This + * one has all four, so a store that tightened the policy by one notch still + * accepts it. + */ +export const customerPassword = 'Mage0s-E2E-pass1'; + +/** A shopper nothing else in the store has seen, name and address apart. */ +export function newShopper() { + const stamp = Date.now(); + + return { + firstName: 'Mage-OS', + lastName: `Shopper ${stamp}`, + email: `mageos-e2e-shopper-${stamp}@example.test`, + }; +} + +/** + * One postal address, shared by every spec that needs one. + * + * Texas and the US because the store installs en_US with the US as its single + * allowed country; overridable because a gate run against a store configured + * for somewhere else should be a matter of two variables, not a patch. + */ +export const shopperAddress = { + street: '1 Open Source Way', + city: 'Austin', + regionId: process.env.E2E_REGION_ID ?? '57', // Texas + region: 'Texas', + postcode: '78701', + telephone: '5125550123', + countryId: process.env.E2E_COUNTRY_ID ?? 'US', +}; + +/** + * Fills an address form -- checkout's or the account's -- with the address + * above. + * + * Deliberately not the name fields. Checkout wants them typed and the account + * form arrives with them already filled from the customer entity, and that + * prefill is worth asserting rather than overwriting. So the caller owns the + * name and this owns the address. + */ +export async function fillAddressFields(form: Locator): Promise<void> { + // The country select repopulates the region field, so it goes first. + await form.locator('select[name="country_id"]').selectOption(shopperAddress.countryId); + await form.locator('input[name="street[0]"]').fill(shopperAddress.street); + await form.locator('input[name="city"]').fill(shopperAddress.city); + + // Magento renders either a region select or a free-text input depending on + // the country. Both are in the account form's markup with one hidden, so + // this asks which one is actually on the page rather than which country it + // is. + const regionSelect = form.locator('select[name="region_id"]'); + if (await regionSelect.isVisible()) { + await regionSelect.selectOption(shopperAddress.regionId); + } else { + await form.locator('input[name="region"]').fill(shopperAddress.region); + } + + await form.locator('input[name="postcode"]').fill(shopperAddress.postcode); + await form.locator('input[name="telephone"]').fill(shopperAddress.telephone); +} + +/** + * Registers an account and submits the form, leaving the outcome to the + * caller: customer-account.spec.ts is about what registration does, and + * customer-checkout.spec.ts only needs an account to exist. + * + * Registration signs the new customer in -- CreatePost calls + * setCustomerDataAsLoggedIn unless customer/create_account/confirm is set, and + * it is 0 -- so a spec that calls this is signed in from here on. There is no + * CAPTCHA on this form: user_create is in always_for but not in + * customer/captcha/forms. + */ +export async function registerCustomer( + page: Page, + customer: { firstName: string; lastName: string; email: string }, +): Promise<void> { + const response = await page.goto('/customer/account/create/'); + + expect(response?.status(), 'the registration page should be served').toBe(200); + await expect(page.locator('body')).toHaveClass(/customer-account-create/); + + await page.fill(luma.registerFirstName, customer.firstName); + await page.fill(luma.registerLastName, customer.lastName); + await page.fill(luma.registerEmail, customer.email); + await page.fill(luma.registerPassword, customerPassword); + await page.fill(luma.registerPasswordConfirm, customerPassword); + + // Read back before submitting. A form that silently dropped a field fails + // here, where the cause is visible, rather than as a validation error + // whose text is about something else. + await expect(page.locator(luma.registerEmail)).toHaveValue(customer.email); + + await page.locator(luma.registerSubmit).click(); +} From 42aa8c5b4c2d47ce783b106a1efe151ab4115ea2 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 14:07:24 -0600 Subject: [PATCH 38/42] fix(e2e): wait for the two things a storefront page fills in late CI failed the new signed-in checkout spec where a local store passed it, and the difference turned out to be two races rather than one bug. Neither option control arrives with its values. The server sends an empty <select> and an empty swatch group, and the configurable widget fills them from spConfig once requirejs has it -- measured here as empty on arrival and three values a moment later. selectRequiredOptions read them straight after the navigation and shrugged when it found nothing, so a configurable went to add-to-cart unconfigured, was refused by validation, and the symptom was a missing success message that said nothing about options. It now waits for a real option and fails naming the locator if one never comes: a product nobody can configure is a product nobody can buy. That is also why CI and a local store disagreed at all. The specs buy whatever the catalogue lists first, which is the fixture configurable on a cold store and a simple product on one an admin spec has run against. CI won the race, bought the configurable, and found the second difference: an order line carries the *child* sku while the product page shows the parent's, and Luma never rewrites what it shows when an option is chosen. luma.ts claimed the opposite; corrected. The order line is now identified by product name, which is the parent's on both pages, and the sku is asserted through the rule that explains the difference -- a line with chosen options carries a variant's sku, a line without them carries the product's. The form key is minted in the browser, because a page out of the full page cache would otherwise carry someone else's. Sampled from document commit: + 0ms cookie=(none) input=sKSvRQDyz5fExuSH no match + 250ms cookie=gVEGZbqOGvCViuHP input=gVEGZbqOGvCViuHP match A person never submits inside that window and Playwright sometimes does, which answers the POST with `Invalid Form Key. Please refresh the page.` Registration is where this suite loses it -- five fields filled back to back -- and it is now behind awaitFormKey(), used before every storefront form submit, including the admin spec that first reported the symptom and had it put down to a stale admin session. Verified: 19 passed, and the storefront project 24/24 over three repeats at --retries=0. The signed-in spec also passes 3/3 pointed at the fixture configurable, which is what CI buys. --- _test/demo-package/Test/e2e/README.md | 54 +++++++++++- .../Test/e2e/admin/create-customer.spec.ts | 7 +- .../e2e/storefront/customer-checkout.spec.ts | 46 ++++++++-- .../e2e/storefront/guest-checkout.spec.ts | 3 +- .../demo-package/Test/e2e/storefront/luma.ts | 10 ++- .../Test/e2e/storefront/product-page.spec.ts | 3 +- .../Test/e2e/storefront/support.ts | 84 ++++++++++++++++--- 7 files changed, 183 insertions(+), 24 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 4914c954..0cda4205 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -44,7 +44,8 @@ looks at a storefront page. A Hyva variant of this suite is that file with a different map, not a rewrite of the specs. `storefront/support.ts` holds the behaviour that goes with them -- choosing whatever options a product requires, reading the number out of a rendered price, registering an account, filling an -address form -- because that part is not theme-specific. Three admin specs import from both, which is the point: an +address form, waiting for a form key to become valid -- because that part is +not theme-specific. Three admin specs import from both, which is the point: an admin spec that proves a save reached a shopper is looking at a storefront page, and should read it the way the storefront specs do. @@ -189,6 +190,24 @@ spec carries the increment id the success page gave it to both of those pages, so what it proves is that one order moved through, not that three pages each rendered something plausible. +What identifies the *line* across those pages is the product name, not the +sku, and that is a measured decision. Every spec here buys whatever the +catalogue lists first, and that is not the same product everywhere -- CI gets +the fixture configurable, a store an admin spec has run against gets a simple +product. A configurable's order line carries the child sku while its product +page shows the parent's, and Luma does not rewrite the displayed sku when an +option is chosen: + +| | product page | order line | +| --- | --- | --- | +| simple | `product_dynamic_11` | `product_dynamic_11` | +| configurable | `Configurable Product 1` | `Configurable Product 1 - option 1` | + +The parent name is on both pages in both cases, so that is the identity. The +sku is then asserted through the rule that explains the difference rather than +around it: a line with chosen options carries a variant's own sku, a line +without them carries the product's. + One selector trap on the way: the My Orders grid and the order's own items table are both `#my-orders-table`. `sales_order_history.phtml` and `order_items.phtml` give them the same id, on different pages. The grid is @@ -202,6 +221,35 @@ The spec also asserts the new-address form arrives carrying the customer's name before it types anything into it: a form reading the wrong entity saves the address either way, so nothing else would notice. +### A storefront form submit has to wait for its form key + +Magento mints the form key in the browser, because a page served from the full +page cache would otherwise hand every visitor whatever key was rendered into +it. `Magento_PageCache/js/form-key-provider.js` writes a fresh one to the +`form_key` cookie and rewrites each form's hidden input to match. Sampling +both values from document commit: + +``` ++ 0ms cookie=(none) input=sKSvRQDyz5fExuSH no match ++ 250ms cookie=gVEGZbqOGvCViuHP input=gVEGZbqOGvCViuHP match +``` + +A quarter of a second. A person never submits a form inside that window; +Playwright does, and Magento answers the POST with `Invalid Form Key. Please +refresh the page.` The store is behaving as designed -- but the spec that +hits it is asserting on a *message*, so the failure arrives as the wrong +message rather than as anything that looks like a timing problem. + +So every storefront form submit here is preceded by `awaitFormKey(page)`, +which polls until the cookie exists and the hidden input matches it. +Registration is where this suite actually loses the race -- five fields filled +back to back is its fastest submission, and it has been seen three times -- +but the wait costs nothing and the next fast spec should not have to +rediscover the reason. + +Not to be confused with the admin-session form key further down. That one is +not a race: the key is valid and belongs to the wrong session. + ### Why a second cart spec `storefront/guest-checkout.spec.ts` walks past the product page and the cart @@ -510,7 +558,9 @@ under a page that has already rendered it. CI has never seen it, because a gate's store is used once and by one run. Rather than chase that race: a shopper is not an administrator. Clearing the -cookies costs one request's worth of session and removes the class. +cookies costs one request's worth of session and removes the class. The +`awaitFormKey` wait above does not help here -- there the page has not caught +up with the cookie yet, and here the cookie itself belongs to somebody else. ### One grid a save does update diff --git a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts index 911d459d..85716ce8 100644 --- a/_test/demo-package/Test/e2e/admin/create-customer.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from '../fixtures'; import { adminGrid, adminSelectors, adminUrl } from './support'; -import { asShopper } from '../storefront/support'; +import { asShopper, awaitFormKey } from '../storefront/support'; import { luma } from '../storefront/luma'; /** @@ -134,6 +134,11 @@ test.describe('Creating a customer in the admin', () => { await page.locator(luma.registerEmail).fill(customer.email); await page.locator(luma.registerPassword).fill('mageos-E2E-1!'); await page.locator(luma.registerPasswordConfirm).fill('mageos-E2E-1!'); + + // Clearing the cookies above means form-key-provider.js has to + // mint a key again, so this submit is in the race awaitFormKey + // describes -- and this is the spec that first hit it. + await awaitFormKey(page); await page.locator(luma.registerSubmit).click(); await expect(page.locator(luma.errorMessage)).toContainText( diff --git a/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts index d7ff6cea..852836d1 100644 --- a/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts @@ -1,6 +1,7 @@ import { expect, test } from '../fixtures'; import { luma } from './luma'; import { + awaitFormKey, fillAddressFields, newShopper, registerCustomer, @@ -36,6 +37,12 @@ import { * It asserts the increment id the success page gave it on all three pages, so * what is being checked is that one order moved through, not that each page * renders something plausible. + * + * Like every spec here it buys whatever the catalogue lists first, which is + * not the same product everywhere -- CI's first product is the fixture + * configurable and a store that has had an admin spec run against it lists a + * simple one. So the assertions below are product-type independent on + * purpose, and the final step says what that costs. */ test.describe('Signed-in checkout', () => { @@ -78,6 +85,7 @@ test.describe('Signed-in checkout', () => { await expect(form.locator(luma.registerLastName)).toHaveValue(customer.lastName); await fillAddressFields(form); + await awaitFormKey(page); await page.locator(luma.addressSubmit).click(); await expect(page.locator('body')).toHaveClass(/customer-address-index/); @@ -109,6 +117,7 @@ test.describe('Signed-in checkout', () => { expect(sku, 'a product page should render a sku').not.toBe(''); await selectRequiredOptions(page); + await awaitFormKey(page); await page.locator(luma.addToCart).click(); await expect(page.locator(luma.cartSuccess)).toContainText('to your shopping cart'); @@ -206,14 +215,37 @@ test.describe('Signed-in checkout', () => { await expect(page.locator(luma.pageTitle)).toContainText(orderNumber); await expect(page.locator(luma.orderStatus)).toHaveText('Pending'); - // The sku read off the product page before it was added to - // the cart: the catalogue, the quote and the order all - // agreeing on which product this was. + // The product name, not the sku, is what identifies this line + // as the thing that was bought. A configurable's order line + // carries the *child* sku while its product page shows the + // parent's, and the page never rewrites what it shows when an + // option is chosen -- measured: a page reading "Configurable + // Product 1" becomes an order line reading "Configurable + // Product 1 - option 1". The parent name is on both pages. await expect( - page.locator(luma.orderItemSku), - 'the order should carry the sku that was added to the cart', - ).toHaveText(sku); - await expect(page.locator(luma.orderItemName)).toContainText(productName); + page.locator(luma.orderItemName), + 'the order should name the product that was added to the cart', + ).toContainText(productName); + + // Which leaves the sku assertable through the rule that + // explains that difference rather than around it: a line with + // chosen options carries a variant's own sku, a line without + // them carries the product's. Both are worth failing on, and + // which kind of product the catalogue happens to list first + // is not this spec's business -- CI and a local store already + // disagree about it. + const orderedSku = page.locator(luma.orderItemSku); + if ((await page.locator(luma.orderItemOptions).count()) === 0) { + await expect( + orderedSku, + 'a line with no options should carry the sku the product page showed', + ).toHaveText(sku); + } else { + await expect( + orderedSku, + 'a configured line should carry a variant sku of its own', + ).not.toBeEmpty(); + } }); }, ); diff --git a/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts index 3b790e0b..3b2db34f 100644 --- a/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts @@ -1,7 +1,7 @@ import { type Page } from '@playwright/test'; import { expect, test } from '../fixtures'; import { luma } from './luma'; -import { fillAddressFields, selectRequiredOptions } from './support'; +import { awaitFormKey, fillAddressFields, selectRequiredOptions } from './support'; // The deepest path a storefront check can walk: catalog -> product -> cart -> // shipping -> payment -> order. It touches the layered navigation, the price @@ -58,6 +58,7 @@ test.describe('Guest checkout', () => { await test.step('adding to the cart updates the minicart', async () => { await selectRequiredOptions(page); + await awaitFormKey(page); await page.locator(luma.addToCart).click(); // customer-data arrives over a separate /customer/section/load diff --git a/_test/demo-package/Test/e2e/storefront/luma.ts b/_test/demo-package/Test/e2e/storefront/luma.ts index 19ddacf4..31f57bfd 100644 --- a/_test/demo-package/Test/e2e/storefront/luma.ts +++ b/_test/demo-package/Test/e2e/storefront/luma.ts @@ -17,8 +17,11 @@ export const luma = { pageTitle: '.page-title', productPrice: '.product-info-main .price', // The sku Luma prints under the product's details. On a configurable this - // starts as the parent sku and is rewritten by JS once an option is - // chosen, so a spec asserts that it is there and not what it says. + // is the parent's sku and it stays that way -- measured on Mage-OS 4.0.0, + // the displayed value does not change when an option is chosen, while the + // order line that follows carries the *child* sku. So a spec asserts that + // a sku is rendered, and uses the product name when it needs to recognise + // the same product on another page. productSku: '.product.attribute.sku .value', // Quick search, as Luma renders it in the header. Typing into it fires no @@ -151,6 +154,9 @@ export const luma = { // td, not th: the items table repeats every column label in its header. orderItemSku: '.table-order-items td.col.sku', orderItemName: '.table-order-items .product-item-name', + // The chosen options a line carries, rendered under its name. Their + // presence is what says the sku below belongs to a variant. + orderItemOptions: '.table-order-items .item-options', }; /** diff --git a/_test/demo-package/Test/e2e/storefront/product-page.spec.ts b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts index e341e726..b97b47d5 100644 --- a/_test/demo-package/Test/e2e/storefront/product-page.spec.ts +++ b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from '../fixtures'; import { luma } from './luma'; -import { parseMoney, selectRequiredOptions } from './support'; +import { awaitFormKey, parseMoney, selectRequiredOptions } from './support'; /** * A product page and the cart it fills, asserted properly. @@ -84,6 +84,7 @@ test.describe('Product page', () => { await qty.fill(String(quantity)); await expect(qty).toHaveValue(String(quantity)); + await awaitFormKey(page); await page.locator(luma.addToCart).click(); // Magento names the product in the message, which is the cheapest diff --git a/_test/demo-package/Test/e2e/storefront/support.ts b/_test/demo-package/Test/e2e/storefront/support.ts index 5bccc920..ec77c0be 100644 --- a/_test/demo-package/Test/e2e/storefront/support.ts +++ b/_test/demo-package/Test/e2e/storefront/support.ts @@ -11,14 +11,27 @@ import { luma } from './luma'; * a value, and which product the catalog lists first is not ours to decide. * So pick the first available value for whatever the page asks for, and let a * spec work on a simple product, a configurable, or a merchant's own catalog. + * + * Every wait here is load-order, not politeness. Neither control arrives with + * its values: the server sends an empty `<select>` and an empty swatch group, + * and Magento_ConfigurableProduct's widget fills them in from spConfig once + * requirejs has it. Reading them straight after the navigation therefore + * finds nothing to choose, which this function used to shrug off -- and the + * product then fails validation on add-to-cart, with no success message and + * no mention of options anywhere. Measured on this store: the dropdown is + * empty on arrival and holds three values a moment later. + * + * So an option control that never becomes selectable now fails here, with a + * timeout naming the locator, rather than three assertions later as a cart + * that stayed empty. A product nobody can configure is a product nobody can + * buy, which is a finding either way. */ export async function selectRequiredOptions(page: Page): Promise<void> { const swatchGroups = page.locator(luma.swatchGroup); for (let i = 0; i < (await swatchGroups.count()); i++) { const option = swatchGroups.nth(i).locator(luma.swatchOption).first(); - if (await option.count()) { - await option.click(); - } + await option.waitFor({ state: 'visible' }); + await option.click(); } // Configurables render dropdowns instead of swatches when the attribute @@ -26,13 +39,13 @@ export async function selectRequiredOptions(page: Page): Promise<void> { const selects = page.locator(luma.optionSelect); for (let i = 0; i < (await selects.count()); i++) { const select = selects.nth(i); - const values = await select - .locator('option') - .evaluateAll((options) => - options.map((option) => (option as HTMLOptionElement).value).filter(Boolean), - ); - if (values.length) { - await select.selectOption(values[0]); + // The placeholder option ships with the page and carries no value, so + // this waits for a real one rather than for any option at all. + const firstValue = select.locator('option[value]:not([value=""])').first(); + await firstValue.waitFor({ state: 'attached' }); + const value = await firstValue.getAttribute('value'); + if (value) { + await select.selectOption(value); } } } @@ -55,6 +68,56 @@ export function parseMoney(text: string): number { return Number.parseFloat(text.replace(/[^\d.,-]/g, '').replace(/,/g, '')); } +/** + * Waits until the page's form key is one the server will accept. + * + * Magento_PageCache ships `form-key-provider.js` because a storefront page can + * be served from the full page cache, where a server-rendered form key would + * be some earlier visitor's. So the script mints a key, writes it to the + * `form_key` cookie and rewrites every form's hidden input to match. Until it + * runs, the page carries a key that does not match any cookie. + * + * Measured on this store, sampling both values from document commit: + * + * + 0ms cookie=(none) input=sKSvRQDyz5fExuSH no match + * + 250ms cookie=gVEGZbqOGvCViuHP input=gVEGZbqOGvCViuHP match + * + * A quarter of a second, which a browser driven by a person never loses and + * one driven by Playwright sometimes does: a form filled in faster than that + * POSTs the stale key and Magento answers `Invalid Form Key. Please refresh + * the page.` It is a flake rather than a bug -- the store is behaving as + * designed and the shopper is never that fast -- and it reads as a broken + * registration, which is worse than it sounds: the spec that hits it is + * asserting on a *message*, so the failure arrives as the wrong message + * rather than as a timing problem. + * + * Observed on registration three times across this suite's history, which is + * where the race is lost: five fields filled back to back is the fastest form + * submission here. Called before every storefront form submit anyway, because + * the next spec to be fast enough should not have to rediscover this. + * + * See asShopper below for the other way this key goes wrong, which is not a + * race at all. + */ +export async function awaitFormKey(page: Page): Promise<void> { + await expect + .poll( + async () => { + const cookie = (await page.context().cookies()).find( + (candidate) => candidate.name === 'form_key', + )?.value; + if (!cookie) return false; + + const input = page.locator('input[name="form_key"]').first(); + if ((await input.count()) === 0) return false; + + return (await input.inputValue()) === cookie; + }, + { message: 'the page should carry a form key matching its cookie' }, + ) + .toBe(true); +} + /** * Drops the cookies an admin spec is carrying, so the storefront half of it * runs as a visitor. @@ -183,5 +246,6 @@ export async function registerCustomer( // whose text is about something else. await expect(page.locator(luma.registerEmail)).toHaveValue(customer.email); + await awaitFormKey(page); await page.locator(luma.registerSubmit).click(); } From 8d56ab9ad60e188284e5ef8dcfb84c58f0f706b3 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 14:16:41 -0600 Subject: [PATCH 39/42] fix(e2e): raise the Redis session cap the admin burst exceeds admin/create-order has failed intermittently since the suite was written, always the same way: locator.click times out with a modal footer intercepting pointer events, alongside a 500 on mui/index/render. It was looked at twice and cleared twice -- Redis session concurrency was the hypothesis both times, and 10 runs at --retries=0 in CI plus 5 locally at max_concurrency=6 all passed, so the hypothesis was dropped. The run's own exception.log settles it: Cm\RedisSession\ConcurrentConnectionsExceededException -> Magento\Framework\Session\SaveHandler\Redis::read (Redis.php:86) -> Magento\Backend\Model\Auth\Session->start() main.ERROR: Redis session exceeded concurrent connections max_concurrency is six by default, and the create-order page starts more admin sessions than that at once -- one per ui-component XHR. The seventh is refused, that request 500s, Magento pops its "Attention" modal, and the modal swallows the click. The symptom is three steps from the cause, which is why it read as a modal race. --repeat-each never reproduced it because the burst is inside one page load, not across tests. The evidence that did was available only because `Report what Magento logged` now runs even when a retry turns the run green, which is what that step was added for. Raised to 20, not disabled: locking stays in force, so a regression in it still has somewhere to show, while the cap only an automated browser reaches stops deciding whether the gate is green. --- .github/workflows/_internal-e2e.yaml | 6 ++++++ .github/workflows/e2e-README.md | 32 ++++++++++++++++++++++++++++ .github/workflows/e2e.yaml | 6 ++++++ 3 files changed, 44 insertions(+) diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml index 4d507d9d..18fe9bb8 100644 --- a/.github/workflows/_internal-e2e.yaml +++ b/.github/workflows/_internal-e2e.yaml @@ -134,6 +134,12 @@ jobs: # Enabling it belongs in its own change, with its own run. magento config:set cms/wysiwyg/enabled disabled + # Redis session locking lets six processes wait on one session, and the + # admin's create-order page starts more admin sessions than that at + # once: the seventh 500s on mui/index/render and pops the "Attention" + # modal over whatever the spec was clicking. Raised, not disabled. + magento setup:config:set -n --session-save-redis-max-concurrency=20 + magento cache:flush # Separate from the test run so "never reachable" and "rendered the wrong diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md index 2a0a7c51..e9738fae 100644 --- a/.github/workflows/e2e-README.md +++ b/.github/workflows/e2e-README.md @@ -121,6 +121,38 @@ either: the store is created and destroyed inside one job. from that single place. Two places holding separate opinions about the admin URL is a 404 that presents as a broken admin. +## The Redis session cap an automated browser reaches + +Six. That is how many processes `max_concurrency` lets wait on one session, +and the admin's create-order page starts more admin sessions than that at +once -- every ui-component XHR it fires starts one. The seventh is refused: + +``` +Cm\RedisSession\ConcurrentConnectionsExceededException + -> Magento\Framework\Session\SaveHandler\Redis::read (Redis.php:86) + -> Magento\Backend\Model\Auth\Session->start() +main.ERROR: Redis session exceeded concurrent connections +``` + +What that looks like from the test is nothing like its cause: the refused +request becomes a `500` on `mui/index/render`, Magento pops its "Attention" +modal over the page, and the modal swallows the click the spec was making. So +the spec fails on `locator.click: Timeout` with a modal footer intercepting +pointer events, three steps away from the session handler. + +This took three attempts to pin down, and the two failed ones are the reason +the `Report what Magento logged` step exists and runs whether the suite passed +or not. A Playwright retry that succeeds makes the run green and `if: failure()` +never fires, so the evidence was being thrown away; `--repeat-each` does not +reproduce it either, because the burst happens inside one page load rather than +across tests. The run's own `var/log/exception.log` named it in one line. + +The workflow therefore sets `--session-save-redis-max-concurrency=20` after +the install. Raised rather than switched off, with `disable_locking` left +alone: session locking stays in force, so a release that broke it still has +somewhere to show up, while the cap that only an automated browser reaches +stops deciding whether the gate is green. + ## Signing in to the admin `disable_admin_auth_modules` (default `true`) disables diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 5e388412..18ef9f18 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -233,6 +233,12 @@ jobs: # Enabling it belongs in its own change, with its own run. magento config:set cms/wysiwyg/enabled disabled + # Redis session locking lets six processes wait on one session, and the + # admin's create-order page starts more admin sessions than that at + # once: the seventh 500s on mui/index/render and pops the "Attention" + # modal over whatever the spec was clicking. Raised, not disabled. + magento setup:config:set -n --session-save-redis-max-concurrency=20 + # The config cache was loaded before any of this was set. magento cache:flush From 44115d6d6d80ac05f7844516e00ffff337532773 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 14:27:10 -0600 Subject: [PATCH 40/42] fix(e2e): apply the order grid's sku filter with Enter With the Redis session cap raised, admin/create-order failed again on the next rehearsal -- but in a different step and with nothing in Magento's logs: `locator.click` timed out for 20 seconds on the product grid's Search button, which resolved every attempt and was visible on none of them. The grid re-renders itself while the filter is being typed, and the button goes with it. varienGrid binds keypress on every filter input and calls doFilter() on Enter, so pressing Enter in the sku field applies the same filter without needing the button to still be on the page when the click lands -- and it is what a person does. The now-unused applyFilter selector goes with the change. Local: create-order 5/5 at --retries=0. --- _test/demo-package/Test/e2e/README.md | 16 ++++++++++++++++ .../Test/e2e/admin/create-order.spec.ts | 11 +++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 0cda4205..177205c6 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -536,6 +536,22 @@ Three more traps on that page, each of which cost a red run to find: nothing has been chosen -- so it works on a store with one method and on a store with six. +- **The product grid's Search button does not survive the typing.** The sku + filter is applied with Enter, not by clicking Search. The grid re-renders + while the filter is being filled in and the button goes with it, which CI + showed as `locator.click` timing out for 20 seconds on a button that + resolved every time and was visible none of them. `varienGrid` binds + keypress on each filter input and calls `doFilter()` on Enter -- a path that + needs nothing to still be on the page by the time the click lands, and the + one a person uses anyway. + +- **A burst of its own XHRs used to exhaust the session handler.** The page + starts one admin session per ui-component request and Redis session locking + allows six waiters, so the seventh was refused, that request returned 500, + and Magento's "Attention" modal landed on top of whatever was being clicked. + The workflow now installs with `max_concurrency=20`; the full account is in + `.github/workflows/e2e-README.md`. + ### The storefront half of an admin spec is a different visitor Three admin specs cross into the storefront to prove the save reached a diff --git a/_test/demo-package/Test/e2e/admin/create-order.spec.ts b/_test/demo-package/Test/e2e/admin/create-order.spec.ts index a65a38b5..bcbb9a9a 100644 --- a/_test/demo-package/Test/e2e/admin/create-order.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -48,7 +48,6 @@ const orderForm = { searchGrid: '#sales_order_create_search_grid', searchGridTable: '#sales_order_create_search_grid_table > tbody tr', skuFilter: '#sales_order_create_search_grid_filter_sku', - applyFilter: '#sales_order_create_search_grid [data-action="grid-filter-apply"]', addSelected: '#order-search .admin__page-section-title .actions button.action-add', itemsGrid: '#order-items_grid', billing: { @@ -191,8 +190,16 @@ test.describe('Creating an order in the admin', () => { // The sku filter is a LIKE, so this narrows the grid rather than // selecting a row: product_dynamic matches every fixture simple. + // + // Applied with Enter rather than by clicking Search, because the + // grid re-renders itself while the filter is being typed and the + // button goes with it: observed in CI as `locator.click` timing + // out for 20s on a Search button that resolved but was never + // visible. varienGrid binds keypress on every filter input and + // calls doFilter() on Enter, which is both what a person does and + // the one path that does not need the button to survive. await page.fill(orderForm.skuFilter, 'product_dynamic'); - await page.locator(orderForm.applyFilter).click(); + await page.locator(orderForm.skuFilter).press('Enter'); await form.settled(); const rows = page.locator(orderForm.searchGridTable); From a46e92cc04103f641389b5433e67ea590ddc97b8 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sat, 21 Nov 2026 15:44:25 -0600 Subject: [PATCH 41/42] test(e2e): take the admin order through to shipped The create-order spec stopped at a Pending order. An order that cannot be invoiced or shipped is a store that cannot be run, and nothing in the suite touched that: the invoice and the shipment are separate entities with their own sequence tables, their own grids and their own totals, and creating them is what moves the order through new -> processing -> complete. Three steps, on the order the spec already placed rather than in a spec of its own -- a second spec would pay the dozen round trips of the create form again to assert something this one is already holding. Measured while writing them: - Neither submit button has an id. Both Items blocks add their button through addChild rather than the page's ButtonList, so the rendered id is random and the label is the only thing separating "Submit Invoice" from "Submit Shipment". - order/totals.phtml names its rows from the key of the totals array, and an invoice's keys are positional: col-0 (Grand Total), col-0 (Subtotal), col-1 (Shipping). Not descriptive, not unique, so the selectors go by label -- and that markup is not the create form's, which is why one spec now carries two sets of totals selectors. - #send_email ships unchecked, which the spec asserts rather than clears: a store that pre-checked it would make this step send mail, and the failure would present as a broken invoice. The end state is asserted by absence. canInvoice() and canShip() are both false once everything is invoiced and shipped, so Order\View adds neither button; an order still offering them is one whose quantities did not move, which a status label alone would not catch. --- _test/demo-package/Test/e2e/README.md | 86 ++++++-- .../Test/e2e/admin/create-order.spec.ts | 183 +++++++++++++++++- 2 files changed, 249 insertions(+), 20 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index 177205c6..e80ab916 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -24,7 +24,7 @@ every change to it and runs this suite against the result. | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | | `admin/create-category.spec.ts` | yes | category tree -> save -> url rewrite -> category index -> storefront listing + menu | | `admin/create-customer.spec.ts` | no | customer form -> save -> read-back -> the storefront refuses the address twice | -| `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid | +| `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid -> invoice -> shipment -> both document grids | | `admin/menu-navigation.spec.ts` | no | the admin's own rendered link reaches the product grid, secret key or not | Each area owns a directory, and the Playwright project of the same name @@ -552,6 +552,58 @@ Three more traps on that page, each of which cost a red run to find: The workflow now installs with `max_concurrency=20`; the full account is in `.github/workflows/e2e-README.md`. +### Taking that order to Complete + +The same spec then invoices and ships the order it placed. That is the order +state machine -- `new` -> `processing` -> `complete` -- and it is a different +thing from placing the order: the invoice and the shipment are separate +entities, with their own sequence tables, their own grids and, in the +invoice's case, totals of their own. + +They are steps of the create-order test rather than a spec of their own +because they need an order nothing else has invoiced, and placing one costs +the dozen round trips above. A second spec would pay that twice to assert +something this one is already holding. + +Four things are worth knowing before touching those steps. + +- **Neither submit button has an id.** `Invoice\Create\Items` and + `Magento_Shipping`'s `Create\Items` both add a + `Backend\Block\Widget\Button` with `class="save submit-button primary"` + through `addChild`, not through the `ButtonList` the page's own toolbar + uses, so the rendered id is a random `id_3OUDV1Cmg...`. The label is the + only thing that separates "Submit Invoice" from "Submit Shipment", so the + spec filters on it -- which also means a step cannot accidentally submit the + page it only thought it was on. +- **The invoice's totals rows are numbered, not named.** + `Magento_Sales::order/totals.phtml` names each row `tr.col-<code>` from the + key of the totals array, and for an invoice those keys are positional. + Measured on a two-line invoice: `col-0` (Grand Total), `col-0` (Subtotal), + `col-1` (Shipping & Handling). The class is neither descriptive nor unique, + so these selectors go by label, the same way the create form's do. Note also + that this is *not* the markup the create form uses -- `order/create/ + totals.phtml` renders `tr.row-totals` -- which is why one spec carries two + sets of totals selectors. +- **The invoice email is opt-in, and the spec asserts that it is.** + `Invoice\Create\Items` renders `#send_email` with no `checked` attribute. + The step asserts it is unchecked rather than clearing it, because a store + that pre-checked it would have this step send mail through whatever + transport the gate installed, and a mail failure would then present as a + broken invoice. +- **The end state is asserted by absence.** Once every item is invoiced and + shipped, `canInvoice()` and `canShip()` are both false and + `Order\View::_construct` adds neither button, so the spec asserts + `#order_invoice` and `#order_ship` are *gone*. An order that still offers + them is one whose item quantities did not move, which a status label alone + would not catch. + +One more thing the offline payment method buys: Check / Money order cannot +capture, so `Invoice::register()` marks the invoice paid as it creates it and +the order's **Total Paid** is the full amount with nothing due. On a gateway +method both would stay at zero until the capture came back. That assertion +belongs with the payment method this gate installs, not in a helper that +claims to hold for any of them. + ### The storefront half of an admin spec is a different visitor Three admin specs cross into the storefront to prove the save reached a @@ -578,14 +630,17 @@ cookies costs one request's worth of session and removes the class. The `awaitFormKey` wait above does not help here -- there the page has not caught up with the cookie yet, and here the cookie itself belongs to somebody else. -### One grid a save does update +### Three grids a save does update, and one it does not -`admin/create-order.spec.ts` asserts the order appears in the order grid. -`admin/create-customer.spec.ts` deliberately does not assert the customer -grid. The difference is in the shipped configuration, not in the specs: -`sales/general/async_indexing` is `0`, so `sales_order_grid` is written in the -same request that saves the order, while `customer_grid` is a scheduled -indexer that this store has no cron to run. +`admin/create-order.spec.ts` asserts the order appears in the order grid, and +the invoice and the shipment in theirs -- three separate grids over three +separate tables, so a release that broke one indexer cannot hide behind +another. `admin/create-customer.spec.ts` deliberately does not assert the +customer grid. The difference is in the shipped configuration, not in the +specs: `sales/general/async_indexing` is `0`, so `sales_order_grid`, +`sales_invoice_grid` and `sales_shipment_grid` are each written in the request +that saves their entity, while `customer_grid` is a scheduled indexer that +this store has no cron to run. One is a fair assertion. The other would be a red test against a store that is working correctly, which is the worst kind to put in front of someone deciding @@ -859,17 +914,12 @@ least two in the `<configs>` block. ## What the checkout specs do not cover A real payment gateway, taxes, discounts, multi-address shipping, and the -order's life after it is placed -- invoice, shipment, credit memo. Each wants -fixtures or credentials of its own, and none of them is on the path between -"we tagged a release" and "a shopper can buy something". +refund half of the order's life -- credit memos. Each wants fixtures or +credentials of its own, and none of them is on the path between "we tagged a +release" and "a shopper can buy something". Both ways of buying are covered: `guest-checkout` as a visitor and `customer-checkout` as a shopper with an account, an address book entry and an order history. `admin/create-order` covers the third front end onto the same -quote model, carrier pool and payment pool. - -The nearest remaining gap is the order state machine. Every order this suite -places stays Pending, because Check / Money order is the only payment method -on a store with no gateway credentials, and nothing here invoices or ships -one. An invoice-and-ship spec against the order `admin/create-order` already -places would cover it without needing a single new fixture. +quote model, carrier pool and payment pool, and then takes its own order +through the state machine -- see below. diff --git a/_test/demo-package/Test/e2e/admin/create-order.spec.ts b/_test/demo-package/Test/e2e/admin/create-order.spec.ts index bcbb9a9a..0382ab01 100644 --- a/_test/demo-package/Test/e2e/admin/create-order.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -34,6 +34,20 @@ import { parseMoney } from '../storefront/support'; * So this spec tracks those requests and waits for them to stop. That is what * formReloads() below is, and it is the only reason the rest of this reads as * simply as it does. + * + * ## Why it goes on to invoice and ship + * + * Placing the order is only the first transition. An order that is created and + * then cannot be invoiced or shipped is a store that cannot be run, and + * nothing before this spec's last three steps touches that: the invoice and + * the shipment are separate entities with their own grids, their own sequence + * tables and their own totals, and creating them is what moves the order + * through new -> processing -> complete. + * + * They are steps of this test rather than a spec of their own because they + * need an order that nothing else has invoiced, and placing one costs the + * dozen round trips above. A second spec would pay that twice to assert + * something this one is already holding in its hand. */ const orderForm = { @@ -80,6 +94,33 @@ const orderForm = { // form's: Order\View\Items renders .edit-order-table, with the sku in // its own element and the quantity as a breakdown ("Ordered 2"). orderedItems: '.edit-order-table', + // Order\View::_construct adds these two by id, each behind its own + // guard: order_invoice only while canInvoice(), order_ship only while + // canShip(). So their absence is an assertion of its own -- see the last + // two lines of the shipping step. + invoiceButton: '#order_invoice', + shipButton: '#order_ship', + // The invoice page and the shipment page submit through the same widget. + // Invoice\Create\Items and Shipping's Create\Items both add a + // Backend\Widget\Button with class "save submit-button primary" and no + // id, so the label is the only thing that tells them apart -- which is + // why the steps below filter on it rather than trusting the page they + // think they are on. + submitDocument: 'button.submit-button', + emailCopy: '#send_email', + // The invoice page and the saved order render their totals through + // Magento_Sales::order/totals.phtml, which is not the markup the create + // form above uses -- order/create/totals.phtml renders tr.row-totals -- + // so this spec needs two sets of totals selectors. + // + // Addressed by label for a second reason as well. totals.phtml names each + // row tr.col-<code> from the key of the totals array, and the invoice's + // keys are positional: measured on a two-line invoice, the rows come back + // as col-0 (Grand Total), col-0 (Subtotal) and col-1 (Shipping), so the + // class says nothing about what the row holds and is not even unique. + documentGrandTotal: '#invoice_totals tr:has-text("Grand Total") .price', + viewTotalPaid: 'table.order-subtotal-table tr:has-text("Total Paid") .price', + viewTotalDue: 'table.order-subtotal-table tr:has-text("Total Due") .price', }; const buyer = { @@ -150,7 +191,7 @@ test.describe('Creating an order in the admin', () => { // the form, on a store that may also be building static assets. test.setTimeout(300_000); - test('@admin places an order for a new customer', async ({ page }) => { + test('@admin takes an order from placed to shipped', async ({ page }) => { const form = formReloads(page); const stamp = `${Date.now()}`; const customer = { @@ -268,6 +309,7 @@ test.describe('Creating an order in the admin', () => { }); let shipping = 0; + let grandTotal = 0; await test.step('the carrier quotes a rate and the method is chosen', async () => { await page.locator(orderForm.getShippingRates).first().click(); @@ -326,7 +368,7 @@ test.describe('Creating an order in the admin', () => { const totals = page.locator(orderForm.totals); const subtotal = parseMoney(await totals.locator(orderForm.subtotalRow).first().innerText()); - const grandTotal = parseMoney(await totals.locator(orderForm.grandTotalRow).first().innerText()); + grandTotal = parseMoney(await totals.locator(orderForm.grandTotalRow).first().innerText()); shipping = grandTotal - subtotal; // The same arithmetic the cart spec checks on the storefront, @@ -340,6 +382,7 @@ test.describe('Creating an order in the admin', () => { }); let incrementId = ''; + let orderId = ''; await test.step('submitting it creates the order', async () => { await page.locator(orderForm.submit).click(); @@ -356,6 +399,12 @@ test.describe('Creating an order in the admin', () => { incrementId = (await page.locator(adminSelectors.pageTitle).innerText()).trim().replace(/^#/, ''); expect(incrementId, 'the order view is titled with the increment id').toMatch(/^\d+$/); + // Kept because the steps after the grid have to come back here, + // and every admin sales route addresses an order by its entity + // id, never by the increment id a person reads. + orderId = page.url().match(/order_id\/(\d+)/)?.[1] ?? ''; + expect(orderId, `the order view URL should carry an entity id: ${page.url()}`).toMatch(/^\d+$/); + // The persisted order item, read from the saved order rather than // from the form that created it. Scoped to the row that carries // the sku, because the column classes are on the header cells @@ -395,5 +444,135 @@ test.describe('Creating an order in the admin', () => { // the next spec inherits. await grid.clearFilters(); }); + + await test.step('invoicing it takes the payment', async () => { + await page.goto(adminUrl(`sales/order/view/order_id/${orderId}/`)); + + const invoice = page.locator(orderForm.invoiceButton); + await expect( + invoice, + 'a pending order paid by an offline method should offer an invoice', + ).toBeVisible(); + await invoice.click(); + + await expect(page).toHaveURL(/order_invoice\/new/); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('New Invoice'); + + // Deliberately left alone rather than cleared. It ships unchecked + // -- Invoice\Create\Items renders no checked attribute -- and + // this spec depends on that: a store that pre-checked it would + // have this step send mail through whatever transport the gate + // installed, and the failure would surface as a mail error on an + // invoice that was otherwise fine. + await expect( + page.locator(orderForm.emailCopy), + 'the invoice email should be opt-in, so this spec sends none', + ).not.toBeChecked(); + + const invoiceTotal = parseMoney( + await page.locator(orderForm.documentGrandTotal).first().innerText(), + ); + expect(invoiceTotal, 'the default invoice should be for the whole order').toBeCloseTo( + grandTotal, + 2, + ); + + await page + .locator(orderForm.submitDocument) + .filter({ hasText: 'Submit Invoice' }) + .first() + .click(); + + await expect(page.locator(orderForm.saved)).toContainText('The invoice has been created.'); + await expect(page).toHaveURL(new RegExp(`sales/order/view/order_id/${orderId}`)); + + // The first real transition: new -> processing. A store whose + // status mapping is broken creates the invoice and leaves the + // order where it was. + await expect( + page.locator(orderForm.orderStatus), + 'an invoiced order is no longer pending', + ).toHaveText('Processing'); + + // Check / money order cannot capture, so Invoice::register() + // marks the invoice paid as it creates it and the order's paid + // total is the whole amount. On a gateway method this would be + // zero until the capture came back, which is why this assertion + // belongs with the offline method the gate installs rather than + // in a helper that claims to hold for any payment. + const paid = parseMoney(await page.locator(orderForm.viewTotalPaid).first().innerText()); + expect(paid, 'an offline invoice is paid as it is created').toBeCloseTo(grandTotal, 2); + + const due = parseMoney(await page.locator(orderForm.viewTotalDue).first().innerText()); + expect(due, 'a fully invoiced order has nothing left due').toBeCloseTo(0, 2); + }); + + await test.step('shipping it completes it', async () => { + const ship = page.locator(orderForm.shipButton); + await expect(ship, 'an invoiced order should still be shippable').toBeVisible(); + await ship.click(); + + await expect(page).toHaveURL(/order_shipment\/new/); + await expect(page.locator(adminSelectors.pageTitle)).toContainText('New Shipment'); + + await page + .locator(orderForm.submitDocument) + .filter({ hasText: 'Submit Shipment' }) + .first() + .click(); + + await expect(page.locator(orderForm.saved)).toContainText('The shipment has been created.'); + await expect( + page.locator(orderForm.orderStatus), + 'invoiced and shipped in full is what Complete means', + ).toHaveText('Complete'); + + // Asserted by absence, which is the only way this page states it: + // canInvoice() and canShip() are both false once every item is + // invoiced and shipped, and Order\View::_construct then adds + // neither button. An order that still offers them is one whose + // item quantities did not move. + await expect( + page.locator(orderForm.invoiceButton), + 'a fully invoiced order should not offer another invoice', + ).toHaveCount(0); + await expect( + page.locator(orderForm.shipButton), + 'a fully shipped order should not offer another shipment', + ).toHaveCount(0); + }); + + await test.step('both documents are listed under the order they belong to', async () => { + // The same synchronous-grid argument as the order grid above: + // sales/general/async_indexing is 0, so sales_invoice_grid and + // sales_shipment_grid are written in the request that saves each + // document. These are separate grids over separate tables, so a + // release that broke one of their indexers would leave the order + // grid above green. + await page.goto(adminUrl('sales/invoice/')); + + const invoices = adminGrid(page, 'sales_order_invoice_grid'); + await invoices.ready(); + await invoices.startUnfiltered(); + await invoices.filterBy('order_increment_id', incrementId); + + await expect(invoices.rows).toHaveCount(1); + await expect(invoices.rows.first()).toContainText(incrementId); + await expect(invoices.rows.first(), 'the invoice should be listed as paid').toContainText( + 'Paid', + ); + await invoices.clearFilters(); + + await page.goto(adminUrl('sales/shipment/')); + + const shipments = adminGrid(page, 'sales_order_shipment_grid'); + await shipments.ready(); + await shipments.startUnfiltered(); + await shipments.filterBy('order_increment_id', incrementId); + + await expect(shipments.rows).toHaveCount(1); + await expect(shipments.rows.first()).toContainText(incrementId); + await shipments.clearFilters(); + }); }); }); From 326c0de497749c251a3555473d54590e3e49ff16 Mon Sep 17 00:00:00 2001 From: Marcel Martinez <martinezlopezmarcel@gmail.com> Date: Sun, 22 Nov 2026 11:03:19 -0600 Subject: [PATCH 42/42] test(e2e): refund the admin order and close it The last transition an offline payment method can reach: complete -> closed. A credit memo is the one sales document that can only be made from an order already paid for, so it goes on the end of the same test rather than into a spec that would have to place and invoice an order of its own first. The step submits the memo as the page prefills it -- item rows at their ordered quantity, creditmemo[shipping_amount] at the shipping still refundable -- and checks the memo's grand total against the order's before submitting, so a release that stopped prefilling either would show up as a refund that came up short rather than as a page that failed. Measured while writing it: - The heading is "New Memo", not "New Credit Memo" -- the only one of the three document pages that does not read like the button reaching it. - Order\View wraps the Credit Memo onclick in confirmSetLocation when the payment method isGateway(), in a plain setLocation when it does not. Check / Money order is not one, so the click navigates rather than opening a dialog. Noted in the README for whoever installs a gateway method later. - The memo page offers a second submit-button, labelled "Refund", when the payment can refund online, so filtering the click by label is what keeps this step from picking the wrong one on such a store. - back_to_stock ships unchecked, so this refund returns nothing to stock and the spec claims nothing about inventory. Deliberate: reservations are a separate subject and would tie the spec to the store's inventory mode. Also widens two notes that were narrower than the truth. order/totals.phtml keys its rows positionally on the saved order too, not just on an invoice -- col-0 Grand Total, col-1 Total Paid, col-2 Total Refunded, col-3 Total Due -- and all three document pages render their submit button through addChild, so none of them has an id. The document grid step now covers sales_creditmemo_grid as well, and asserts the invoice is still listed as Paid afterwards: a memo is placed beside an invoice rather than reversing it. --- _test/demo-package/Test/e2e/README.md | 120 ++++++++++------ .../Test/e2e/admin/create-order.spec.ts | 128 +++++++++++++++--- 2 files changed, 188 insertions(+), 60 deletions(-) diff --git a/_test/demo-package/Test/e2e/README.md b/_test/demo-package/Test/e2e/README.md index e80ab916..1cd8d2be 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -24,7 +24,7 @@ every change to it and runs this suite against the result. | `admin/create-product.spec.ts` | no | admin form -> EAV save -> url rewrite -> indexers -> storefront -> quote | | `admin/create-category.spec.ts` | yes | category tree -> save -> url rewrite -> category index -> storefront listing + menu | | `admin/create-customer.spec.ts` | no | customer form -> save -> read-back -> the storefront refuses the address twice | -| `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid -> invoice -> shipment -> both document grids | +| `admin/create-order.spec.ts` | yes | create-order form -> quote -> shipping rate -> payment -> order -> order grid -> invoice -> shipment -> credit memo -> all three document grids | | `admin/menu-navigation.spec.ts` | no | the admin's own rendered link reaches the product grid, secret key or not | Each area owns a directory, and the Playwright project of the same name @@ -552,50 +552,77 @@ Three more traps on that page, each of which cost a red run to find: The workflow now installs with `max_concurrency=20`; the full account is in `.github/workflows/e2e-README.md`. -### Taking that order to Complete +### Taking that order through the state machine -The same spec then invoices and ships the order it placed. That is the order -state machine -- `new` -> `processing` -> `complete` -- and it is a different -thing from placing the order: the invoice and the shipment are separate -entities, with their own sequence tables, their own grids and, in the -invoice's case, totals of their own. +The same spec then invoices, ships and refunds the order it placed. That is +the order state machine -- `new` -> `processing` -> `complete` -> `closed`, +the whole of it a store with no gateway credentials can reach -- and it is a +different thing from placing the order: the invoice, the shipment and the +credit memo are separate entities, with their own sequence tables, their own +grids and, in two cases, totals of their own. They are steps of the create-order test rather than a spec of their own because they need an order nothing else has invoiced, and placing one costs the dozen round trips above. A second spec would pay that twice to assert something this one is already holding. -Four things are worth knowing before touching those steps. +Five things are worth knowing before touching those steps. -- **Neither submit button has an id.** `Invoice\Create\Items` and - `Magento_Shipping`'s `Create\Items` both add a +- **None of the three submit buttons has an id.** `Invoice\Create\Items`, + `Creditmemo\Create\Items` and `Magento_Shipping`'s `Create\Items` all add a `Backend\Block\Widget\Button` with `class="save submit-button primary"` through `addChild`, not through the `ButtonList` the page's own toolbar uses, so the rendered id is a random `id_3OUDV1Cmg...`. The label is the - only thing that separates "Submit Invoice" from "Submit Shipment", so the - spec filters on it -- which also means a step cannot accidentally submit the - page it only thought it was on. -- **The invoice's totals rows are numbered, not named.** + only thing that separates "Submit Invoice" from "Submit Shipment" from + "Refund Offline", so the spec filters on it -- which also means a step + cannot accidentally submit the page it only thought it was on. The memo page + is the one where that matters twice over: it offers a second + `submit-button`, labelled "Refund", when the payment can refund online. +- **Those totals rows are numbered, not named.** `Magento_Sales::order/totals.phtml` names each row `tr.col-<code>` from the - key of the totals array, and for an invoice those keys are positional. - Measured on a two-line invoice: `col-0` (Grand Total), `col-0` (Subtotal), - `col-1` (Shipping & Handling). The class is neither descriptive nor unique, - so these selectors go by label, the same way the create form's do. Note also - that this is *not* the markup the create form uses -- `order/create/ - totals.phtml` renders `tr.row-totals` -- which is why one spec carries two - sets of totals selectors. -- **The invoice email is opt-in, and the spec asserts that it is.** - `Invoice\Create\Items` renders `#send_email` with no `checked` attribute. - The step asserts it is unchecked rather than clearing it, because a store - that pre-checked it would have this step send mail through whatever - transport the gate installed, and a mail failure would then present as a - broken invoice. -- **The end state is asserted by absence.** Once every item is invoiced and + key of the totals array, and those keys are positional rather than the + totals' own codes. Measured on a two-line order: the invoice renders `col-0` + (Grand Total), `col-0` (Subtotal), `col-1` (Shipping & Handling), and the + saved order renders `col-0` (Grand Total), `col-1` (Total Paid), `col-2` + (Total Refunded), `col-3` (Total Due). The class is neither descriptive nor + unique, so these selectors go by label, the same way the create form's do. + Note also that this is *not* the markup the create form uses -- + `order/create/totals.phtml` renders `tr.row-totals` -- which is why one spec + carries two sets of totals selectors. +- **The customer emails are opt-in, and the spec asserts that they are.** + The invoice page and the credit memo page both render `#send_email` with no + `checked` attribute. Each step asserts it is unchecked rather than clearing + it, because a store that pre-checked it would have the step send mail + through whatever transport the gate installed, and a mail failure would then + present as a broken document. +- **Each end state is asserted by absence.** Once every item is invoiced and shipped, `canInvoice()` and `canShip()` are both false and `Order\View::_construct` adds neither button, so the spec asserts - `#order_invoice` and `#order_ship` are *gone*. An order that still offers - them is one whose item quantities did not move, which a status label alone - would not catch. + `#order_invoice` and `#order_ship` are *gone*; after the refund it asserts + the same of `#order_creditmemo`, which `canCreditmemo()` drops once what was + refunded equals what was paid. An order that still offers one of them is one + whose quantities or amounts did not move, which a status label alone would + not catch. +- **The credit memo button is the one that could have opened a dialog.** + `Order\View` wraps its onclick in `confirmSetLocation` when the payment + method `isGateway()`, and in a plain `setLocation` when it does not. Check / + Money order is not a gateway, so the click navigates. A gate that ever + installed a gateway method would need that dialog answered -- worth knowing + before the failure arrives as a click that appeared to do nothing. + +The memo page is also where two defaults do the work the spec is asserting: +the item rows arrive carrying their ordered quantity and +`creditmemo[shipping_amount]` arrives prefilled with the shipping still +refundable, so submitting the page as it stands refunds the whole order. If a +release stopped prefilling either, the refund would come up short rather than +fail, which is why the step checks the memo's grand total against the order's +before it submits. + +One thing left deliberately unasserted there: `back_to_stock` ships +*unchecked*, so this refund returns nothing to stock and the spec makes no +claim about inventory. Stock movement through MSI's reservations is a separate +subject from the order state machine, and asserting it here would tie this +spec to whichever inventory mode the store was installed in. One more thing the offline payment method buys: Check / Money order cannot capture, so `Invoice::register()` marks the invoice paid as it creates it and @@ -604,6 +631,10 @@ method both would stay at zero until the capture came back. That assertion belongs with the payment method this gate installs, not in a helper that claims to hold for any of them. +Refunding the order does not undo any of that. The invoice stays **Paid** -- +the spec asserts that after the refund, in the grid -- because a credit memo +is a document placed beside it rather than a reversal of it. + ### The storefront half of an admin spec is a different visitor Three admin specs cross into the storefront to prove the save reached a @@ -630,17 +661,17 @@ cookies costs one request's worth of session and removes the class. The `awaitFormKey` wait above does not help here -- there the page has not caught up with the cookie yet, and here the cookie itself belongs to somebody else. -### Three grids a save does update, and one it does not +### Four grids a save does update, and one it does not `admin/create-order.spec.ts` asserts the order appears in the order grid, and -the invoice and the shipment in theirs -- three separate grids over three -separate tables, so a release that broke one indexer cannot hide behind -another. `admin/create-customer.spec.ts` deliberately does not assert the -customer grid. The difference is in the shipped configuration, not in the +the invoice, the shipment and the credit memo in theirs -- four separate grids +over four separate tables, so a release that broke one indexer cannot hide +behind another. `admin/create-customer.spec.ts` deliberately does not assert +the customer grid. The difference is in the shipped configuration, not in the specs: `sales/general/async_indexing` is `0`, so `sales_order_grid`, -`sales_invoice_grid` and `sales_shipment_grid` are each written in the request -that saves their entity, while `customer_grid` is a scheduled indexer that -this store has no cron to run. +`sales_invoice_grid`, `sales_shipment_grid` and `sales_creditmemo_grid` are +each written in the request that saves their entity, while `customer_grid` is +a scheduled indexer that this store has no cron to run. One is a fair assertion. The other would be a red test against a store that is working correctly, which is the worst kind to put in front of someone deciding @@ -913,13 +944,14 @@ least two in the `<configs>` block. ## What the checkout specs do not cover -A real payment gateway, taxes, discounts, multi-address shipping, and the -refund half of the order's life -- credit memos. Each wants fixtures or -credentials of its own, and none of them is on the path between "we tagged a -release" and "a shopper can buy something". +A real payment gateway, taxes, discounts, multi-address shipping, and partial +documents -- half an invoice, a split shipment, a refund of one line. Each +wants fixtures or credentials of its own, and none of them is on the path +between "we tagged a release" and "a shopper can buy something". Both ways of buying are covered: `guest-checkout` as a visitor and `customer-checkout` as a shopper with an account, an address book entry and an order history. `admin/create-order` covers the third front end onto the same quote model, carrier pool and payment pool, and then takes its own order -through the state machine -- see below. +through the whole state machine an offline payment method can reach -- +`new` -> `processing` -> `complete` -> `closed`. diff --git a/_test/demo-package/Test/e2e/admin/create-order.spec.ts b/_test/demo-package/Test/e2e/admin/create-order.spec.ts index 0382ab01..0bcc9c7b 100644 --- a/_test/demo-package/Test/e2e/admin/create-order.spec.ts +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -47,7 +47,11 @@ import { parseMoney } from '../storefront/support'; * They are steps of this test rather than a spec of their own because they * need an order that nothing else has invoiced, and placing one costs the * dozen round trips above. A second spec would pay that twice to assert - * something this one is already holding in its hand. + * something this one is already holding in its hand. The credit memo at the + * end is there for the same reason, and it is the one document that can only + * be made from an order already paid for: new -> processing -> complete -> + * closed is the whole of the order state machine a store with no gateway + * credentials can reach. */ const orderForm = { @@ -100,6 +104,12 @@ const orderForm = { // two lines of the shipping step. invoiceButton: '#order_invoice', shipButton: '#order_ship', + // order_creditmemo is added while canCreditmemo(), i.e. while the order + // has been paid for more than it has been refunded. Its onclick is a + // plain setLocation here: Order\View wraps it in confirmSetLocation only + // when the payment method isGateway(), and Check / Money order is not + // one, so this click navigates rather than opening a dialog. + creditMemoButton: '#order_creditmemo', // The invoice page and the shipment page submit through the same widget. // Invoice\Create\Items and Shipping's Create\Items both add a // Backend\Widget\Button with class "save submit-button primary" and no @@ -108,18 +118,22 @@ const orderForm = { // think they are on. submitDocument: 'button.submit-button', emailCopy: '#send_email', - // The invoice page and the saved order render their totals through - // Magento_Sales::order/totals.phtml, which is not the markup the create - // form above uses -- order/create/totals.phtml renders tr.row-totals -- - // so this spec needs two sets of totals selectors. + // The saved order and the three document pages render their totals + // through Magento_Sales::order/totals.phtml, which is not the markup the + // create form above uses -- order/create/totals.phtml renders + // tr.row-totals -- so this spec needs two sets of totals selectors. // // Addressed by label for a second reason as well. totals.phtml names each - // row tr.col-<code> from the key of the totals array, and the invoice's - // keys are positional: measured on a two-line invoice, the rows come back - // as col-0 (Grand Total), col-0 (Subtotal) and col-1 (Shipping), so the - // class says nothing about what the row holds and is not even unique. + // row tr.col-<code> from the key of the totals array, and those keys are + // positional, not the totals' own codes. Measured: the invoice's rows are + // col-0 (Grand Total), col-0 (Subtotal), col-1 (Shipping), and the saved + // order's are col-0 (Grand Total), col-1 (Total Paid), col-2 (Total + // Refunded), col-3 (Total Due). The class says nothing about what the row + // holds and is not even unique. documentGrandTotal: '#invoice_totals tr:has-text("Grand Total") .price', + creditMemoGrandTotal: '.creditmemo-totals tr:has-text("Grand Total") .price', viewTotalPaid: 'table.order-subtotal-table tr:has-text("Total Paid") .price', + viewTotalRefunded: 'table.order-subtotal-table tr:has-text("Total Refunded") .price', viewTotalDue: 'table.order-subtotal-table tr:has-text("Total Due") .price', }; @@ -191,7 +205,7 @@ test.describe('Creating an order in the admin', () => { // the form, on a store that may also be building static assets. test.setTimeout(300_000); - test('@admin takes an order from placed to shipped', async ({ page }) => { + test('@admin takes an order from placed to refunded', async ({ page }) => { const form = formReloads(page); const stamp = `${Date.now()}`; const customer = { @@ -542,13 +556,79 @@ test.describe('Creating an order in the admin', () => { ).toHaveCount(0); }); - await test.step('both documents are listed under the order they belong to', async () => { + await test.step('refunding it closes it', async () => { + const creditMemo = page.locator(orderForm.creditMemoButton); + await expect( + creditMemo, + 'an order that has been paid for should be refundable', + ).toBeVisible(); + await creditMemo.click(); + + await expect(page).toHaveURL(/order_creditmemo\/new/); + // "New Memo", not "New Credit Memo". Asserted because it is the + // one of these three pages whose heading does not read the way + // the button that reached it does. + await expect(page.locator(adminSelectors.pageTitle)).toContainText('New Memo'); + + await expect( + page.locator(orderForm.emailCopy), + 'the credit memo email should be opt-in too', + ).not.toBeChecked(); + + // The memo arrives filled in for the whole order: the item rows + // carry their ordered quantity and creditmemo[shipping_amount] + // is prefilled with the shipping that is still refundable, so + // submitting it as it stands refunds everything. If a release + // ever stopped prefilling the shipping, this is the assertion + // that says so -- the refund would simply come up short. + const refundTotal = parseMoney( + await page.locator(orderForm.creditMemoGrandTotal).first().innerText(), + ); + expect( + refundTotal, + 'the default memo should refund the whole order, shipping included', + ).toBeCloseTo(grandTotal, 2); + + // Refund Offline is the only button an offline method offers -- + // Creditmemo\Create\Items adds "Refund" as well only when the + // payment can refund online. Filtering on the label means a store + // that did offer both does not have this step pick by accident. + await page + .locator(orderForm.submitDocument) + .filter({ hasText: 'Refund Offline' }) + .first() + .click(); + + await expect(page.locator(orderForm.saved)).toContainText('You created the credit memo.'); + await expect(page).toHaveURL(new RegExp(`sales/order/view/order_id/${orderId}`)); + + // The last transition this store can reach: complete -> closed. + await expect( + page.locator(orderForm.orderStatus), + 'an order refunded in full is closed', + ).toHaveText('Closed'); + + const refunded = parseMoney( + await page.locator(orderForm.viewTotalRefunded).first().innerText(), + ); + expect(refunded, 'the whole amount should be refunded').toBeCloseTo(grandTotal, 2); + + // Asserted by absence again: canCreditmemo() compares what was + // paid against what was refunded, so a second memo is offered + // only if the first one did not account for everything. + await expect( + page.locator(orderForm.creditMemoButton), + 'a fully refunded order should not offer another credit memo', + ).toHaveCount(0); + }); + + await test.step('every document is listed under the order it belongs to', async () => { // The same synchronous-grid argument as the order grid above: - // sales/general/async_indexing is 0, so sales_invoice_grid and - // sales_shipment_grid are written in the request that saves each - // document. These are separate grids over separate tables, so a - // release that broke one of their indexers would leave the order - // grid above green. + // sales/general/async_indexing is 0, so sales_invoice_grid, + // sales_shipment_grid and sales_creditmemo_grid are each written + // in the request that saves their entity. These are three grids + // over three tables, so a release that broke one of their + // indexers would leave the order grid above green. await page.goto(adminUrl('sales/invoice/')); const invoices = adminGrid(page, 'sales_order_invoice_grid'); @@ -558,6 +638,8 @@ test.describe('Creating an order in the admin', () => { await expect(invoices.rows).toHaveCount(1); await expect(invoices.rows.first()).toContainText(incrementId); + // Still Paid after the refund: refunding the order does not + // unpay its invoice, it adds a credit memo beside it. await expect(invoices.rows.first(), 'the invoice should be listed as paid').toContainText( 'Paid', ); @@ -573,6 +655,20 @@ test.describe('Creating an order in the admin', () => { await expect(shipments.rows).toHaveCount(1); await expect(shipments.rows.first()).toContainText(incrementId); await shipments.clearFilters(); + + await page.goto(adminUrl('sales/creditmemo/')); + + const memos = adminGrid(page, 'sales_order_creditmemo_grid'); + await memos.ready(); + await memos.startUnfiltered(); + await memos.filterBy('order_increment_id', incrementId); + + await expect(memos.rows).toHaveCount(1); + await expect(memos.rows.first()).toContainText(incrementId); + await expect(memos.rows.first(), 'the memo should be listed as refunded').toContainText( + 'Refunded', + ); + await memos.clearFilters(); }); }); });