Skip to content

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.

tests: get playwright running again (#5567)

Myles Scolnickb773580b4f26
diff --git a/.github/workflows/test_be.yaml b/.github/workflows/test_be.yaml
index a98899e385..221fa4450f 100644
--- a/.github/workflows/test_be.yaml
+++ b/.github/workflows/test_be.yaml
@@ -51,7 +51,7 @@ jobs:
if: ${{ needs.changes.outputs.backend == 'true' }}
name: ${{ matrix.os }} / Py ${{ matrix.python-version }} / ${{ matrix.dependencies }} deps
runs-on: ${{ matrix.os }}
- timeout-minutes: 15
+ timeout-minutes: 20
defaults:
run:
shell: bash
diff --git a/frontend/.eslintrc.cjs b/frontend/.eslintrc.cjs
index febc3618da..2081cce314 100644
--- a/frontend/.eslintrc.cjs
+++ b/frontend/.eslintrc.cjs
@@ -168,6 +168,7 @@ module.exports = {
"@typescript-eslint/require-await": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
+ "no-console": "off",
},
},
{
diff --git a/frontend/e2e-tests/global-setup.ts b/frontend/e2e-tests/global-setup.ts
new file mode 100644
index 0000000000..7a2dc7c199
--- /dev/null
+++ b/frontend/e2e-tests/global-setup.ts
@@ -0,0 +1,52 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable no-console */
+
+import { chromium, type FullConfig } from "@playwright/test";
+import { type ApplicationNames, getAppUrl } from "../playwright.config";
+
+async function globalSetup(config: FullConfig) {
+ // Start a browser to test server connectivity
+ const browser = await chromium.launch();
+ const page = await browser.newPage();
+
+ // Test some apps to ensure they're ready
+ const criticalApps: ApplicationNames[] = ["components.py"];
+
+ console.log("🔧 Testing server connectivity...");
+
+ for (const app of criticalApps) {
+ try {
+ const url = getAppUrl(app);
+ console.log(`Testing ${app} at ${url}`);
+
+ // Wait for server to be ready with retries
+ let retries = 3;
+ while (retries > 0) {
+ try {
+ await page.goto(url, {
+ waitUntil: "networkidle",
+ timeout: 15_000,
+ });
+ console.log(`✅ ${app} ready`);
+ break;
+ } catch (error) {
+ retries--;
+ if (retries === 0) {
+ console.error(`❌ ${app} failed to start:`, error);
+ throw error;
+ }
+ console.log(`⏳ Retrying ${app} (${retries} attempts left)`);
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ }
+ }
+ } catch (error) {
+ console.error(`Failed to connect to ${app}:`, error);
+ throw error;
+ }
+ }
+
+ await browser.close();
+ console.log("🎉 All servers ready!");
+}
+
+export default globalSetup;
diff --git a/frontend/e2e-tests/global-teardown.ts b/frontend/e2e-tests/global-teardown.ts
new file mode 100644
index 0000000000..7eb40d2a44
--- /dev/null
+++ b/frontend/e2e-tests/global-teardown.ts
@@ -0,0 +1,32 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable no-console */
+
+import { exec } from "node:child_process";
+import { promisify } from "node:util";
+
+const execAsync = promisify(exec);
+
+async function globalTeardown() {
+ console.log("🧹 Cleaning up test environment...");
+
+ try {
+ // Kill any remaining marimo processes
+ try {
+ await execAsync("pkill -f 'marimo.*--headless' || true");
+ console.log("✅ Cleaned up marimo processes");
+ } catch {
+ // Ignore errors - processes might not exist
+ console.log("⚠️ No marimo processes to clean up");
+ }
+
+ // Small delay to ensure cleanup completes
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+
+ console.log("🎉 Cleanup complete!");
+ } catch (error) {
+ console.error("❌ Error during cleanup:", error);
+ // Don't throw - we don't want cleanup failures to fail the test run
+ }
+}
+
+export default globalTeardown;
diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.ts
index 36f5f5b52c..f37aa0f6e7 100644
--- a/frontend/e2e-tests/helper.ts
+++ b/frontend/e2e-tests/helper.ts
@@ -3,6 +3,7 @@
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { type HotkeyAction, HotkeyProvider } from "../src/core/hotkeys/hotkeys";
+import { clickWithRetry, waitForMarimoApp } from "./test-utils";
export async function createCellBelow(opts: {
page: Page;
@@ -111,10 +112,7 @@ export async function exportAsHTMLAndTakeScreenshot(page: Page) {
.getByTestId("notebook-menu-dropdown")
.click()
.then(() => {
- return page.getByText("Download", { exact: true }).hover();
- })
- .then(() => {
- return page.getByText("Download as HTML", { exact: true }).click();
+ return openCommandPalette({ page, command: "Download as HTML" });
}),
]);
@@ -151,10 +149,7 @@ export async function exportAsPNG(page: Page) {
.getByTestId("notebook-menu-dropdown")
.click()
.then(() => {
- return page.getByText("Download", { exact: true }).hover();
- })
- .then(() => {
- return page.getByText("Download as PNG", { exact: true }).click();
+ return openCommandPalette({ page, command: "Download as PNG" });
}),
]);
@@ -163,12 +158,34 @@ export async function exportAsPNG(page: Page) {
await download.saveAs(path);
}
+/**
+ * Open the command palette, type something, and hit Enter
+ */
+export async function openCommandPalette(opts: {
+ page: Page;
+ command: string;
+}) {
+ const { page, command } = opts;
+
+ // Open command palette with Ctrl+K (or Cmd+K on Mac)
+ await pressShortcut(page, "global.commandPalette");
+
+ // Wait for the command palette to be visible
+ await expect(page.getByPlaceholder("Type to search")).toBeVisible();
+
+ // Type the command
+ await page.keyboard.type(command);
+
+ // Hit Enter to execute
+ await page.keyboard.press("Enter");
+}
+
/**
* Waits for the page to load. If we have resumed a session, we restart the kernel.
*/
export async function maybeRestartKernel(page: Page) {
// Wait for cells to appear
- await waitForCellsToRender(page);
+ await waitForMarimoApp(page);
// If it says, "You have connected to an existing session", then restart
const hasText = await page
@@ -178,14 +195,7 @@ export async function maybeRestartKernel(page: Page) {
return;
}
- await page.getByTestId("notebook-menu-dropdown").click();
+ await clickWithRetry(page, "[data-testid='notebook-menu-dropdown']");
await page.getByText("Restart kernel", { exact: true }).click();
await page.getByLabel("Confirm Restart", { exact: true }).click();
}
-
-/**
- * Waits for cells to render in edit mode.
- */
-export async function waitForCellsToRender(page: Page) {
- await page.waitForSelector("[data-testid=cell-editor]");
-}
diff --git a/frontend/e2e-tests/py/bad_button.py b/frontend/e2e-tests/py/bad_button.py
index 38571d8b10..bcf1d3d171 100644
--- a/frontend/e2e-tests/py/bad_button.py
+++ b/frontend/e2e-tests/py/bad_button.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.0.1"
diff --git a/frontend/e2e-tests/py/bugs.py b/frontend/e2e-tests/py/bugs.py
index a056e10081..3bea23bfc7 100644
--- a/frontend/e2e-tests/py/bugs.py
+++ b/frontend/e2e-tests/py/bugs.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.0.6"
diff --git a/frontend/e2e-tests/py/cells.py b/frontend/e2e-tests/py/cells.py
index 6b1a98d3fe..1a74b4958b 100644
--- a/frontend/e2e-tests/py/cells.py
+++ b/frontend/e2e-tests/py/cells.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.0.5"
diff --git a/frontend/e2e-tests/py/components.py b/frontend/e2e-tests/py/components.py
index 4dbfb9a51d..25ec999abf 100644
--- a/frontend/e2e-tests/py/components.py
+++ b/frontend/e2e-tests/py/components.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.9.15"
@@ -14,7 +18,7 @@ def __(mo):
def __(basic_ui_elements, mo):
mo.md(
f"""### Basic elements
-
+
{basic_ui_elements}
"""
)
diff --git a/frontend/e2e-tests/py/disabled_cells.py b/frontend/e2e-tests/py/disabled_cells.py
index 0caf00424c..75d6165cc1 100644
--- a/frontend/e2e-tests/py/disabled_cells.py
+++ b/frontend/e2e-tests/py/disabled_cells.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.0.5"
diff --git a/frontend/e2e-tests/py/kitchen_sink.py b/frontend/e2e-tests/py/kitchen_sink.py
index 1f66dfb75e..e4152a2ced 100644
--- a/frontend/e2e-tests/py/kitchen_sink.py
+++ b/frontend/e2e-tests/py/kitchen_sink.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.13.15"
diff --git a/frontend/e2e-tests/py/layout_grid.py b/frontend/e2e-tests/py/layout_grid.py
index ae71e320e5..28412c43d9 100644
--- a/frontend/e2e-tests/py/layout_grid.py
+++ b/frontend/e2e-tests/py/layout_grid.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.13.15"
diff --git a/frontend/e2e-tests/py/layout_grid_max_width.py b/frontend/e2e-tests/py/layout_grid_max_width.py
index c5c4fabe16..2177fe0a21 100644
--- a/frontend/e2e-tests/py/layout_grid_max_width.py
+++ b/frontend/e2e-tests/py/layout_grid_max_width.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.1.50"
diff --git a/frontend/e2e-tests/py/output.py b/frontend/e2e-tests/py/output.py
index 3c3fdf0dc2..fc8abe4b1a 100644
--- a/frontend/e2e-tests/py/output.py
+++ b/frontend/e2e-tests/py/output.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.1.19"
diff --git a/frontend/e2e-tests/py/shutdown.py b/frontend/e2e-tests/py/shutdown.py
index 8b4eed19f5..456e87c268 100644
--- a/frontend/e2e-tests/py/shutdown.py
+++ b/frontend/e2e-tests/py/shutdown.py
@@ -1,3 +1,9 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# [tool.marimo.save]
+# autosave = "off"
+# ///
import marimo
__generated_with = "0.1.88"
diff --git a/frontend/e2e-tests/py/stdin.py b/frontend/e2e-tests/py/stdin.py
index 53cdae4fbd..7979bb8dab 100644
--- a/frontend/e2e-tests/py/stdin.py
+++ b/frontend/e2e-tests/py/stdin.py
@@ -1,5 +1,7 @@
-# Copyright 2024 Marimo. All rights reserved.
-
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.13.15"
diff --git a/frontend/e2e-tests/py/streams.py b/frontend/e2e-tests/py/streams.py
index fc9fc570c6..2892888368 100644
--- a/frontend/e2e-tests/py/streams.py
+++ b/frontend/e2e-tests/py/streams.py
@@ -1,3 +1,7 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
__generated_with = "0.0.1"
diff --git a/frontend/e2e-tests/py/title.py b/frontend/e2e-tests/py/title.py
index 6b038e93da..b97d5a97ab 100644
--- a/frontend/e2e-tests/py/title.py
+++ b/frontend/e2e-tests/py/title.py
@@ -1,5 +1,10 @@
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = true
+# ///
import marimo
+
__generated_with = "0.0.1"
app = marimo.App()
diff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.ts
index d898dddfb0..84fc88fce7 100644
--- a/frontend/e2e-tests/shutdown.spec.ts
+++ b/frontend/e2e-tests/shutdown.spec.ts
@@ -58,22 +58,22 @@ test("restart kernel", async ({ page }) => {
test("shutdown shows disconnected text", async ({ page }) => {
const appUrl = getAppUrl("shutdown.py");
await page.goto(appUrl);
+
+ // make changes without saving
+ await page
+ .getByRole("textbox")
+ .filter({ hasText: "import marimo" })
+ .locator("div")
+ .nth(1)
+ .fill("1234");
+
+ // shutdown and confirm
await page.getByRole("button", { name: "Shutdown" }).click();
- // confirm shutdown on modal
await page.getByRole("button", { name: "Confirm Shutdown" }).click();
// kernel disconnected message to be on the page
await expect(page.getByText("kernel not found")).toBeVisible();
- // when no unsaved changes, recovery modal should not be shown
- await page.getByRole("button", { name: "Save" }).click();
- await expect(page.getByText("Download unsaved changes?")).toHaveCount(0);
-
- // when changes are made, recovery modal should be shown
- await page
- .getByRole("textbox")
- .filter({ hasText: "import marimo" })
- .fill("1234");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Download unsaved changes?")).toHaveCount(1);
diff --git a/frontend/e2e-tests/test-utils.ts b/frontend/e2e-tests/test-utils.ts
new file mode 100644
index 0000000000..703f02463f
--- /dev/null
+++ b/frontend/e2e-tests/test-utils.ts
@@ -0,0 +1,130 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Locator, Page } from "@playwright/test";
+
+/**
+ * Wait for a marimo app to be fully loaded and ready
+ */
+export async function waitForMarimoApp(
+ page: Page,
+ timeout = 30_000,
+): Promise<void> {
+ await page.waitForLoadState("networkidle", { timeout });
+
+ // Wait for the marimo app to be initialized
+ await page.waitForFunction(
+ () => {
+ // Check if the app is loaded by looking for key elements
+ return (
+ document.querySelector("[data-testid='cell-editor']") !== null ||
+ document.querySelector(".marimo-cell") !== null ||
+ document.querySelector("[data-testid='marimo-static']") !== null
+ );
+ },
+ { timeout },
+ );
+}
+
+/**
+ * Wait for server to be responsive with retries
+ */
+export async function waitForServerReady(
+ page: Page,
+ url: string,
+ maxRetries = 5,
+): Promise<void> {
+ let retries = 0;
+
+ while (retries < maxRetries) {
+ try {
+ await page.goto(url, {
+ waitUntil: "networkidle",
+ timeout: 10_000,
+ });
+
+ // Additional check to ensure the page is actually loaded
+ await waitForMarimoApp(page);
+ return;
+ } catch (error) {
+ retries++;
+ if (retries === maxRetries) {
+ throw new Error(
+ `Server not ready after ${maxRetries} retries: ${error}`,
+ );
+ }
+
+ console.log(`Server not ready, retrying... (${retries}/${maxRetries})`);
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ }
+ }
+}
+
+/**
+ * Robust element interaction with retry
+ */
+export async function clickWithRetry(
+ page: Page,
+ selector: string,
+ maxRetries = 3,
+ timeout = 5000,
+): Promise<void> {
+ let element: Locator | undefined;
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ element = page.locator(selector);
+ await element.waitFor({ state: "visible", timeout });
+ break;
+ } catch (error) {
+ if (i === maxRetries - 1) {
+ throw error;
+ }
+ await page.waitForTimeout(1000);
+ }
+ }
+ if (!element) {
+ throw new Error(`Element not found: ${selector}`);
+ }
+ await element.click({ timeout });
+}
+
+export async function hoverWithRetry(
+ page: Page,
+ selector: string,
+ maxRetries = 3,
+ timeout = 5000,
+): Promise<void> {
+ let element: Locator | undefined;
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ element = page.locator(selector);
+ await element.waitFor({ state: "visible", timeout });
+ break;
+ } catch (error) {
+ if (i === maxRetries - 1) {
+ throw error;
+ }
+ await page.waitForTimeout(1000);
+ }
+ }
+ if (!element) {
+ throw new Error(`Element not found: ${selector}`);
+ }
+ await element.hover({ timeout });
+}
+
+/**
+ * Safe page navigation with fallback
+ */
+export async function safeGoto(
+ page: Page,
+ url: string,
+ timeout = 30_000,
+): Promise<void> {
+ try {
+ await page.goto(url, { waitUntil: "networkidle", timeout });
+ } catch (error) {
+ // Fallback to basic load
+ console.log(`Network idle failed, trying basic load: ${error}`);
+ await page.goto(url, { waitUntil: "load", timeout });
+ }
+}
diff --git a/frontend/e2e-tests/tsconfig.json b/frontend/e2e-tests/tsconfig.json
index 9757244bce..0bf959ffb1 100644
--- a/frontend/e2e-tests/tsconfig.json
+++ b/frontend/e2e-tests/tsconfig.json
@@ -1,20 +1,15 @@
{
+ "extends": "../tsconfig.json",
"compilerOptions": {
- "lib": ["ES2022", "DOM"],
- "noEmit": true,
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "types": ["@types/node"],
+ "types": ["node", "@playwright/test"],
+ "moduleResolution": "node",
+ "allowSyntheticDefaultImports": true,
"esModuleInterop": true,
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitAny": true,
- "noImplicitThis": true,
- "noUnusedLocals": true,
- "noFallthroughCasesInSwitch": true,
- "noImplicitOverride": true,
- "useUnknownInCatchVariables": true,
- "skipLibCheck": true
+ "skipLibCheck": true,
+ "paths": {
+ "@/*": ["../src/*"]
+ }
},
- "include": ["*"]
+ "include": ["**/*.ts", "**/*.spec.ts", "../playwright.config.ts"],
+ "exclude": ["node_modules", "playwright-report", "test-results"]
}
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index 41d4cd1e60..296be231b1 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -108,21 +108,21 @@ export function startServer(app: ApplicationNames): void {
exec(marimoCmd);
}
-const WASM_SERVER = {
- command: "PYODIDE=true vite --port 3000",
- url: "http://localhost:3000",
- reuseExistingServer: !!process.env.CI,
-};
+// const WASM_SERVER = {
+// command: "PYODIDE=true vite --port 3000",
+// url: "http://localhost:3000",
+// reuseExistingServer: !!process.env.CI,
+// };
// See https://playwright.dev/docs/test-configuration.
const config: PlaywrightTestConfig = {
testDir: "./e2e-tests",
// Maximum time one test can run for
- timeout: 30 * 1000,
+ timeout: 30 * 1000, // 30s
expect: {
// Maximum time expect() should wait for the condition to be met.
// For example in `await expect(locator).toHaveText();`
- timeout: 5000,
+ timeout: 5 * 1000, // 5s
},
// Run tests in files in parallel
fullyParallel: false,
@@ -134,23 +134,34 @@ const config: PlaywrightTestConfig = {
workers: 1,
// Reporter to use. See https://playwright.dev/docs/test-reporters
reporter: "html",
- // Suppress tests stdout/stderr.
- quiet: true,
+ // Enable stdout/stderr for better debugging
+ quiet: false,
// Shared settings for all the projects below. See
// https://playwright.dev/docs/api/class-testoptions.
use: {
- // Max time each action (eg `click()`) can take. Defaults to 0 (no limit).
- actionTimeout: 0,
- // Collect trace when retrying the failed test. See
- // https://playwright.dev/docs/trace-viewer
+ // Max time each action can take
+ actionTimeout: 5 * 1000, // 5s
+ // Navigation timeout
+ navigationTimeout: 10 * 1000, // 10s
+ // Collect trace when retrying the failed test
trace: "on-first-retry",
+ // Take screenshot on failure
+ screenshot: "only-on-failure",
},
+ // Global setup for better test isolation
+ globalSetup: "./e2e-tests/global-setup.ts",
+ globalTeardown: "./e2e-tests/global-teardown.ts",
+
// TODO(akshayka): Consider testing on firefox
projects: [
{
name: "chromium",
- use: { ...devices["Desktop Chrome"] },
+ use: {
+ ...devices["Desktop Chrome"],
+ // Add viewport for consistency
+ viewport: { width: 1280, height: 720 },
+ },
testIgnore: ["**/cells.spec.ts", "**/disabled.spec.ts"],
},
// Re-enable later ...
@@ -182,7 +193,7 @@ const config: PlaywrightTestConfig = {
return [];
}
- const baseUrl = options.command === "run" ? options.baseUrl : undefined;
+ const baseUrl = command === "run" ? options.baseUrl : undefined;
const pathToApp = path.join(pydir, app);
let marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless --no-token`;
@@ -193,13 +204,23 @@ const config: PlaywrightTestConfig = {
return {
command: marimoCmd,
url: getUrl(port, baseUrl),
- reuseExistingServer: false,
+ reuseExistingServer: true,
+ timeout: 30 * 1000,
+ ignoreHTTPSErrors: true,
+ // Add stdout/stderr for debugging
+ stdout: "pipe" as const,
+ stderr: "pipe" as const,
};
}),
{
command: `marimo -q edit -p ${EDIT_PORT} --headless --no-token`,
url: getUrl(EDIT_PORT),
- reuseExistingServer: false,
+ reuseExistingServer: true,
+ timeout: 30 * 1000,
+ ignoreHTTPSErrors: true,
+ // Add stdout/stderr for debugging
+ stdout: "pipe" as const,
+ stderr: "pipe" as const,
},
// WASM_SERVER,
],
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index 2cd0304376..fb810fff9a 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -33,5 +33,5 @@
"useDefineForClassFields": true,
"experimentalDecorators": true
},
- "include": ["src"]
+ "include": ["src", "playwright.config.ts", "e2e-tests"]
}
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index e4b5c915cf..ca7254bbd7 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -431,9 +431,14 @@ class SessionCacheManager:
cache_file = get_session_cache_file(Path(self.path))
if not cache_file.exists():
return self.session_view
- notebook_session: NotebookSessionV1 = json.loads(
- cache_file.read_text()
- )
+ try:
+ notebook_session: NotebookSessionV1 = json.loads(
+ cache_file.read_text()
+ )
+ except Exception as e:
+ LOGGER.error(f"Failed to read session cache file: {e}")
+ return self.session_view
+
if not self.is_cache_hit(notebook_session, key):
LOGGER.debug("Session view cache miss")
return self.session_view
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index b5ff8df7aa..4121b701aa 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -7,6 +7,8 @@ import time
from pathlib import Path
from typing import TYPE_CHECKING, Callable
+import pytest
+
from tests._server.conftest import get_session_manager
from tests._server.mocks import (
token_header,
@@ -127,6 +129,9 @@ def test_save_file(client: TestClient) -> None:
)
+ reason="Flaky in CI, can't repro locally",
+)
@with_session(SESSION_ID)
def test_save_with_header(client: TestClient) -> None:
filename = get_session_manager(client).file_router.get_unique_file_key()
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 7318ea4c79..b48b9c0bc8 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -13,6 +13,7 @@ from marimo._ast.cell import CellConfig
from marimo._server.api.status import HTTPException, HTTPStatus
from marimo._server.file_manager import AppFileManager
from marimo._server.models.models import SaveNotebookRequest
+from marimo._types.ids import CellId_t
if TYPE_CHECKING:
from collections.abc import Generator
@@ -230,6 +231,38 @@ def test_save_cannot_rename(app_file_manager: AppFileManager) -> None:
assert e.value.status_code == HTTPStatus.BAD_REQUEST
+def test_save_with_header(
+ app_file_manager: AppFileManager, tmp_path: Path
+) -> None:
+ file = tmp_path / "test_save_with_header.py"
+ file.write_text("""
+# This is a header
+
+import marimo
+app = marimo.App()
+
+def _():
+ print(1)
+ return
+""")
+ app_file_manager.filename = str(file)
+ assert app_file_manager.path is not None
+ app_file_manager.save(
+ SaveNotebookRequest(
+ cell_ids=[CellId_t("1")],
+ filename=str(file),
+ codes=["print(2)"],
+ names=["_"],
+ configs=[CellConfig(hide_code=True)],
+ )
+ )
+ new_contents = file.read_text()
+ assert "# This is a header" in new_contents
+ assert "print(2)" in new_contents
+ assert "print(1)" not in new_contents
+
+
def test_read_valid_filename(app_file_manager: AppFileManager) -> None:
expected_content = "This is a test read."
app_file_manager.filename = "test_read.py"