A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
test: add webkit testing to playright (#52)
Myles Scolnicke28b539e950b
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.ymlindex 4330023669..a78a18003f 100644--- a/.github/workflows/playwright.yml+++ b/.github/workflows/playwright.yml@@ -65,12 +65,12 @@ jobs:with:path: |~/.cache/ms-playwright- key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }}+ key: ${{ runner.os }}-playwright-2-${{ env.PLAYWRIGHT_VERSION }}- name: 📥 Install Playwright Browsersworking-directory: ./frontendif: steps.playwright-cache.outputs.cache-hit != 'true'- run: npx playwright install chromium --with-deps+ run: npx playwright install chromium webkit --with-deps- name: 🎭 Run Playwright testsworking-directory: ./frontenddiff --git a/frontend/e2e-tests/badButton.spec.ts b/frontend/e2e-tests/badButton.spec.tsindex 30c3fd211b..cd3b712399 100644--- a/frontend/e2e-tests/badButton.spec.ts+++ b/frontend/e2e-tests/badButton.spec.ts@@ -4,8 +4,14 @@ import { getAppUrl } from "../playwright.config";const appUrl = getAppUrl("bad_button.py");-test("invalid on_click does not crash kernel", async ({ page }) => {+test.beforeEach(async ({ page }, info) => {await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ }+});++test("invalid on_click does not crash kernel", async ({ page }) => {await page.getByRole("button", { name: "Bad button" }).click();// the kernel should still be aliveawait expect(page.getByText("kernel not found")).toHaveCount(0);diff --git a/frontend/e2e-tests/bugs.spec.ts b/frontend/e2e-tests/bugs.spec.tsindex be2bd4c053..0fd1cfe77a 100644--- a/frontend/e2e-tests/bugs.spec.ts+++ b/frontend/e2e-tests/bugs.spec.ts@@ -3,14 +3,19 @@ import { test, expect } from "@playwright/test";import { getAppUrl } from "../playwright.config";import { createCellBelow, runCell } from "./helper";+const appUrl = getAppUrl("bugs.py");+test.beforeEach(async ({ page }, info) => {+ await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ }+});+/*** This test makes sure that downstream UI elements are re-initialized when* upstream source cells are re-run.*/-test("correctly initializes cells", async ({ page }) => {- const appUrl = getAppUrl("bugs.py");- await page.goto(appUrl);-+test("correctly initializes cells", async ({ page }, info) => {// Is initialized to 1const number = page.getByRole("spinbutton");await expect(number).toBeVisible();diff --git a/frontend/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.tsindex e1b8477d37..06dcb404d7 100644--- a/frontend/e2e-tests/cells.spec.ts+++ b/frontend/e2e-tests/cells.spec.ts@@ -1,13 +1,25 @@/* Copyright 2023 Marimo. All rights reserved. */import { test, expect } from "@playwright/test";-import { getAppUrl } from "../playwright.config";+import { getAppUrl, resetFile } from "../playwright.config";+import { pressShortcut } from "./helper";++const appUrl = getAppUrl("cells.py");+test.beforeEach(async ({ page }, info) => {+ await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ }+});++test.beforeEach(async () => {+ // Need to reset the file because this test modifies it+ await resetFile("cells.py");+});/*** Cell re-render count is a good indicator of performance.*/test("keeps re-renders from growing", async ({ page }) => {- const appUrl = getAppUrl("cells.py");- await page.goto(appUrl);await page.waitForLoadState("networkidle");// Read the render count@@ -30,9 +42,6 @@ test("keeps re-renders from growing", async ({ page }) => {* - moving cells up and down*/test("page renders 2 cells", async ({ page }) => {- const appUrl = getAppUrl("cells.py");- await page.goto(appUrl);-// Can see output / codeawait expect(page.locator("h1").getByText("Cell 1")).toBeVisible();await expect(page.locator("h1").getByText("Cell 2")).toBeVisible();@@ -89,14 +98,14 @@ test("page renders 2 cells", async ({ page }) => {.getByRole("textbox").filter({ hasText: 'mo.md("# Cell 0")' }).click();- await page.keyboard.press("Control+Shift+J");+ await pressShortcut(page, "cell.moveDown");// Focus on Cell 2 and move it upawait page.getByRole("textbox").filter({ hasText: 'mo.md("# Cell 2")' }).click();- await page.keyboard.press("Control+Shift+K");+ await pressShortcut(page, "cell.moveUp");// Verify the rendered cellsawait expect(page.locator("h1")).toHaveText([@@ -105,4 +114,23 @@ test("page renders 2 cells", async ({ page }) => {"Cell 2","Cell 1.5",]);++ // Revert the file by deleting the new cells+ // Delete cell 1.5+ await page+ .getByRole("textbox")+ .filter({ hasText: 'mo.md("# Cell 1.5")' })+ .selectText();+ await page.keyboard.press("Backspace");+ await pressShortcut(page, "cell.delete");+ // Delete cell 0+ await page+ .getByRole("textbox")+ .filter({ hasText: 'mo.md("# Cell 0")' })+ .selectText();+ await page.keyboard.press("Backspace");+ await pressShortcut(page, "cell.delete");++ // Verify the rendered cells+ await expect(page.locator("h1")).toHaveText(["Cell 1", "Cell 2"]);});diff --git a/frontend/e2e-tests/components.spec.ts b/frontend/e2e-tests/components.spec.tsindex 40d00a8d25..e3fdf3496a 100644--- a/frontend/e2e-tests/components.spec.ts+++ b/frontend/e2e-tests/components.spec.ts@@ -1,13 +1,16 @@/* Copyright 2023 Marimo. All rights reserved. */-import { test, expect } from "@playwright/test";+import { test, expect, Page } from "@playwright/test";import { getAppUrl } from "../playwright.config";-test.beforeEach(async ({ page }) => {- const appUrl = getAppUrl("components.py");+const appUrl = getAppUrl("components.py");+test.beforeEach(async ({ page }, info) => {await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ }});-const pageHelper = async (page) => {+const pageHelper = async (page: Page) => {return {selectBasicComponent: async (type: string) => {const select = await page.locator("#cell-1").locator("select");@@ -212,13 +215,9 @@ test("table", async ({ page }) => {await expect(element).toBeVisible();// Click first checkbox to select allawait page.getByRole("checkbox").first().click();- await page.waitForTimeout(100); // Sleeps are not ideal- const output = await page- .locator("#cell-3")- .locator(".marimo-json-output")- .first()- .innerText();- expect(output).toMatch(+ await expect(+ page.locator("#cell-3").locator(".marimo-json-output").first()+ ).toHaveText(`[2 Items0:{2 Items@@ -230,18 +229,15 @@ test("table", async ({ page }) => {"last_name":"Schrute"}]- `.trim()+ `.trim(),+ { useInnerText: true });// Click second checkbox to remove first rowawait page.getByRole("checkbox").nth(1).click();- await page.waitForTimeout(100); // Sleeps are not ideal- const output2 = await page- .locator("#cell-3")- .locator(".marimo-json-output")- .first()- .innerText();- expect(output2).toMatch(+ await expect(+ page.locator("#cell-3").locator(".marimo-json-output").first()+ ).toHaveText(`[1 Items0:{2 Items@@ -249,7 +245,8 @@ test("table", async ({ page }) => {"last_name":"Schrute"}]-`.trim()+`.trim(),+ { useInnerText: true });});@@ -296,20 +293,17 @@ test("complex - array", async ({ page }) => {await slider.dragTo(page.locator("marimo-slider").first());await date.fill("2020-01-20");// Verify output- await page.waitForTimeout(100); // Sleeps are not ideal- const output = await page- .locator("#cell-6")- .locator(".marimo-json-output")- .first()- .innerText();- expect(output).toMatch(+ await expect(+ page.locator("#cell-6").locator(".marimo-json-output").first()+ ).toHaveText(`[3 Items0:"hi marimo"1:52:2020-01-20]-`.trim()+`.trim(),+ { useInnerText: true });});@@ -327,19 +321,16 @@ test("complex - batch", async ({ page }) => {await textbox.fill("hi again marimo");await date.fill("2020-04-20");// Verify output- await page.waitForTimeout(100); // Sleeps are not ideal- const output = await page- .locator("#cell-6")- .locator(".marimo-json-output")- .first()- .innerText();- expect(output).toMatch(+ await expect(+ page.locator("#cell-6").locator(".marimo-json-output").first()+ ).toHaveText(`{2 Items"name":"hi again marimo""date":2020-04-20}-`.trim()+`.trim(),+ { useInnerText: true });});@@ -361,13 +352,9 @@ test("complex - dictionary", async ({ page }) => {// Click last onceawait buttons.last().click();// Verify output- await page.waitForTimeout(100); // Sleeps are not ideal- const output = await page- .locator("#cell-6")- .locator(".marimo-json-output")- .first()- .innerText();- expect(output).toMatch(+ await expect(+ page.locator("#cell-6").locator(".marimo-json-output").first()+ ).toHaveText(`{3 Items"slider":1@@ -378,7 +365,8 @@ test("complex - dictionary", async ({ page }) => {2:1]}-`.trim()+`.trim(),+ { useInnerText: true });});diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.tsindex ac128359e1..c5769c92cf 100644--- a/frontend/e2e-tests/helper.ts+++ b/frontend/e2e-tests/helper.ts@@ -1,5 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { Page, expect } from "@playwright/test";+import { HotkeyProvider, HotkeyAction } from "../src/core/hotkeys/hotkeys";import path from "node:path";export async function createCellBelow(opts: {@@ -61,3 +62,25 @@ export async function takeScreenshot(page: Page, filename: string) {fullPage: true,});}++/**+ * Press a hotkey on the page.+ *+ * It uses the hotkey provider to get the correct key for the current platform+ * and then maps it to the correct key for playwright.+ */+export async function pressShortcut(page: Page, action: HotkeyAction) {+ const isMac = await page.evaluate(() => navigator.userAgent.includes("Mac"));+ const provider = HotkeyProvider.create(isMac);+ const key = provider.getHotkey(action);+ // playwright uses "Meta" for command key on mac, "Control" for windows/linux+ // we also need to capitalize the first letter of each key+ const split = key.key.split("-");+ const capitalized = split.map((s) => s[0].toUpperCase() + s.slice(1));+ const keymap = capitalized+ .join("+")+ .replace("Cmd", isMac ? "Meta" : "Control")+ .replace("Ctrl", "Control");++ await page.keyboard.press(keymap);+}diff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.tsindex e967a295e4..6bd3e71ae5 100644--- a/frontend/e2e-tests/shutdown.spec.ts+++ b/frontend/e2e-tests/shutdown.spec.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { test, expect } from "@playwright/test";-import { getAppUrl } from "../playwright.config";+import { getAppUrl, startServer } from "../playwright.config";test("shutdown shows disconnected text", async ({ page }) => {const appUrl = getAppUrl("shutdown.py");@@ -27,3 +27,7 @@ test("shutdown shows disconnected text", async ({ page }) => {await page.getByRole("button", { name: "Save" }).click();await expect(page.getByText("Download unsaved changes?")).toHaveCount(1);});++test.afterAll(async () => {+ startServer("shutdown.py"); // restart the server+});diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.tsindex a0258a7ef3..c6e7e74050 100644--- a/frontend/playwright.config.ts+++ b/frontend/playwright.config.ts@@ -2,6 +2,7 @@import type { PlaywrightTestConfig } from "@playwright/test";import { devices } from "@playwright/test";import path from "node:path";+import { exec } from "node:child_process";export interface ServerOptions {command: "edit" | "run";@@ -43,6 +44,22 @@ export function getAppUrl(app: ApplicationNames): string {return getUrl(appToOptions[app].port);}+// Reset file via git checkout+export async function resetFile(app: ApplicationNames): Promise<void> {+ const pathToApp = path.join(pydir, app);+ const cmd = `git checkout -- ${pathToApp}`;+ await exec(cmd);+ return;+}++// Start marimo server for the given app+export function startServer(app: ApplicationNames): void {+ const { command, port } = appToOptions[app];+ const pathToApp = path.join(pydir, app);+ const marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless`;+ exec(marimoCmd);+}+// See https://playwright.dev/docs/test-configuration.const config: PlaywrightTestConfig = {testDir: "./e2e-tests",@@ -76,23 +93,38 @@ const config: PlaywrightTestConfig = {trace: "on-first-retry",},- // TODO(akshayka): Consider testing on firefox, safari+ // TODO(akshayka): Consider testing on firefoxprojects: [{name: "chromium",- use: {- ...devices["Desktop Chrome"],- },+ use: { ...devices["Desktop Chrome"] },+ },+ {+ name: "webkit",+ use: { ...devices["Desktop Safari"] },+ testIgnore: [+ // This test uses keyboard shortcuts which seem to work locally with webkit, but not on CI+ // Disable this test until we can figure out why+ "**/cells.spec.ts",+ ],+ },+ {+ name: "ios",+ use: { ...devices["iPhone 13"] },+ // Just run the cells tests for read-only apps+ testMatch: ["**/components.spec.ts", "**/mode.spec.ts"],},],// Run marimo servers before starting the tests, one for each app/testwebServer: Object.entries(appToOptions).map(([app, options]) => {+ const { command, port } = options;+ const pathToApp = path.join(pydir, app);+ const marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless`;+return {- command: `marimo -q ${options.command} ${path.join(pydir, app)} -p ${- options.port- } --headless`,- url: getUrl(options.port),+ command: marimoCmd,+ url: getUrl(port),reuseExistingServer: false,};}),diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.tsindex 8cac952a1e..3a20d29c59 100644--- a/frontend/src/core/hotkeys/hotkeys.ts+++ b/frontend/src/core/hotkeys/hotkeys.ts@@ -237,10 +237,19 @@ export interface IHotkeyProvider {}export class HotkeyProvider implements IHotkeyProvider {- private mod = isPlatformMac() ? "Cmd" : "Ctrl";- private platform: Platform = isPlatformMac() ? "mac" : "windows";+ private mod: string;+ private platform: Platform;- constructor(private hotkeys: Record<HotkeyAction, Hotkey>) {}+ static create(isMac?: boolean): HotkeyProvider {+ return new HotkeyProvider(DEFAULT_HOT_KEY, isMac);+ }++ constructor(private hotkeys: Record<HotkeyAction, Hotkey>, isMac?: boolean) {+ isMac = isMac ?? isPlatformMac();++ this.mod = isMac ? "Cmd" : "Ctrl";+ this.platform = isMac ? "mac" : "windows";+ }iterate(): HotkeyAction[] {return Objects.keys(this.hotkeys);