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
fix: disallow auto-export when unnamed, marimo convert tests (#4029)
Myles Scolnickec9c63eef202
diff --git a/marimo/_cli/convert/ipynb.py b/marimo/_cli/convert/ipynb.pydeleted file mode 100644index eab50fbc05..0000000000--- a/marimo/_cli/convert/ipynb.py+++ /dev/null@@ -1,12 +0,0 @@-# Copyright 2024 Marimo. All rights reserved.-from __future__ import annotations--from marimo._cli.convert.utils import (- load_external_file,-)-from marimo._convert.ipynb import convert_from_ipynb---def convert_from_ipynb_file(file_path: str) -> str:- raw_notebook = load_external_file(file_path, "ipynb")- return convert_from_ipynb(raw_notebook)diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.pyindex d6f5607a53..bcf6f9ffab 100644--- a/marimo/_cli/convert/utils.py+++ b/marimo/_cli/convert/utils.py@@ -5,6 +5,7 @@ import urllib.requestfrom pathlib import Pathfrom marimo._cli.file_path import get_github_src_url, is_github_src+from marimo._utils.url import is_urldef load_external_file(file_path: str, ext: str) -> str:@@ -15,6 +16,8 @@ def load_external_file(file_path: str, ext: str) -> str:.read().decode("utf-8"))+ elif is_url(file_path):+ notebook = urllib.request.urlopen(file_path).read().decode("utf-8")else:notebook = Path(file_path).read_text(encoding="utf-8")diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex fbedb8cdaf..06e54c3c69 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -56,6 +56,13 @@ async def export_as_html(body = await parse_request(request, cls=ExportAsHTMLRequest)session = app_state.require_current_session()+ # Check if the file is named+ if not session.app_file_manager.is_notebook_named:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File must have a name before exporting",+ )+# Only include the code and console if we are in edit modeif app_state.mode != SessionMode.EDIT:body.include_code = False@@ -106,6 +113,12 @@ async def auto_export_as_html(session = app_state.require_current_session()session_view = session.session_view+ if not session.app_file_manager.is_notebook_named:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File must have a name before exporting",+ )+# If we have already exported to HTML, don't do it againif not session_view.needs_export("html"):LOGGER.debug("Already auto-exported to HTML")@@ -249,6 +262,12 @@ async def auto_export_as_markdown(session = app_state.require_current_session()session_view = session.session_view+ if not session.app_file_manager.is_notebook_named:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File must have a name before exporting",+ )+# If we have already exported to Markdown, don't do it againif not session_view.needs_export("md"):LOGGER.debug("Already auto-exported to Markdown")@@ -297,6 +316,12 @@ async def auto_export_as_ipynb(session = app_state.require_current_session()session_view = session.session_view+ if not session.app_file_manager.is_notebook_named:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File must have a name before exporting",+ )+# If we have already exported to IPYNB, don't do it againif not session_view.needs_export("ipynb"):LOGGER.debug("Already auto-exported to IPYNB")diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex e3f0e0a0b1..06c4e84e23 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -193,7 +193,7 @@ class AppFileManager:# Check if filename is not None to satisfy mypy's type checking.# This ensures that filename is treated as a non-optional str,# preventing potential type errors in subsequent code.- if self._is_named() and self.filename is not None:+ if self.is_notebook_named and self.filename is not None:# Force a save after rename in case filetype changed.need_save = self.filename[-3:] != new_filename[-3:]self._rename_file(new_filename)@@ -277,7 +277,7 @@ class AppFileManager:configs=configs,)- if self._is_named() and not self._is_same_path(filename):+ if self.is_notebook_named and not self._is_same_path(filename):raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,detail="Save handler cannot rename files.",@@ -323,7 +323,9 @@ class AppFileManager:def _is_unnamed(self) -> bool:return self.filename is None- def _is_named(self) -> bool:+ @property+ def is_notebook_named(self) -> bool:+ """Whether the notebook has a name."""return self.filename is not Nonedef read_file(self) -> str:diff --git a/tests/_cli/snapshots/remote_ipynb_to_marimo.txt b/tests/_cli/snapshots/remote_ipynb_to_marimo.txtnew file mode 100644index 0000000000..9896e3055e--- /dev/null+++ b/tests/_cli/snapshots/remote_ipynb_to_marimo.txt@@ -0,0 +1,15 @@+import marimo+++app = marimo.App()+++def _():+ print('Hello from Remote Notebook!')+ return+++if __name__ == "__main__":+ app.run()+diff --git a/tests/_cli/snapshots/remote_markdown_to_marimo.txt b/tests/_cli/snapshots/remote_markdown_to_marimo.txtnew file mode 100644index 0000000000..4eaa998e14--- /dev/null+++ b/tests/_cli/snapshots/remote_markdown_to_marimo.txt@@ -0,0 +1,22 @@+import marimo+++app = marimo.App()++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ # Remote Markdown Test++ ```python+ print('Hello from Remote Markdown!')+ ```+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_cli/test_cli_convert.py b/tests/_cli/test_cli_convert.pyindex 972b230043..ef6402622f 100644--- a/tests/_cli/test_cli_convert.py+++ b/tests/_cli/test_cli_convert.py@@ -1,16 +1,70 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import http.serverimport re+import shutil+import socketserverimport subprocess-from typing import TYPE_CHECKING+import tempfile+import threading+from pathlib import Path+from typing import Any+import pytest++from marimo._server.utils import find_free_port+from marimo._utils.platform import is_windowsfrom tests.mocks import snapshottersnapshot = snapshotter(__file__)-if TYPE_CHECKING:- from pathlib import Path++# HTTP server for testing remote file conversion+class TestHTTPServer:+ def __init__(self, directory: Path, port: int):+ self.directory = directory+ self.port = port+ self.server = None+ self.thread = None++ def start(self):+ # Create a simple HTTP server that serves files from the directory+ directory = self.directory # Create a local reference to directory++ class CustomHandler(http.server.SimpleHTTPRequestHandler):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, directory=str(directory), **kwargs)++ self.server = socketserver.TCPServer(+ ("localhost", self.port), CustomHandler+ )++ # Run server in a separate thread+ self.thread = threading.Thread(target=self.server.serve_forever)+ self.thread.daemon = True+ self.thread.start()++ def stop(self):+ if self.server:+ self.server.shutdown()+ self.server.server_close()+ if self.thread:+ self.thread.join()++ def get_url(self, path: str) -> str:+ return f"http://localhost:{self.port}/{path}"++[email protected](scope="session")+def http_server():+ tmp_path = tempfile.mkdtemp()+ port = find_free_port(1234)+ server = TestHTTPServer(Path(tmp_path), port=port)+ server.start()+ yield server+ server.stop()+ shutil.rmtree(tmp_path)class TestConvert:@@ -114,3 +168,109 @@ print('Hello from Markdown!'))assert p.returncode != 0assert "File must be an .ipynb or .md file" in p.stderr++ @staticmethod+ def test_convert_remote_ipynb(http_server: TestHTTPServer) -> None:+ # Create a notebook file+ notebook_path = http_server.directory / "remote_notebook.ipynb"+ notebook_content = """+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "print('Hello from Remote Notebook!')"+ ]+ }+ ],+ "metadata": {},+ "nbformat": 4,+ "nbformat_minor": 4+}+"""+ notebook_path.write_text(notebook_content)++ # Convert remote file+ p = subprocess.run(+ [+ "marimo",+ "convert",+ http_server.get_url("remote_notebook.ipynb"),+ ],+ capture_output=True,+ text=True,+ )+ assert p.returncode == 0, p.stderr+ output = p.stdout+ output = re.sub(r"__generated_with = .*", "", output)+ snapshot("remote_ipynb_to_marimo.txt", output)++ @staticmethod+ @pytest.mark.skipif(+ is_windows(),+ reason="Markdown conversion adds extra new line on Windows",+ )+ def test_convert_remote_markdown(http_server: TestHTTPServer) -> None:+ # Create a markdown file+ md_path = http_server.directory / "remote_markdown.md"+ md_content = """+# Remote Markdown Test++```python+print('Hello from Remote Markdown!')+```+"""+ md_path.write_text(md_content)++ # Convert remote file+ p = subprocess.run(+ [+ "marimo",+ "convert",+ http_server.get_url("remote_markdown.md"),+ ],+ capture_output=True,+ text=True,+ )+ assert p.returncode == 0, p.stderr+ output = p.stdout+ output = re.sub(r"__generated_with = .*", "", output)+ snapshot("remote_markdown_to_marimo.txt", output)++ @staticmethod+ def test_convert_remote_invalid_file(http_server: TestHTTPServer) -> None:+ # Create an invalid file+ invalid_file = http_server.directory / "invalid.txt"+ invalid_file.write_text(+ "This is not a valid notebook or markdown file"+ )++ # Try to convert invalid remote file+ p = subprocess.run(+ ["marimo", "convert", http_server.get_url("invalid.txt")],+ capture_output=True,+ text=True,+ )+ assert p.returncode != 0+ assert "File must be an .ipynb or .md file" in p.stderr++ @staticmethod+ def test_convert_nonexistent_remote_file(+ http_server: TestHTTPServer,+ ) -> None:+ # Try to convert non-existent remote file+ p = subprocess.run(+ [+ "marimo",+ "convert",+ http_server.get_url("nonexistent.ipynb"),+ ],+ capture_output=True,+ text=True,+ )+ assert p.returncode != 0+ # The error message will be from urllib.error.HTTPError+ assert "HTTP Error 404" in p.stderr or "Not Found" in p.stderrdiff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 1cf6499198..95affbe334 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -396,20 +396,6 @@ def test_auto_export_ipynb_with_new_cell(marimo_dir = Path(temp_marimo_file).parent / "__marimo__"shutil.rmtree(marimo_dir, ignore_errors=True)- # Now attempt to auto-export as ipynb- export_response = client.post(- "/api/export/auto_export/ipynb",- headers=HEADERS,- json={- "download": False,- },- )- assert export_response.status_code == 200- assert export_response.json() == {"success": True}-- # Verify the exported file exists- assert marimo_dir.exists()-# Verify the cell output is correctsession = get_session_manager(client).get_session(SESSION_ID)assert session@@ -423,15 +409,32 @@ def test_auto_export_ipynb_with_new_cell(time.sleep(0.1)continuecell_op = session.session_view.cell_operations["new_cell"]- if cell_op.output is not None:+ if cell_op.output is not None and cell_op.output.data:breakassert cell_opassert cell_op.output is not Noneassert "3.14" in cell_op.output.data+ # Now attempt to auto-export as ipynb+ export_response = client.post(+ "/api/export/auto_export/ipynb",+ headers=HEADERS,+ json={+ "download": False,+ },+ )+ assert export_response.status_code == 200+ assert export_response.json() == {"success": True}++ # Verify the exported file exists+ assert marimo_dir.exists()+# Verify the ipynb file existsfilename = Path(temp_marimo_file).name.replace(".py", ".ipynb")ipynb_path = marimo_dir / filename++ # Wait for the ipynb file to be created+ time.sleep(0.2)notebook = ipynb_path.read_text()assert "<pre style='font-size: 12px'>3.14</pre>" in notebook@@ -454,3 +457,47 @@ def test_export_html_with_script_config(client: TestClient) -> None:)body = response.textassert '"code_editor_font_size": 999' in body+++@with_session(SESSION_ID)+def test_auto_export_html_unnamed_file(client: TestClient) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ # Ensure the file is unnamed+ session.app_file_manager.filename = None++ response = client.post(+ "/api/export/auto_export/html",+ headers=HEADERS,+ json={+ "download": False,+ "files": [],+ "include_code": True,+ },+ )++ # Should return 400 Bad Request when file is unnamed+ assert response.status_code == 400+ assert "File must have a name before exporting" in response.text+++@with_session(SESSION_ID)+def test_export_html_unnamed_file(client: TestClient) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ # Ensure the file is unnamed+ session.app_file_manager.filename = None++ response = client.post(+ "/api/export/html",+ headers=HEADERS,+ json={+ "download": False,+ "files": [],+ "include_code": True,+ },+ )++ # Should return 400 Bad Request when file is unnamed+ assert response.status_code == 400+ assert "File must have a name before exporting" in response.text