diff --git a/.github/workflows/_internal-e2e.yaml b/.github/workflows/_internal-e2e.yaml new file mode 100644 index 00000000..18fe9bb8 --- /dev/null +++ b/.github/workflows/_internal-e2e.yaml @@ -0,0 +1,379 @@ +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 and admin tests" + 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: actions/_test/demo-package/Test/e2e + # 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 + # opinions about the admin URL is a 404 that looks like a broken admin. + ADMIN_FRONTNAME: "admin" + # 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 puts the Warden CLI + # in warden/ there, which is where this repository keeps that action. + - uses: actions/checkout@v6 + with: + path: actions + + # 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: + 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: ./actions/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 + varnish_as_page_cache: 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 + backend_frontname: ${{ env.ADMIN_FRONTNAME }} + run_static_content_deploy: 1 + # 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: 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 + 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: 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" (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 + # (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 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 + + # 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 + # 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: + BASE_URL: ${{ steps.warden.outputs.base_url }} + 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 + + # 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 + 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. + 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)" + + # 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" ;; + 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. No spec 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} |" + 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 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 + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + MODULES=() + for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do + # 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 + MODULES+=("${MODULE}") + fi + done + + # 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 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 + + # 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 + working-directory: ./_ghamagento + shell: bash + env: + PROFILE: ${{ github.workspace }}/${{ env.E2E_DIRECTORY }}/fixtures/mageos-e2e.xml + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + ${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: + 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 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 + + # 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 + + 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 + # or whether Traefik had a route. Nothing here may fail the job. + - 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 + with: + name: playwright-report + path: | + ${{ env.E2E_DIRECTORY }}/playwright-report + ${{ env.E2E_DIRECTORY }}/test-results + retention-days: 30 + if-no-files-found: ignore diff --git a/.github/workflows/e2e-README.md b/.github/workflows/e2e-README.md new file mode 100644 index 00000000..e9738fae --- /dev/null +++ b/.github/workflows/e2e-README.md @@ -0,0 +1,307 @@ +# 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 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 + +| 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. + +## 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` | +| `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. + +## 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 +`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. + +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" +``` + +An admin suite also **writes to the store**. The specs in this repository +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. + +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. + +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. 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 +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. + +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 +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. 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: + 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: "e2e-report-${{ 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..18ef9f18 --- /dev/null +++ b/.github/workflows/e2e.yaml @@ -0,0 +1,486 @@ +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. +# +# 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: + 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 Magento/backend MageOS/m137-admin-theme" + description: > + Space separated themes to deploy static content for. Empty deploys + every theme, which is considerably slower. + + 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 + 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; 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 + # 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, not in + flags here: a CLI flag overrides the config. + 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 -- + right for a suite that only asserts on what 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/. + SUITE: suite + # 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 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: + 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 + varnish_as_page_cache: 1 + 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 + static_content_themes: ${{ inputs.static_content_themes }} + + # 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 + 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: 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" (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 + # (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 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 + + # 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 + + # 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: + BASE_URL: ${{ steps.warden.outputs.base_url }} + 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 + + # 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 + 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. + 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)" + + # 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" ;; + 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. No spec 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} |" + 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 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 + shell: bash + run: | + export WARDEN="$(dirname $(pwd))/warden/bin/warden" + + MODULES=() + for MODULE in MageOS_PasskeyAuth Magento_TwoFactorAuth; do + # 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 + MODULES+=("${MODULE}") + fi + done + + # 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 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 + + # 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 + 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 + + # 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: + 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 }} + MAGENTO_ADMIN_USER: ${{ env.ADMIN_USER }} + MAGENTO_ADMIN_PASSWORD: ${{ env.ADMIN_PASSWORD }} + 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 + + 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 + # or whether Traefik had a route. Nothing here may fail the job. + - 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 outlives 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 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..f13089b0 --- /dev/null +++ b/_test/demo-package/Test/e2e/.env.example @@ -0,0 +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 new file mode 100644 index 00000000..6fb83b67 --- /dev/null +++ b/_test/demo-package/Test/e2e/.gitignore @@ -0,0 +1,5 @@ +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 36c8d271..1cd8d2be 100644 --- a/_test/demo-package/Test/e2e/README.md +++ b/_test/demo-package/Test/e2e/README.md @@ -1,5 +1,957 @@ -cd e2e -npm install -D @playwright/test -npx playwright install -npm install -D dotenv -npx playwright test hello-magento.spec.ts +# Browser tests + +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 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 +every change to it and runs this suite against the result. + +| Spec | Needs fixtures | Asserts | +| --- | --- | --- | +| `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 | +| `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 -> 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 +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, +reading the number out of a rendered price, registering an account, filling 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. + +## 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 +``` + +`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` +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 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 +`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 +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`). + +### 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`, +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. + +### 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 `` | `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. + +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 +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. + +### 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 +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 +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 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 +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. + +### 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. + +### 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 +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//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. + +**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 +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. + +### 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 - 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 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`. + +### Taking that order through the state machine + +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. + +Five things are worth knowing before touching those steps. + +- **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" 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-` from the + 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*; 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 +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. + +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 +shopper. They do it from a fresh session, by `asShopper(page)` in +`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 +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. 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. + +### 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, 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`, `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 +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 +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//` 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 +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: 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 +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. + +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 +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 +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. 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. + +## 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 +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`. 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 +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 specs do not cover + +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 whole state machine an offline payment method can reach -- +`new` -> `processing` -> `complete` -> `closed`. 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..9286e8b1 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-category.spec.ts @@ -0,0 +1,220 @@ +import { expect, test } from '../fixtures'; +import { adminSelectors, adminUrl } from './support'; +import { categoryUrl, luma } from '../storefront/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..85716ce8 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-customer.spec.ts @@ -0,0 +1,149 @@ +import { expect, test } from '../fixtures'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +import { asShopper, awaitFormKey } from '../storefront/support'; +import { luma } from '../storefront/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. + // 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(); + + 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!'); + + // 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( + 'There is already an account with this email address', + ); + }); + }); +}); 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..0bcc9c7b --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-order.spec.ts @@ -0,0 +1,674 @@ +import { type Page, type Request } from '@playwright/test'; +import { expect, test } from '../fixtures'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +import { parseMoney } from '../storefront/support'; + +/** + * 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. + * + * ## 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. 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 = { + // 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', + 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', + // 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', + // 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 + // 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 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 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', +}; + +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 takes an order from placed to refunded', 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. + // + // 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.skuFilter).press('Enter'); + 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; + let grandTotal = 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()); + 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 = ''; + let orderId = ''; + + 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+$/); + + // 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 + // 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(); + }); + + 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('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, + // 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'); + 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); + // 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', + ); + 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(); + + 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(); + }); + }); +}); 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..f3894efe --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/create-product.spec.ts @@ -0,0 +1,226 @@ +import { expect, test } from '../fixtures'; +import { adminGrid, adminSelectors, adminUrl } from './support'; +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 + * 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"]', + // 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 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 + // 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 () => { + // 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); + 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 () => { + // 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); + // 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 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 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 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 + // 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); + // 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 () => { + 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); + // 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. + 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. + // 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); + 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/login.spec.ts b/_test/demo-package/Test/e2e/admin/login.spec.ts new file mode 100644 index 00000000..099dda0b --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/login.spec.ts @@ -0,0 +1,50 @@ +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 +// 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/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/product-grid.spec.ts b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts new file mode 100644 index 00000000..8e58a423 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/product-grid.spec.ts @@ -0,0 +1,113 @@ +import { expect, test } from '../fixtures'; +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/session.setup.ts b/_test/demo-package/Test/e2e/admin/session.setup.ts new file mode 100644 index 00000000..3ec7a217 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/session.setup.ts @@ -0,0 +1,26 @@ +import { expect, test as setup } from '../fixtures'; +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..6f0ef5f3 --- /dev/null +++ b/_test/demo-package/Test/e2e/admin/support.ts @@ -0,0 +1,213 @@ +import { expect, type Locator, 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. + // + // 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', +}; + +/** + * 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', +}; + +/** + * 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: + * + * - 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/fixtures.ts b/_test/demo-package/Test/e2e/fixtures.ts new file mode 100644 index 00000000..18460917 --- /dev/null +++ b/_test/demo-package/Test/e2e/fixtures.ts @@ -0,0 +1,166 @@ +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/]; + +/** + * 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. 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, 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) + * + * +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 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. + */ +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'); + +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) => { + 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) => { + 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/fixtures/mageos-e2e.xml b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml new file mode 100644 index 00000000..a673cf0c --- /dev/null +++ b/_test/demo-package/Test/e2e/fixtures/mageos-e2e.xml @@ -0,0 +1,104 @@ +<?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. + + 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 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> + <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/hello-magento.spec.ts b/_test/demo-package/Test/e2e/hello-magento.spec.ts deleted file mode 100644 index 37762363..00000000 --- a/_test/demo-package/Test/e2e/hello-magento.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -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."); - } - - const homepageResponsePromise = page.waitForResponse(homepageURL); - await page.goto(homepageURL); - const homepageResponse = await homepageResponsePromise; - expect(homepageResponse.status(), 'Homepage should return 200').toBe(200); - - const pageTtitle = page.getByRole('heading', {level: 1}) - - await expect(pageTtitle, 'Homepage has a visible title').toBeVisible(); - await expect(pageTtitle).toHaveText(/\S+/); - }) -}) 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..d3b90636 100644 --- a/_test/demo-package/Test/e2e/playwright.config.ts +++ b/_test/demo-package/Test/e2e/playwright.config.ts @@ -1,8 +1,68 @@ -import { defineConfig } from '@playwright/test'; +import { defineConfig, devices } from '@playwright/test'; import dotenv from 'dotenv'; +import { adminStateFile } from './admin/support'; 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, + // 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', + }, + 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'] }, + }, + // 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', + testMatch: /storefront[\\/].*\.spec\.ts$/, + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'admin', + testMatch: /admin[\\/].*\.spec\.ts$/, + dependencies: ['admin-session'], + use: { ...devices['Desktop Chrome'], storageState: adminStateFile }, + }, + ], }); diff --git a/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts new file mode 100644 index 00000000..2812bf74 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/customer-account.spec.ts @@ -0,0 +1,116 @@ +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. + * + * 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. 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 -- + * 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. + */ + +test.describe('Storefront customer account', () => { + test('creates an account and signs back into it', { tag: ['@customer'] }, async ({ page }) => { + const customer = newShopper(); + + await test.step('the registration form accepts a new account', async () => { + await registerCustomer(page, customer); + }); + + 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, customerPassword); + 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/storefront/customer-checkout.spec.ts b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts new file mode 100644 index 00000000..852836d1 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/customer-checkout.spec.ts @@ -0,0 +1,252 @@ +import { expect, test } from '../fixtures'; +import { luma } from './luma'; +import { + awaitFormKey, + 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. + * + * 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', () => { + 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 awaitFormKey(page); + 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 awaitFormKey(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 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.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 new file mode 100644 index 00000000..3b2db34f --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/guest-checkout.spec.ts @@ -0,0 +1,123 @@ +import { type Page } from '@playwright/test'; +import { expect, test } from '../fixtures'; +import { luma } from './luma'; +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 +// 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', +}; + +async function fillShippingAddress(page: Page) { + const form = page.locator(luma.shippingForm); + + // 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 fillAddressFields(form); +} + +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(luma.productPrice).first()).toBeVisible(); + await expect(page.locator(luma.addToCart)).toBeEnabled(); + }); + + 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 + // 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}/); + }); + }); +}); diff --git a/_test/demo-package/Test/e2e/storefront/hello-magento.spec.ts b/_test/demo-package/Test/e2e/storefront/hello-magento.spec.ts new file mode 100644 index 00000000..9d4ca2b5 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/hello-magento.spec.ts @@ -0,0 +1,40 @@ +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 +// 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('/'); + + await test.step('the homepage responds 200', async () => { + expect(response?.status(), 'the homepage should respond 200').toBe(200); + }); + + 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 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/storefront/luma.ts b/_test/demo-package/Test/e2e/storefront/luma.ts new file mode 100644 index 00000000..31f57bfd --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/luma.ts @@ -0,0 +1,184 @@ +/** + * 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', + // 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', + productPrice: '.product-info-main .price', + // The sku Luma prints under the product's details. On a configurable this + // 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 + // 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 + // neither. + productStock: '.stock.available', + productQty: '#qty', + 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', + 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', + 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', + // 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 + // 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"]', + + // 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', + + // 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"]', + + // 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', + // 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', +}; + +/** + * 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}`; +} + +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}`; +} diff --git a/_test/demo-package/Test/e2e/storefront/product-page.spec.ts b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts new file mode 100644 index 00000000..b97b47d5 --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/product-page.spec.ts @@ -0,0 +1,143 @@ +import { expect, test } from '../fixtures'; +import { luma } from './luma'; +import { awaitFormKey, parseMoney, selectRequiredOptions } from './support'; + +/** + * 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 awaitFormKey(page); + 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/search.spec.ts b/_test/demo-package/Test/e2e/storefront/search.spec.ts new file mode 100644 index 00000000..54eee54f --- /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 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 + * 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); + }); +}); diff --git a/_test/demo-package/Test/e2e/storefront/support.ts b/_test/demo-package/Test/e2e/storefront/support.ts new file mode 100644 index 00000000..ec77c0be --- /dev/null +++ b/_test/demo-package/Test/e2e/storefront/support.ts @@ -0,0 +1,251 @@ +import { expect, type Locator, 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. + * + * 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(); + await option.waitFor({ state: 'visible' }); + 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); + // 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); + } + } +} + +/** + * 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, '')); +} + +/** + * 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. + * + * 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(); +} + +/** + * 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 awaitFormKey(page); + await page.locator(luma.registerSubmit).click(); +} diff --git a/warden/setup-environment/README.md b/warden/setup-environment/README.md new file mode 100644 index 00000000..8ce84c9c --- /dev/null +++ b/warden/setup-environment/README.md @@ -0,0 +1,140 @@ +# 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. | +| `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. | +| `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`. | +| `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. | +| `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. | + +### 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 +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 | +| --- | --- | +| `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..c9a03097 100644 --- a/warden/setup-environment/action.yml +++ b/warden/setup-environment/action.yml @@ -78,11 +78,99 @@ 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: "./" 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)." + + 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" + 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 +192,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 +240,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,12 +287,28 @@ 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 + 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 @@ -211,6 +318,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 +382,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 +412,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) @@ -342,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 @@ -351,6 +477,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 @@ -374,6 +519,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