From a521d0e3d88d149ac4b2a8c9ccc665223b073059 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Fri, 20 Nov 2026 14:26:35 +0100 Subject: [PATCH 01/24] test: add Playwright end-to-end tests Add an e2e/ package that runs Playwright from the official runner image against a fresh all-in-one Lowcoder container and a PostgreSQL sidecar, started and removed by e2e/scripts/run-in-docker.sh. Tests: sign-up, sign-in and sign-out, wrong password, drag from the insert panel, editing a property, published view versus draft, public and private apps for a visitor, trash and restore, invited member permissions, and PostgreSQL queries in the editor and in a published app. Every browser context blocks all origins except the app under test, so no request reaches lowcoder.cloud or HubSpot; there is no way to switch this off. Claude-Session: https://claude.ai/code/session_015KPtHKPW6LJoxzf4tn8Rtm --- e2e/.gitignore | 5 + e2e/fixtures/sql/init.sql | 3 + e2e/package-lock.json | 91 +++++++ e2e/package.json | 17 ++ e2e/playwright.config.ts | 45 ++++ e2e/scripts/run-in-docker.sh | 182 ++++++++++++++ e2e/src/api/client.ts | 278 ++++++++++++++++++++++ e2e/src/constants.ts | 116 +++++++++ e2e/src/dsl/builders.ts | 97 ++++++++ e2e/src/fixtures.ts | 92 +++++++ e2e/src/pages/AppListPage.ts | 25 ++ e2e/src/pages/AppViewPage.ts | 31 +++ e2e/src/pages/AuthPage.ts | 31 +++ e2e/src/pages/EditorPage.ts | 59 +++++ e2e/src/pages/LoginPage.ts | 41 ++++ e2e/src/pages/PropertyPanel.ts | 23 ++ e2e/src/pages/QueryPanel.ts | 28 +++ e2e/src/pages/UserMenu.ts | 12 + e2e/src/postgres.ts | 17 ++ e2e/tests/apps/public-app.spec.ts | 31 +++ e2e/tests/apps/publish-draft.spec.ts | 36 +++ e2e/tests/apps/trash-restore.spec.ts | 27 +++ e2e/tests/auth/login.spec.ts | 42 ++++ e2e/tests/datasource/postgres.spec.ts | 69 ++++++ e2e/tests/editor/edit-property.spec.ts | 33 +++ e2e/tests/smoke/editor-drag.spec.ts | 31 +++ e2e/tests/smoke/network-guard.spec.ts | 36 +++ e2e/tests/smoke/published-view.spec.ts | 22 ++ e2e/tests/smoke/signup.spec.ts | 16 ++ e2e/tests/workspace/member-access.spec.ts | 49 ++++ e2e/tsconfig.json | 14 ++ 31 files changed, 1599 insertions(+) create mode 100644 e2e/.gitignore create mode 100644 e2e/fixtures/sql/init.sql create mode 100644 e2e/package-lock.json create mode 100644 e2e/package.json create mode 100644 e2e/playwright.config.ts create mode 100755 e2e/scripts/run-in-docker.sh create mode 100644 e2e/src/api/client.ts create mode 100644 e2e/src/constants.ts create mode 100644 e2e/src/dsl/builders.ts create mode 100644 e2e/src/fixtures.ts create mode 100644 e2e/src/pages/AppListPage.ts create mode 100644 e2e/src/pages/AppViewPage.ts create mode 100644 e2e/src/pages/AuthPage.ts create mode 100644 e2e/src/pages/EditorPage.ts create mode 100644 e2e/src/pages/LoginPage.ts create mode 100644 e2e/src/pages/PropertyPanel.ts create mode 100644 e2e/src/pages/QueryPanel.ts create mode 100644 e2e/src/pages/UserMenu.ts create mode 100644 e2e/src/postgres.ts create mode 100644 e2e/tests/apps/public-app.spec.ts create mode 100644 e2e/tests/apps/publish-draft.spec.ts create mode 100644 e2e/tests/apps/trash-restore.spec.ts create mode 100644 e2e/tests/auth/login.spec.ts create mode 100644 e2e/tests/datasource/postgres.spec.ts create mode 100644 e2e/tests/editor/edit-property.spec.ts create mode 100644 e2e/tests/smoke/editor-drag.spec.ts create mode 100644 e2e/tests/smoke/network-guard.spec.ts create mode 100644 e2e/tests/smoke/published-view.spec.ts create mode 100644 e2e/tests/smoke/signup.spec.ts create mode 100644 e2e/tests/workspace/member-access.spec.ts create mode 100644 e2e/tsconfig.json diff --git a/e2e/.gitignore b/e2e/.gitignore new file mode 100644 index 000000000..e8c9224cf --- /dev/null +++ b/e2e/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +playwright-report/ +test-results/ +blob-report/ +playwright/.auth/ diff --git a/e2e/fixtures/sql/init.sql b/e2e/fixtures/sql/init.sql new file mode 100644 index 000000000..a4f3433d4 --- /dev/null +++ b/e2e/fixtures/sql/init.sql @@ -0,0 +1,3 @@ +-- Data of the PostgreSQL sidecar the data source tests read. +CREATE TABLE items (id integer PRIMARY KEY, name text NOT NULL); +INSERT INTO items (id, name) VALUES (1, 'alpha'), (2, 'beta'); diff --git a/e2e/package-lock.json b/e2e/package-lock.json new file mode 100644 index 000000000..36398ce21 --- /dev/null +++ b/e2e/package-lock.json @@ -0,0 +1,91 @@ +{ + "name": "lowcoder-e2e", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "lowcoder-e2e", + "devDependencies": { + "@playwright/test": "1.64.0", + "@types/node": "^22.10.0", + "typescript": "^5.6.0" + } + }, + "node_modules/@playwright/test": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.0.tgz", + "integrity": "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/playwright": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", + "integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/e2e/package.json b/e2e/package.json new file mode 100644 index 000000000..487b27fe5 --- /dev/null +++ b/e2e/package.json @@ -0,0 +1,17 @@ +{ + "name": "lowcoder-e2e", + "private": true, + "description": "End-to-end tests of the Lowcoder all-in-one image, run with Playwright from scripts/run-in-docker.sh", + "scripts": { + "test": "playwright test", + "test:smoke": "playwright test --grep @smoke", + "test:core": "playwright test --grep @core", + "report": "playwright show-report", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@playwright/test": "1.64.0", + "@types/node": "^22.10.0", + "typescript": "^5.6.0" + } +} diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts new file mode 100644 index 000000000..262b20299 --- /dev/null +++ b/e2e/playwright.config.ts @@ -0,0 +1,45 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** Origin of the Lowcoder instance under test. The run script sets it to the app container on the Docker network. */ +const BASE_URL = process.env.LOWCODER_BASE_URL; +if (!BASE_URL) { + throw new Error("LOWCODER_BASE_URL is not set. Run the suite through e2e/scripts/run-in-docker.sh."); +} + +const IS_CI = !!process.env.CI; +const TEST_TIMEOUT_MS = 60_000; +const EXPECT_TIMEOUT_MS = 15_000; +/** The insert panel and the canvas fit without scrolling at this size. */ +const VIEWPORT = { width: 1600, height: 1000 }; +const CI_RETRIES = 1; +/** + * Parallel workers. Four is what the editor's save race was measured with; with many more the machine is loaded so + * much that the fixed editor wait of EDITOR_SETTLE_MS is no longer enough (see constants.ts). + */ +const DEFAULT_WORKERS = 4; + +export default defineConfig({ + testDir: "./tests", + outputDir: "./test-results", + fullyParallel: true, + workers: Number(process.env.E2E_WORKERS || DEFAULT_WORKERS), + forbidOnly: IS_CI, + retries: IS_CI ? CI_RETRIES : 0, + timeout: TEST_TIMEOUT_MS, + expect: { timeout: EXPECT_TIMEOUT_MS }, + reporter: [ + ["list"], + ["html", { outputFolder: "./playwright-report", open: "never" }], + ["junit", { outputFile: "./test-results/junit.xml" }], + ], + use: { + baseURL: BASE_URL, + // With service workers blocked, every request of the page goes through the context route of the network guard. + serviceWorkers: "block", + trace: "retain-on-failure", + video: "retain-on-failure", + screenshot: "only-on-failure", + viewport: VIEWPORT, + }, + projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"], viewport: VIEWPORT } }], +}); diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh new file mode 100755 index 000000000..d1605aef3 --- /dev/null +++ b/e2e/scripts/run-in-docker.sh @@ -0,0 +1,182 @@ +#!/bin/bash + +## +## Runs the Lowcoder end-to-end tests (Playwright) against a fresh all-in-one container. +## +## Starts the all-in-one image on its own Docker network, waits until the API answers, runs the tests from the +## official Playwright image on the same network (the app is reachable by its container name), and removes +## the container and the network when it ends, however it ends. +## +## Usage (from any directory): +## e2e/scripts/run-in-docker.sh [playwright test arguments] +## e2e/scripts/run-in-docker.sh --grep @smoke +## e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 +## +## Environment: +## LOWCODER_E2E_IMAGE image under test (default lowcoderorg/lowcoder-ce:3.0.0), e.g. a locally built one +## PLAYWRIGHT_IMAGE runner image; its version must equal @playwright/test in e2e/package-lock.json +## (default mcr.microsoft.com/playwright:v1.64.0-noble) +## POSTGRES_IMAGE PostgreSQL sidecar for the data source tests (pinned by digest) +## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts +## E2E_EDITOR_SETTLE_MS wait after opening the editor (see EDITOR_SETTLE_MS in e2e/src/constants.ts) +## +## Results: e2e/playwright-report (HTML), e2e/test-results (JUnit, traces, videos, screenshots of failures). +## Exit code: the one of `playwright test`; non-zero when the app does not start or the versions differ. +## +## One-off, after changing e2e/package.json: regenerate the lockfile inside the runner image +## docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD/e2e":/work -w /work \ +## mcr.microsoft.com/playwright:v1.64.0-noble npm install --no-audit --no-fund +## +## Also starts a PostgreSQL sidecar with the data of fixtures/sql/init.sql; the tests reach it by container name +## (the name is passed as E2E_POSTGRES_HOST). +## +## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than +## PostgreSQL. +## + +set -euo pipefail + +readonly DEFAULT_APP_IMAGE="lowcoderorg/lowcoder-ce:3.0.0" +readonly DEFAULT_PLAYWRIGHT_IMAGE="mcr.microsoft.com/playwright:v1.64.0-noble" +readonly APP_IMAGE="${LOWCODER_E2E_IMAGE:-$DEFAULT_APP_IMAGE}" +readonly PLAYWRIGHT_IMAGE="${PLAYWRIGHT_IMAGE:-$DEFAULT_PLAYWRIGHT_IMAGE}" + +readonly DEFAULT_POSTGRES_IMAGE="postgres:17-alpine@sha256:778d0b486d6daa02b77434d0358ec57a1b21fd8b6d22ac2eef56a33e816928f6" +readonly POSTGRES_IMAGE="${POSTGRES_IMAGE:-$DEFAULT_POSTGRES_IMAGE}" +# Must equal POSTGRES in e2e/src/constants.ts +readonly POSTGRES_DATABASE="shop" +readonly POSTGRES_USER="postgres" +readonly POSTGRES_PASSWORD="e2e-postgres-password" + +readonly APP_PORT=3000 +readonly READY_PATH="/api/configs" +# Seconds to wait for the app to answer, and between two checks +readonly STARTUP_TIMEOUT=300 +readonly POLL_INTERVAL=2 +readonly LOG_TAIL_LINES=60 + +readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +readonly E2E_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +readonly LOCKFILE="$E2E_DIR/package-lock.json" + +readonly NAME_PREFIX="lowcoder-e2e-$$" +readonly NETWORK="${NAME_PREFIX}-net" +readonly APP_CONTAINER="${NAME_PREFIX}-app" +readonly POSTGRES_CONTAINER="${NAME_PREFIX}-pg" +readonly RUNNER_CONTAINER="${NAME_PREFIX}-runner" + +log() { + echo "[$(date +%H:%M:%S)] $*" +} + +fail() { + echo "ERROR: $*" >&2 + exit 1 +} + +cleanup() { + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" > /dev/null 2>&1 || true + docker network rm "$NETWORK" > /dev/null 2>&1 || true +} +trap cleanup EXIT + +# Version of @playwright/test locked in package-lock.json +locked_playwright_version() { + awk '/"node_modules\/@playwright\/test"/ { found = 1 } + found && /"version"/ { gsub(/[",]/, "", $2); print $2; exit }' "$LOCKFILE" +} + +# Version in the tag of the runner image, v1.64.0-noble -> 1.64.0 +image_playwright_version() { + local tag="${PLAYWRIGHT_IMAGE##*:}" + tag="${tag#v}" + echo "${tag%%-*}" +} + +check_playwright_versions() { + [ -f "$LOCKFILE" ] || fail "$LOCKFILE is missing; see the usage comment of this script to generate it" + local locked image + locked="$(locked_playwright_version)" + image="$(image_playwright_version)" + [ -n "$locked" ] || fail "no @playwright/test version found in $LOCKFILE" + if [ "$locked" != "$image" ]; then + fail "@playwright/test $locked (package-lock.json) does not match the runner image $PLAYWRIGHT_IMAGE ($image)" + fi +} + +start_app() { + local publish=() + if [ -n "${E2E_HOST_PORT:-}" ]; then + publish=(-p "127.0.0.1:${E2E_HOST_PORT}:${APP_PORT}") + fi + log "Starting $APP_IMAGE as $APP_CONTAINER" + docker run -d --name "$APP_CONTAINER" --network "$NETWORK" "${publish[@]}" \ + -e LOWCODER_PUBLIC_URL="http://${APP_CONTAINER}:${APP_PORT}/" \ + -e LOWCODER_SUPERUSER_PASSWORD="$(head -c 18 /dev/urandom | od -An -tx1 | tr -d ' \n')" \ + "$APP_IMAGE" > /dev/null +} + +start_postgres() { + log "Starting $POSTGRES_IMAGE as $POSTGRES_CONTAINER" + docker run -d --name "$POSTGRES_CONTAINER" --network "$NETWORK" \ + -e POSTGRES_DB="$POSTGRES_DATABASE" -e POSTGRES_USER="$POSTGRES_USER" -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \ + -v "$E2E_DIR/fixtures/sql":/docker-entrypoint-initdb.d:ro \ + "$POSTGRES_IMAGE" > /dev/null +} + +# The image starts a temporary server for the init scripts, so "accepting connections" alone is too early: +# wait until the seeded table can be read. +wait_for_postgres() { + local waited=0 + until docker exec "$POSTGRES_CONTAINER" psql -U "$POSTGRES_USER" -d "$POSTGRES_DATABASE" -tAc "SELECT count(*) FROM items" > /dev/null 2>&1; do + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$POSTGRES_CONTAINER" >&2 || true + fail "PostgreSQL did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + waited=$((waited + POLL_INTERVAL)) + done + log "PostgreSQL ready after ${waited}s" +} + +wait_for_app() { + local waited=0 + log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" + until docker exec "$APP_CONTAINER" curl -sf "http://localhost:${APP_PORT}${READY_PATH}" > /dev/null 2>&1; do + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$APP_CONTAINER" >&2 || true + fail "the application did not answer on $READY_PATH within ${STARTUP_TIMEOUT}s" + fi + if [ "$(docker inspect -f '{{.State.Running}}' "$APP_CONTAINER" 2>/dev/null)" != "true" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$APP_CONTAINER" >&2 || true + fail "the application container stopped" + fi + sleep "$POLL_INTERVAL" + waited=$((waited + POLL_INTERVAL)) + done + log "Application ready after ${waited}s" +} + +run_tests() { + log "Running Playwright from $PLAYWRIGHT_IMAGE" + local status=0 + # --init and --ipc=host: recommended by Playwright for Chromium in Docker (https://playwright.dev/docs/docker) + docker run --rm --name "$RUNNER_CONTAINER" --network "$NETWORK" --init --ipc=host \ + --user "$(id -u):$(id -g)" -e HOME=/tmp \ + -e CI="${CI:-}" \ + -e LOWCODER_BASE_URL="http://${APP_CONTAINER}:${APP_PORT}" \ + -e E2E_POSTGRES_HOST="$POSTGRES_CONTAINER" \ + -e E2E_EDITOR_SETTLE_MS="${E2E_EDITOR_SETTLE_MS:-}" \ + -v "$E2E_DIR":/work -w /work \ + "$PLAYWRIGHT_IMAGE" \ + sh -c 'npm ci --no-audit --no-fund && npx playwright test "$@"' sh "$@" || status=$? + return "$status" +} + +check_playwright_versions +docker network create "$NETWORK" > /dev/null +start_postgres +start_app +wait_for_postgres +wait_for_app +run_tests "$@" diff --git a/e2e/src/api/client.ts b/e2e/src/api/client.ts new file mode 100644 index 000000000..8266e580c --- /dev/null +++ b/e2e/src/api/client.ts @@ -0,0 +1,278 @@ +import type { APIRequestContext, APIResponse } from "@playwright/test"; +import { + API_OK, + API_PATHS, + APP_TYPE_APPLICATION, + appPermissionsPath, + applicationPath, + appViewPath, + AUTH_ID_EMAIL, + AUTH_SOURCE_EMAIL, + invitationAcceptPath, + NEW_USER_GUIDANCE_STATUS, + publicToAllPath, + publishPath, + recyclePath, + restorePath, + TEST_PASSWORD, +} from "../constants"; + +/** A Lowcoder API call that did not answer with `code === API_OK`. The message carries the response body. */ +export class LowcoderApiError extends Error { + constructor(action: string, status: number, body: string) { + super(`${action} failed: HTTP ${status}, body: ${body}`); + this.name = "LowcoderApiError"; + } +} + +interface ApiEnvelope { + code: number; + message?: string; + data: T; +} + +async function unwrap(action: string, response: APIResponse): Promise { + const text = await response.text(); + let envelope: ApiEnvelope; + try { + envelope = JSON.parse(text) as ApiEnvelope; + } catch { + throw new LowcoderApiError(action, response.status(), text); + } + if (!response.ok() || envelope.code !== API_OK) { + throw new LowcoderApiError(action, response.status(), text); + } + return envelope.data; +} + +export interface RegisteredUser { + email: string; + orgId: string; +} + +interface CurrentUserData { + orgAndRoles: { org: { id: string } }[]; +} + +/** + * Registers a user with e-mail and password. The request context keeps the session cookie, so when it is the + * `page.request` of a browser context the page is logged in as well. + */ +export async function registerUser(request: APIRequestContext, email: string): Promise { + await unwrap( + `register ${email}`, + await request.post(API_PATHS.LOGIN, { + data: { + loginId: email, + password: TEST_PASSWORD, + register: true, + source: AUTH_SOURCE_EMAIL, + authId: AUTH_ID_EMAIL, + }, + }), + ); + await dismissNewUserGuidance(request); + const me = await currentUser(request); + const org = me.orgAndRoles[0]; + if (!org) { + throw new LowcoderApiError(`register ${email}`, 200, "the new user has no workspace"); + } + return { email, orgId: org.org.id }; +} + +/** + * Marks the new-user tour as done. Otherwise the tour (react-joyride) opens on the first visit of the app list + * and its overlay intercepts clicks. The tests that are about the tour itself do not exist yet. + */ +export async function dismissNewUserGuidance(request: APIRequestContext): Promise { + await unwrap( + "dismiss new user guidance", + await request.put(API_PATHS.MARK_USER_STATUS, { data: { type: NEW_USER_GUIDANCE_STATUS, value: true } }), + ); +} + +export async function loginUser(request: APIRequestContext, email: string, password = TEST_PASSWORD): Promise { + await unwrap( + `login ${email}`, + await request.post(API_PATHS.LOGIN, { + data: { loginId: email, password, register: false, source: AUTH_SOURCE_EMAIL, authId: AUTH_ID_EMAIL }, + }), + ); +} + +export async function currentUser(request: APIRequestContext): Promise { + return unwrap("current user", await request.get(API_PATHS.CURRENT_USER)); +} + +export interface CreatedApp { + appId: string; +} + +interface CreateAppData { + applicationInfoView: { applicationId: string }; +} + +export async function createApp( + request: APIRequestContext, + params: { orgId: string; name: string; dsl?: object }, +): Promise { + const data = await unwrap( + `create app ${params.name}`, + await request.post(API_PATHS.APPLICATIONS, { + data: { + orgId: params.orgId, + name: params.name, + applicationType: APP_TYPE_APPLICATION, + editingApplicationDSL: params.dsl ?? {}, + }, + }), + ); + return { appId: data.applicationInfoView.applicationId }; +} + +export const FIRST_VERSION_TAG = "1.0.0"; + +/** + * Publishes the draft as version `tag`, like the editor's publish dialog (which sends a commit message and a + * version tag). A publish with an empty body works once; a second one with an empty body answered HTTP 500 + * "Service is busy" on the 3.0.0 image, so every publish names its version. + */ +export async function publishApp( + request: APIRequestContext, + appId: string, + tag: string = FIRST_VERSION_TAG, +): Promise { + await unwrap( + `publish app ${appId} as ${tag}`, + await request.post(publishPath(appId), { data: { commitMessage: `e2e ${tag}`, tag } }), + ); +} + +interface AppData { + /** The draft (editing) DSL: what GET /api/applications/{id} returns for the editor. */ + applicationDSL: unknown; +} + +/** The stored draft DSL of an app, as the editor saved it. */ +export async function getAppDsl(request: APIRequestContext, appId: string): Promise { + return unwrap(`read app ${appId}`, await request.get(applicationPath(appId))); +} + +export async function updateApp( + request: APIRequestContext, + appId: string, + changes: { name?: string; dsl?: object }, +): Promise { + await unwrap( + `update app ${appId}`, + await request.put(applicationPath(appId), { + data: { + ...(changes.name === undefined ? {} : { name: changes.name }), + ...(changes.dsl === undefined ? {} : { editingApplicationDSL: changes.dsl }), + }, + }), + ); +} + +export async function setPublicToAll(request: APIRequestContext, appId: string, publicToAll: boolean): Promise { + await unwrap( + `set public-to-all of ${appId}`, + await request.put(publicToAllPath(appId), { data: { publicToAll } }), + ); +} + +export interface AppSummary { + applicationId: string; + name: string; + applicationStatus: string; +} + +export async function listRecycledApps(request: APIRequestContext): Promise { + return unwrap("list recycled apps", await request.get(API_PATHS.APPLICATION_RECYCLE_LIST)); +} + +export async function recycleApp(request: APIRequestContext, appId: string): Promise { + await unwrap(`recycle app ${appId}`, await request.put(recyclePath(appId))); +} + +export async function restoreApp(request: APIRequestContext, appId: string): Promise { + await unwrap(`restore app ${appId}`, await request.put(restorePath(appId))); +} + +interface InviteData { + inviteCode: string; +} + +/** Creates an invitation link of a workspace; returns its code. */ +export async function createInvitation(request: APIRequestContext, orgId: string): Promise { + const data = await unwrap( + `invite to ${orgId}`, + await request.post(API_PATHS.INVITATION, { params: { orgId } }), + ); + return data.inviteCode; +} + +export async function acceptInvitation(request: APIRequestContext, inviteCode: string): Promise { + await unwrap(`accept invitation ${inviteCode}`, await request.get(invitationAcceptPath(inviteCode))); +} + +export async function currentUserId(request: APIRequestContext): Promise { + const me = await unwrap<{ id: string }>("current user id", await request.get(API_PATHS.CURRENT_USER)); + return me.id; +} + +export async function grantAppPermission( + request: APIRequestContext, + appId: string, + params: { role: "viewer" | "editor"; userIds: string[] }, +): Promise { + await unwrap( + `grant ${params.role} on ${appId}`, + await request.put(appPermissionsPath(appId), { data: { role: params.role, userIds: params.userIds, groupIds: [] } }), + ); +} + +/** + * The raw answer of GET /api/applications/{id}/view (the published app). Not unwrapped: tests also need the + * failure answers (permission denied) and compare their `code`. + */ +export async function viewAppRaw(request: APIRequestContext, appId: string): Promise<{ status: number; code: number }> { + const response = await request.get(appViewPath(appId)); + const body = (await response.json()) as { code: number }; + return { status: response.status(), code: body.code }; +} + +/** The raw answer of GET /api/applications/{id} (the editable app), see viewAppRaw. */ +export async function editAppRaw(request: APIRequestContext, appId: string): Promise<{ status: number; code: number }> { + const response = await request.get(applicationPath(appId)); + const body = (await response.json()) as { code: number }; + return { status: response.status(), code: body.code }; +} + +export interface PostgresConnection { + host: string; + port: number; + database: string; + username: string; + password: string; +} + +/** Creates a PostgreSQL data source in the workspace; returns its id. */ +export async function createPostgresDatasource( + request: APIRequestContext, + params: { orgId: string; name: string; connection: PostgresConnection }, +): Promise { + const data = await unwrap<{ id: string }>( + `create datasource ${params.name}`, + await request.post(API_PATHS.DATASOURCES, { + data: { + name: params.name, + type: "postgres", + organizationId: params.orgId, + // extParams is a map; a list is rejected as an illegal configuration + datasourceConfig: { ...params.connection, usingSsl: false, extParams: {} }, + }, + }), + ); + return data.id; +} diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts new file mode 100644 index 000000000..c8476b44c --- /dev/null +++ b/e2e/src/constants.ts @@ -0,0 +1,116 @@ +/** `code` of every successful Lowcoder API response (ResponseView). */ +export const API_OK = 1; + +/** AppTypeEnum.Application in client/packages/lowcoder/src/constants/applicationConstants.ts. */ +export const APP_TYPE_APPLICATION = 1; + +/** Authentication source and id of the e-mail/password login, from GET /api/configs. */ +export const AUTH_SOURCE_EMAIL = "EMAIL"; +export const AUTH_ID_EMAIL = "EMAIL"; + +export const API_PATHS = { + LOGIN: "/api/auth/form/login", + CURRENT_USER: "/api/users/me", + APPLICATIONS: "/api/applications", + APPLICATION_RECYCLE_LIST: "/api/applications/recycle/list", + INVITATION: "/api/invitation", + MARK_USER_STATUS: "/api/users/mark-status", + DATASOURCES: "/api/datasources", +} as const; + +export function applicationPath(appId: string): string { + return `${API_PATHS.APPLICATIONS}/${appId}`; +} + +export function appViewPath(appId: string): string { + return `${applicationPath(appId)}/view`; +} + +export function appPermissionsPath(appId: string): string { + return `${applicationPath(appId)}/permissions`; +} + +export function publicToAllPath(appId: string): string { + return `${applicationPath(appId)}/public-to-all`; +} + +export function recyclePath(appId: string): string { + return `${API_PATHS.APPLICATIONS}/recycle/${appId}`; +} + +export function restorePath(appId: string): string { + return `${API_PATHS.APPLICATIONS}/restore/${appId}`; +} + +export function invitationAcceptPath(inviteCode: string): string { + return `${API_PATHS.INVITATION}/${inviteCode}/invite`; +} + +/** `code` of the API answer when the user may not view or edit the app (observed on the 3.0.0 image). */ +export const API_CODE_APP_PERMISSION_DENIED = 5308; + +export function publishPath(appId: string): string { + return `${applicationPath(appId)}/publish`; +} + +export const APP_PAGE = { + EDIT: (appId: string) => `/apps/${appId}/edit`, + VIEW: (appId: string) => `/apps/${appId}/view`, +} as const; + +export const UI_PATHS = { + REGISTER: "/user/auth/register", + APP_LIST_PATH: "/apps", + APP_LIST: /\/apps/, + LOGIN: /\/user\/auth\/login/, + /** Where a visitor who may not see an app lands: the sign-in page of the app's workspace. */ + LOGIN_IN_ORG: /\/org\/[^/]+\/auth\/login/, +} as const; + +/** Meets the password rules of the sign-up form. */ +export const TEST_PASSWORD = "Passw0rd-e2e"; + +/** User status flag that the new-user tour sets when it is finished (HomeTutorialsV2.tsx). */ +export const NEW_USER_GUIDANCE_STATUS = "newUserGuidance"; + +/** The `example.test` domain cannot receive mail (RFC 2606). */ +export const TEST_EMAIL_DOMAIN = "example.test"; + +export const TAGS = { + SMOKE: "@smoke", + CORE: "@core", + SLOW: "@slow", + QUARANTINE: "@quarantine", +} as const; + +/** + * WORKAROUND, remove when the editor exposes a "ready to save" signal: the first component state the editor + * sees after mounting becomes its save baseline and is never sent (useSaveComp in + * client/packages/lowcoder/src/pages/editor/appEditorInternal.tsx), so an edit made earlier is lost. + * Measured: without this wait 6 of 12 parallel drag runs lost the edit, with 2.5 s none. + */ +export const EDITOR_SETTLE_MS = Number(process.env.E2E_EDITOR_SETTLE_MS || 2500); + +export const SAVE_POLL_TIMEOUT_MS = 20_000; +export const INSERT_PANEL_TIMEOUT_MS = 30_000; +export const INSERT_PANEL_ATTEMPT_TIMEOUT_MS = 3_000; + +/** Request failure reported by Chromium for a request that a Playwright route aborted with "blockedbyclient". */ +export const BLOCKED_BY_CLIENT_ERROR = "net::ERR_BLOCKED_BY_CLIENT"; + +/** Origin the client reports to for subscriptions; the network guard has to block it. */ +export const LOWCODER_CLOUD_FLOW_URL = "https://api-service.lowcoder.cloud/api/flow"; + +/** + * The PostgreSQL sidecar that scripts/run-in-docker.sh starts on the run's network (see fixtures/sql/init.sql). + * The run script passes its host name; the rest is fixed there. + */ +export const POSTGRES = { + HOST_ENV: "E2E_POSTGRES_HOST", + PORT: 5432, + DATABASE: "shop", + USERNAME: "postgres", + PASSWORD: "e2e-postgres-password", +} as const; + +export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; diff --git a/e2e/src/dsl/builders.ts b/e2e/src/dsl/builders.ts new file mode 100644 index 000000000..b6d7eb916 --- /dev/null +++ b/e2e/src/dsl/builders.ts @@ -0,0 +1,97 @@ +/** + * Builders for the application DSL. The shape is the one the editor saves (recorded from a real editor session): + * `ui.layout` places items on the grid, `ui.items` holds each component by its layout id. Only `ui` is needed for + * the app to load; the editor adds `refTree`, `hooks`, `settings` and `preload` itself. + */ + +export interface GridPosition { + x: number; + y: number; + w: number; + h: number; +} + +export interface DslItem { + id: string; + layout: GridPosition; + item: { compType: string; name: string; comp: Record }; +} + +const DEFAULT_BUTTON_SIZE = { w: 6, h: 6 } as const; + +/** A button. `testId` becomes the data-testid of the rendered component (its "Individual ID" property). */ +export function button(params: { + id: string; + name: string; + text: string; + testId: string; + x?: number; + y?: number; +}): DslItem { + return { + id: params.id, + layout: { x: params.x ?? 0, y: params.y ?? 0, ...DEFAULT_BUTTON_SIZE }, + item: { compType: "button", name: params.name, comp: { text: params.text, dataTestId: params.testId } }, + }; +} + +/** A text component. Its `text` is an expression string, so `{{ ... }}` binds it to queries and components. */ +export function text(params: { id: string; name: string; text: string; testId: string; x?: number; y?: number }): DslItem { + return { + id: params.id, + layout: { x: params.x ?? 0, y: params.y ?? 0, w: 12, h: 5 }, + item: { compType: "text", name: params.name, comp: { text: params.text, dataTestId: params.testId } }, + }; +} + +/** + * A query on a PostgreSQL data source that runs when the app loads. The shape is the one the editor saves + * (recorded after creating the query in the editor and typing the SQL). + */ +export interface PostgresQuery { + id: string; + name: string; + datasourceId: string; + sql: string; +} + +function queryDsl(query: PostgresQuery): object { + return { + compType: "postgres", + comp: { + commandType: "INSERT", + command: { table: "", changeSet: { compType: "KEY_VALUE_PAIRS", comp: [{ column: "", value: "" }] } }, + mode: "SQL", + sql: query.sql, + disablePreparedStatement: false, + }, + id: query.id, + name: query.name, + order: 1, + datasourceId: query.datasourceId, + triggerType: "automatic", + onEvent: [], + notification: { showSuccess: true, showFail: true, fail: [{}] }, + timeout: "", + confirmationModal: {}, + variables: [], + periodic: false, + periodicTime: "", + cancelPrevious: false, + depQueryName: "", + delayTime: "", + }; +} + +/** The DSL of an app that shows the given items and runs the given queries. */ +export function appDsl(items: DslItem[], queries: PostgresQuery[] = []): object { + const layout: Record = {}; + const components: Record = {}; + items.forEach((entry, index) => { + layout[entry.id] = { i: entry.id, ...entry.layout, pos: index }; + components[entry.id] = entry.item; + }); + return queries.length === 0 + ? { ui: { layout, items: components } } + : { ui: { layout, items: components }, queries: queries.map(queryDsl) }; +} diff --git a/e2e/src/fixtures.ts b/e2e/src/fixtures.ts new file mode 100644 index 000000000..e3cd8f6e4 --- /dev/null +++ b/e2e/src/fixtures.ts @@ -0,0 +1,92 @@ +import { test as base, expect, type BrowserContext, type Page } from "@playwright/test"; +import { BLOCKED_BY_CLIENT_ERROR, TEST_EMAIL_DOMAIN } from "./constants"; +import { registerUser, type RegisteredUser } from "./api/client"; + +export interface NetworkGuard { + /** URLs of the requests the guard blocked in this context. */ + blockedUrls: string[]; +} + +/** + * Blocks every request of the browser context to an origin other than the app under test. The Lowcoder + * client calls api-service.lowcoder.cloud (subscriptions, with the user's e-mail, workspace and host) and loads + * HubSpot; no test may reach them. Every context a test uses has to get this guard: the `context` of the test + * gets it from the automatic `networkGuard` fixture, further contexts come from `newUserSession`. + * + * Limits: it covers HTTP(S) requests of the pages of the context. It does not cover requests made by the + * backend inside the application container, and not WebSocket connections (context routes do not see them). + * Service workers are blocked in the config, so none can bypass the route. The suite never switches the guard off. + */ +export async function installNetworkGuard(context: BrowserContext, baseURL: string): Promise { + const allowedOrigin = new URL(baseURL).origin; + const guard: NetworkGuard = { blockedUrls: [] }; + await context.route( + (url) => url.origin !== allowedOrigin, + (route) => { + guard.blockedUrls.push(route.request().url()); + return route.abort("blockedbyclient"); + }, + ); + return guard; +} + +/** A second, independent browser session (own cookies), guarded like the test's own. */ +export interface UserSession { + context: BrowserContext; + page: Page; +} + +interface Fixtures { + networkGuard: NetworkGuard; + /** A user registered through the API and logged in in the test's browser context. */ + apiUser: RegisteredUser; + /** Opens another browser session, for a second user or an anonymous visitor. Closed after the test. */ + newUserSession: () => Promise; +} + +let emailCounter = 0; +/** `e2e--w-