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: install inline-metadata for remote deps (#2416)
Myles Scolnick54192302dc57
diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex 90ce441008..6bef6dee45 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import abcimport jsonimport loggingimport os@@ -8,17 +9,13 @@ import pathlibimport urllib.parseimport urllib.requestfrom tempfile import TemporaryDirectory-from typing import Optional+from typing import Optional, Tuple+from urllib.error import HTTPErrorfrom marimo._cli.print import greenfrom marimo._utils.marimo_path import MarimoPathfrom marimo._utils.url import is_url-STATIC_HTML_CODE_PREFIX = '<marimo-code hidden="">'-STATIC_HTML_CODE_SUFFIX = "</marimo-code>"-STATIC_HTML_FILENAME_PREFIX = '<marimo-filename hidden="">'-STATIC_HTML_FILENAME_SUFFIX = "</marimo-filename>"-def is_github_src(url: str, ext: str) -> bool:if not is_url(url):@@ -40,176 +37,278 @@ def get_github_src_url(url: str) -> str:return f"https://raw.githubusercontent.com{path}"-def validate_name(- name: str, allow_new_file: bool, allow_directory: bool-) -> tuple[str, Optional[TemporaryDirectory[str]]]:- """- Validate the name of the file to be edited/run.+class FileReader(abc.ABC):+ @abc.abstractmethod+ def can_read(self, name: str) -> bool:+ pass- If it's an existing path, check that it is a valid notebook file.- If it's a URL, we download it to a temporary file and return- the path to that file.+ @abc.abstractmethod+ def read(self, name: str) -> Tuple[str, str]:+ """Read the file and return its content and filename."""+ pass- Args:- name: The name of the file to be edited/run.- Returns:- The name of file to to be edited/run- Optional TemporaryDirectory, returned to prevent it from being- cleaned up- """- import click-- if _is_github_issue_url(name):- temp_dir = TemporaryDirectory()- return _handle_github_issue(name, temp_dir), temp_dir-- is_static_notebook, static_notebook_html = _is_static_marimo_notebook_url(- name- )- if is_static_notebook:- temp_dir = TemporaryDirectory()- return (- _create_tmp_file_from_static_notebook(- static_notebook_html, temp_dir- ),- temp_dir,+class LocalFileReader(FileReader):+ def can_read(self, name: str) -> bool:+ return not is_url(name)++ def read(self, name: str) -> Tuple[str, str]:+ with open(name, "r") as f:+ content = f.read()+ return content, os.path.basename(name)+++class GitHubIssueReader(FileReader):+ def can_read(self, name: str) -> bool:+ return is_url(name) and name.startswith(+ "https://github.com/marimo-team/marimo/issues/")- if allow_directory:- if os.path.isdir(name):+ def read(self, name: str) -> Tuple[str, str]:+ issue_number = name.split("/")[-1]+ api_url = f"https://api.github.com/repos/marimo-team/marimo/issues/{issue_number}"+ issue_response = urllib.request.urlopen(api_url).read().decode("utf-8")+ issue_json = json.loads(issue_response)+ body = issue_json["body"]+ code = self._find_python_code_in_github_issue(body)+ return code, f"issue_{issue_number}.py"++ @staticmethod+ def _find_python_code_in_github_issue(body: str) -> str:+ return body.split("```python")[1].rsplit("```", 1)[0]+++class StaticNotebookReader(FileReader):+ CODE_PREFIX = '<marimo-code hidden="">'+ CODE_SUFFIX = "</marimo-code>"+ FILENAME_PREFIX = '<marimo-filename hidden="">'+ FILENAME_SUFFIX = "</marimo-filename>"++ def can_read(self, name: str) -> bool:+ return self._is_static_marimo_notebook_url(name)[0]++ def read(self, name: str) -> Tuple[str, str]:+ _, file_contents = self._is_static_marimo_notebook_url(name)+ code = self._extract_code_from_static_notebook(file_contents)+ filename = self._extract_filename_from_static_notebook(file_contents)+ return code, filename++ @staticmethod+ def _is_static_marimo_notebook_url(url: str) -> tuple[bool, str]:+ def download(url: str) -> tuple[bool, str]:+ logging.info("Downloading %s", url)+ request = urllib.request.Request(+ url,+ # User agent to avoid 403 Forbidden some bot protection+ headers={"User-Agent": "Mozilla/5.0"},+ )+ file_contents = (+ urllib.request.urlopen(request).read().decode("utf-8")+ )+ return StaticNotebookReader.CODE_PREFIX in file_contents, str(+ file_contents+ )++ # Not a URL+ if not is_url(url):+ return False, ""++ # Ends with .html, try to download it+ if url.endswith(".html"):+ return download(url)++ # Starts with https://static.marimo.app/, append /download+ if url.startswith("https://static.marimo.app/"):+ return download(os.path.join(url, "download"))++ # Otherwise, not a static marimo notebook+ return False, ""++ @staticmethod+ def _extract_code_from_static_notebook(file_contents: str) -> str:+ # normalize hidden attribute+ file_contents = file_contents.replace("hidden=''", 'hidden=""')+ return file_contents.split(StaticNotebookReader.CODE_PREFIX)[1].split(+ StaticNotebookReader.CODE_SUFFIX+ )[0]++ @staticmethod+ def _extract_filename_from_static_notebook(file_contents: str) -> str:+ # normalize hidden attribute+ file_contents = file_contents.replace("hidden=''", 'hidden=""')+ return file_contents.split(StaticNotebookReader.FILENAME_PREFIX)[+ 1+ ].split(StaticNotebookReader.FILENAME_SUFFIX)[0]+++class GitHubSourceReader(FileReader):+ def can_read(self, name: str) -> bool:+ return is_github_src(name, ext=".py") or is_github_src(name, ext=".md")++ def read(self, name: str) -> Tuple[str, str]:+ url = get_github_src_url(name)+ content = urllib.request.urlopen(url).read().decode("utf-8")+ return content, os.path.basename(url)+++class GenericURLReader(FileReader):+ def can_read(self, name: str) -> bool:+ return is_url(name)++ def read(self, name: str) -> Tuple[str, str]:+ content = urllib.request.urlopen(name).read().decode("utf-8")+ # Remove query parameters from the URL+ url_without_query = name.split("?")[0]+ return content, os.path.basename(url_without_query)+++class FileContentReader:+ def __init__(self) -> None:+ self.readers = [+ LocalFileReader(),+ GitHubIssueReader(),+ StaticNotebookReader(),+ GitHubSourceReader(),+ GenericURLReader(),+ ]++ def read_file(self, name: str) -> Tuple[str, str]:+ """+ Read the file and return its content and filename++ Args:+ name (str): File path or URL++ Raises:+ ValueError: If the file cannot be read++ Returns:+ Tuple[str, str]: File content and filename+ """+ for reader in self.readers:+ if reader.can_read(name):+ return reader.read(name)+ raise ValueError(f"Unable to read file contents of {name}")+++class FileHandler(abc.ABC):+ @abc.abstractmethod+ def can_handle(self, name: str) -> bool:+ pass++ @abc.abstractmethod+ def handle(+ self, name: str, temp_dir: TemporaryDirectory[str]+ ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ pass+++class LocalFileHandler(FileHandler):+ def __init__(self, allow_new_file: bool, allow_directory: bool):+ self.allow_new_file = allow_new_file+ self.allow_directory = allow_directory++ def can_handle(self, name: str) -> bool:+ return not is_url(name)++ def handle(+ self, name: str, temp_dir: TemporaryDirectory[str]+ ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ del temp_dir+ import click++ path = pathlib.Path(name)++ if self.allow_directory and os.path.isdir(name):return name, None- path = pathlib.Path(name)- if path.suffix == ".ipynb":- prefix = str(path)[: -len(".ipynb")]- raise click.UsageError(- f"Invalid NAME - {name} is not a Python file.\n\n"- f" {green('Tip:')} Convert {name} to a marimo notebook with\n\n"- f" marimo convert {name} > {prefix}.py\n\n"- f" then open with marimo edit {prefix}.py"+ if path.suffix == ".ipynb":+ prefix = str(path)[: -len(".ipynb")]+ raise click.ClickException(+ f"Invalid NAME - {name} is not a Python file.\n\n"+ f" {green('Tip:')} Convert {name} to a marimo notebook with"+ "\n\n"+ f" marimo convert {name} > {prefix}.py\n\n"+ f" then open with marimo edit {prefix}.py"+ )++ if not MarimoPath.is_valid_path(path):+ raise click.ClickException(+ f"Invalid NAME - {name} is not a Python or Markdown file"+ )++ if not self.allow_new_file:+ if not os.path.exists(name):+ raise click.ClickException(+ f"Invalid NAME - {name} does not exist"+ )+ if not path.is_file():+ raise click.ClickException(+ f"Invalid NAME - {name} is not a file"+ )++ return name, None+++class RemoteFileHandler(FileHandler):+ def __init__(self) -> None:+ self.reader = FileContentReader()++ def can_handle(self, name: str) -> bool:+ return is_url(name)++ def handle(+ self, name: str, temp_dir: TemporaryDirectory[str]+ ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ try:+ content, filename = self.reader.read_file(name)+ except HTTPError as e:+ import click++ raise click.ClickException(f"Failed to read URL: {e}") # noqa: B904+ path_to_app = self._create_tmp_file_from_content(+ content, filename, temp_dir)- elif not MarimoPath.is_valid_path(path):- raise click.UsageError(- "Invalid NAME - %s is not a Python or Markdown file" % name- )-- for ext in (".py", ".md"):- if is_github_src(name, ext=ext):- temp_dir = TemporaryDirectory()- return _handle_github_src(name, temp_dir), temp_dir+ return path_to_app, temp_dir- if is_url(name):- temp_dir = TemporaryDirectory()- return _create_tmp_file_from_url(name, temp_dir), temp_dir+ @staticmethod+ def _create_tmp_file_from_content(+ content: str, name: str, temp_dir: TemporaryDirectory[str]+ ) -> str:+ logging.info("Creating temporary file")+ path_to_app = os.path.join(temp_dir.name, name)+ with open(path_to_app, "w") as f:+ f.write(content)+ logging.info("App saved to %s", path_to_app)+ return path_to_app- if not allow_new_file:- if not os.path.exists(name):- raise click.UsageError("Invalid NAME - %s does not exist" % name)- if not path.is_file():- raise click.UsageError("Invalid NAME - %s is not a file" % name)- return name, None+def validate_name(+ name: str, allow_new_file: bool, allow_directory: bool+) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ """+ Validate the file name and return the path to the file.+ Args:+ name (str): Local file path, URL, or directory path+ allow_new_file (bool): Whether to allow creating a new file+ allow_directory (bool): Whether to allow a directory-def _is_github_issue_url(url: str) -> bool:- return is_url(url) and url.startswith(- "https://github.com/marimo-team/marimo/issues/"- )+ Raises:+ ValueError: If the file name is invalid+ Returns:+ Path to the file and temporary directory+ """+ handlers = [+ LocalFileHandler(allow_new_file, allow_directory),+ RemoteFileHandler(),+ ]-def _is_static_marimo_notebook_url(url: str) -> tuple[bool, str]:- def download(url: str) -> tuple[bool, str]:- logging.info("Downloading %s", url)- request = urllib.request.Request(- url,- # User agent to avoid 403 Forbidden some bot protection- headers={"User-Agent": "Mozilla/5.0"},- )- file_contents = urllib.request.urlopen(request).read().decode("utf-8")- return STATIC_HTML_CODE_PREFIX in file_contents, str(file_contents)+ temp_dir = TemporaryDirectory()- # Not a URL- if not is_url(url):- return False, ""+ for handler in handlers:+ if handler.can_handle(name):+ return handler.handle(name, temp_dir)- # Ends with .html, try to download it- if url.endswith(".html"):- return download(url)-- # Starts with https://static.marimo.app/, append /download- if url.startswith("https://static.marimo.app/"):- return download(os.path.join(url, "download"))-- # Otherwise, not a static marimo notebook- return False, ""---def _handle_github_issue(url: str, temp_dir: TemporaryDirectory[str]) -> str:- import click-- issue_number = url.split("/")[-1]- api_url = f"https://api.github.com/repos/marimo-team/marimo/issues/{issue_number}"- issue_response = urllib.request.urlopen(api_url).read().decode("utf-8")- issue_json = json.loads(issue_response)- body = issue_json["body"]-- # Find the content between first ```python and last ```- try:- code = _find_python_code_in_github_issue(body)- except IndexError:- raise click.UsageError(- "Invalid Issue - %s does not include a marimo app" % url- ) from None-- # Create a temporary file with the content- path_to_app = _create_tmp_file_from_content(- code, f"issue_{issue_number}.py", temp_dir- )- return path_to_app---def _find_python_code_in_github_issue(body: str) -> str:- # Find the content between first ```python and last ```- return body.split("```python")[1].rsplit("```", 1)[0]---def _handle_github_src(url: str, temp_dir: TemporaryDirectory[str]) -> str:- url = get_github_src_url(url)- path_to_app = _create_tmp_file_from_url(url, temp_dir)- return path_to_app---def _create_tmp_file_from_static_notebook(- file_contents: str, temp_dir: TemporaryDirectory[str]-) -> str:- def between(prefix: str, suffix: str) -> str:- return file_contents.split(prefix)[1].split(suffix)[0]-- code = between(STATIC_HTML_CODE_PREFIX, STATIC_HTML_CODE_SUFFIX)- filename = between(- STATIC_HTML_FILENAME_PREFIX, STATIC_HTML_FILENAME_SUFFIX- )- decoded_code = urllib.parse.unquote(code).strip()- return _create_tmp_file_from_content(decoded_code, filename, temp_dir)---def _create_tmp_file_from_url(- url: str, temp_dir: TemporaryDirectory[str]-) -> str:- logging.info("Downloading %s", url)- path_to_app = os.path.join(temp_dir.name, os.path.basename(url))- urllib.request.urlretrieve(url=url, filename=path_to_app)- logging.info("App saved to %s", path_to_app)- return path_to_app---def _create_tmp_file_from_content(- content: str, name: str, temp_dir: TemporaryDirectory[str]-) -> str:- logging.info("Creating temporary file")- path_to_app = os.path.join(temp_dir.name, name)- with open(path_to_app, "w") as f:- f.write(content)- logging.info("App saved to %s", path_to_app)- return path_to_app+ raise ValueError(f"Unable to handle file {name}")diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex dcb8ee1e4a..183241d635 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -13,6 +13,7 @@ from typing import Any, Dict, List, Optional, castimport clickfrom marimo import _loggers+from marimo._cli.file_path import FileContentReaderfrom marimo._cli.print import bold, echo, greenfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManager@@ -35,11 +36,12 @@ def _get_dependencies(script: str) -> List[str] | None:def get_dependencies_from_filename(name: str) -> List[str]:- if os.path.isfile(name):- with open(name) as f:- dependencies = _get_dependencies(f.read())- return dependencies if dependencies is not None else []- return []+ try:+ contents, _ = FileContentReader().read_file(name)+ return _get_dependencies(contents) or []+ except Exception:+ LOGGER.warning(f"Failed to read dependencies from {name}")+ return []def _read_pyproject(script: str) -> Dict[str, Any] | None:diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.pyindex 0ce7b5a4d9..05fde4e713 100644--- a/tests/_cli/test_file_path.py+++ b/tests/_cli/test_file_path.py@@ -2,18 +2,19 @@from __future__ import annotationsimport tempfile-from typing import Any+import urllib.errorfrom unittest.mock import mock_open, patchimport clickimport pytestfrom marimo._cli.file_path import (- _create_tmp_file_from_content,- _create_tmp_file_from_url,- _find_python_code_in_github_issue,- _handle_github_issue,- _is_github_issue_url,+ FileContentReader,+ GenericURLReader,+ GitHubIssueReader,+ GitHubSourceReader,+ LocalFileReader,+ StaticNotebookReader,is_github_src,validate_name,)@@ -29,18 +30,18 @@ def test_validate_name_with_python_file() -> None:def test_validate_name_with_non_python_file() -> None:- with pytest.raises(click.UsageError):+ with pytest.raises(click.ClickException):validate_name("example.txt", allow_new_file=False, allow_directory=False)- with pytest.raises(click.UsageError):+ with pytest.raises(click.ClickException):validate_name("example.txt", allow_new_file=True, allow_directory=False)def test_validate_name_with_nonexistent_file() -> None:- with pytest.raises(click.UsageError):+ with pytest.raises(click.ClickException):validate_name("nonexistent.py", allow_new_file=False, allow_directory=False)@@ -53,9 +54,9 @@ def test_validate_name_with_nonexistent_file() -> None:def test_validate_name_with_directory_false() -> None:- with pytest.raises(click.UsageError):+ with pytest.raises(click.ClickException):validate_name(".", allow_new_file=False, allow_directory=False)- with pytest.raises(click.UsageError):+ with pytest.raises(click.ClickException):validate_name(".", allow_new_file=True, allow_directory=False)@@ -69,12 +70,25 @@ def test_validate_name_with_directory_true() -> None:)-def test_is_github_issue_url_with_valid_url() -> None:+def test_github_issue_reader() -> None:+ reader = GitHubIssueReader()valid_url = "https://github.com/marimo-team/marimo/issues/1"- assert _is_github_issue_url(valid_url) is True-invalid_url = "https://github.com/marimo-team/marimo/pull/1"- assert _is_github_issue_url(invalid_url) is False++ assert reader.can_read(valid_url) is True+ assert reader.can_read(invalid_url) is False++ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_response = mock_open(+ read_data="""{+ "body": "Some content.```python\\nprint('Hello, world!')\\n```"}+ """.encode() # noqa: E501+ )+ mock_urlopen.return_value = mock_response()++ content, filename = reader.read(valid_url)+ assert content.strip() == "print('Hello, world!')"+ assert filename == "issue_1.py"def test_is_github_src_with_valid_url() -> None:@@ -85,40 +99,106 @@ def test_is_github_src_with_valid_url() -> None:assert is_github_src(invalid_url, ext=".py") is False-@patch("urllib.request.urlopen")-def test_handle_github_issue(mock_urlopen: Any) -> None:- # Mock the response from GitHub API- mock_response = mock_open(- read_data="""{- "body": "Some content.```python\\nprint(\'Hello, world!\')\\n```"}- """.encode()- )- mock_urlopen.return_value = mock_response()+def test_github_source_reader() -> None:+ reader = GitHubSourceReader()+ valid_url = "https://github.com/marimo-team/marimo/blob/main/example.py"+ invalid_url = "https://github.com/marimo-team/marimo/blob/main/example.txt"- # Call the function with a mock URL- issue_url = "https://github.com/marimo-team/marimo/issues/1"- result = _handle_github_issue(issue_url, temp_dir)+ assert reader.can_read(valid_url) is True+ assert reader.can_read(invalid_url) is False- # Check if the result is a path to a temporary file- assert result.endswith(".py")- assert open(result).read().strip() == "print('Hello, world!')"+ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_urlopen.return_value = mock_response()+ content, filename = reader.read(valid_url)+ assert content == "print('Hello, world!')"+ assert filename == "example.py"-def test_create_tmp_file_from_url() -> None:- url = "https://raw.githubusercontent.com/marimo-team/marimo/0.8.5/examples/optimization/regularization_and_sparsity.py"- result = _create_tmp_file_from_url(url, temp_dir)- # Check if the result is a path to a temporary file- assert result.endswith(".py")+def test_local_file_reader() -> None:+ reader = LocalFileReader()+ assert reader.can_read("local_file.py") is True+ assert reader.can_read("https://example.com/file.py") is False+ with patch("builtins.open", mock_open(read_data="print('Hello, world!')")):+ content, filename = reader.read("local_file.py")+ assert content == "print('Hello, world!')"+ assert filename == "local_file.py"-def test_create_tmp_file_from_content() -> None:- content = 'print("Hello, world!")'- name = "test_script.py"- result = _create_tmp_file_from_content(content, name, temp_dir)- assert result.endswith(name)- assert open(result).read() == content+def test_static_notebook_reader() -> None:+ reader = StaticNotebookReader()+ valid_url = "https://static.marimo.app/example"+ invalid_url = "https://example.com/file.py"++ with patch.object(+ StaticNotebookReader, "_is_static_marimo_notebook_url"+ ) as mock_is_static:+ mock_is_static.return_value = (+ True,+ "<marimo-code hidden=''>print('Hello')</marimo-code><marimo-filename hidden=''>test.py</marimo-filename>", # noqa: E501+ )+ assert reader.can_read(valid_url) is True+ content, filename = reader.read(valid_url)+ assert content == "print('Hello')"+ assert filename == "test.py"++ mock_is_static.return_value = (False, "")+ assert reader.can_read(invalid_url) is False+++def test_generic_url_reader() -> None:+ reader = GenericURLReader()+ assert reader.can_read("https://example.com/file.py") is True+ assert reader.can_read("local_file.py") is False++ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_urlopen.return_value = mock_response()++ content, filename = reader.read("https://example.com/file.py")+ assert content == "print('Hello, world!')"+ assert filename == "file.py"+++def test_file_content_reader() -> None:+ reader = FileContentReader()++ with patch.object(+ LocalFileReader, "read"+ ) as mock_local_read, patch.object(+ GitHubIssueReader, "read"+ ) as mock_github_issue_read, patch.object(+ StaticNotebookReader, "read"+ ) as mock_static_notebook_read, patch.object(+ GitHubSourceReader, "read"+ ) as mock_github_source_read, patch.object(+ GenericURLReader, "read"+ ) as mock_generic_url_read:+ mock_local_read.return_value = ("local content", "local.py")+ mock_github_issue_read.return_value = ("issue content", "issue.py")+ mock_static_notebook_read.return_value = (+ "notebook content",+ "notebook.py",+ )+ mock_github_source_read.return_value = ("github content", "github.py")+ mock_generic_url_read.return_value = ("url content", "url.py")++ assert reader.read_file("local.py") == ("local content", "local.py")+ assert reader.read_file(+ "https://github.com/marimo-team/marimo/issues/1"+ ) == ("issue content", "issue.py")+ assert reader.read_file(+ "https://github.com/marimo-team/marimo/blob/main/example.py"+ ) == ("github content", "github.py")+ assert reader.read_file("https://example.com/file.py") == (+ "url content",+ "url.py",+ )++ with pytest.raises((FileNotFoundError, OSError)):+ reader.read_file("invalid://example.com")def test_find_python_code_in_github_issue_multiple_codes() -> None:@@ -133,14 +213,14 @@ def test_find_python_code_in_github_issue_multiple_codes() -> None:```"""expected = '\n print("First block of Python code")\n '- actual = _find_python_code_in_github_issue(body)+ actual = GitHubIssueReader._find_python_code_in_github_issue(body)assert actual == expectedbody = """some text without any code blocks."""try:- _find_python_code_in_github_issue(body)+ GitHubIssueReader._find_python_code_in_github_issue(body)raise AssertionError("Expected an IndexError")except IndexError:# IndexError if there are no code blocks@@ -153,5 +233,122 @@ def test_find_python_code_in_github_issue_multiple_codes() -> None:```"""expected = '\n print("Only one block of Python code")\n '- actual = _find_python_code_in_github_issue(body)+ actual = GitHubIssueReader._find_python_code_in_github_issue(body)assert actual == expected+++def test_validate_name_with_invalid_extension():+ with pytest.raises(click.ClickException):+ validate_name(+ "file.invalid", allow_new_file=True, allow_directory=False+ )+++def test_validate_name_with_markdown_file():+ assert (+ validate_name("file.md", allow_new_file=True, allow_directory=False)[0]+ == "file.md"+ )+++def test_validate_name_with_jupyter_notebook():+ with pytest.raises(click.ClickException) as excinfo:+ validate_name(+ "notebook.ipynb", allow_new_file=True, allow_directory=False+ )+ assert "Convert notebook.ipynb to a marimo notebook" in str(excinfo.value)+++def test_generic_url_reader_with_query_params():+ reader = GenericURLReader()+ url = "https://example.com/file.py?param=value"+ assert reader.can_read(url) is True+ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_urlopen.return_value = mock_response()+ content, filename = reader.read(url)+ assert content == "print('Hello, world!')"+ assert filename == "file.py"+++def test_static_notebook_reader_url_formats():+ reader = StaticNotebookReader()+ urls = [+ "https://static.marimo.app/example",+ "https://static.marimo.app/example/",+ "https://static.marimo.app/example.html",+ ]+ for url in urls:+ with patch.object(+ StaticNotebookReader, "_is_static_marimo_notebook_url"+ ) as mock_is_static:+ mock_is_static.return_value = (+ True,+ "<marimo-code hidden=''>print('Hello')</marimo-code><marimo-filename hidden=''>test.py</marimo-filename>", # noqa: E501+ )+ assert reader.can_read(url) is True+ content, filename = reader.read(url)+ assert content == "print('Hello')"+ assert filename == "test.py"+++def test_github_issue_reader_nonexistent_issue():+ reader = GitHubIssueReader()+ url = "https://github.com/marimo-team/marimo/issues/999999" # noqa: E501+ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_urlopen.side_effect = urllib.error.HTTPError(+ url,+ 404,+ "Not Found",+ {}, # ignore+ None,+ )+ with pytest.raises(urllib.error.HTTPError):+ reader.read(url)+++def test_github_source_reader_different_extensions():+ reader = GitHubSourceReader()+ urls = [+ "https://github.com/marimo-team/marimo/blob/main/example.py",+ "https://github.com/marimo-team/marimo/blob/main/README.md",+ ]+ for url in urls:+ assert reader.can_read(url) is True+ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_response = mock_open(read_data="content".encode())+ mock_urlopen.return_value = mock_response()+ content, filename = reader.read(url)+ assert content == "content"+ assert filename in ["example.py", "README.md"]+++def test_local_file_reader_with_spaces():+ reader = LocalFileReader()+ filename = "file with spaces.py"+ assert reader.can_read(filename) is True+ with patch("builtins.open", mock_open(read_data="print('Hello, world!')")):+ content, read_filename = reader.read(filename)+ assert content == "print('Hello, world!')"+ assert read_filename == filename+++def test_validate_name_with_relative_and_absolute_paths():+ relative_path = "relative/path/file.py"+ absolute_path = "/absolute/path/file.py"++ with patch("os.path.exists", return_value=True), patch(+ "pathlib.Path.is_file", return_value=True+ ):+ assert (+ validate_name(+ relative_path, allow_new_file=False, allow_directory=False+ )[0]+ == relative_path+ )+ assert (+ validate_name(+ absolute_path, allow_new_file=False, allow_directory=False+ )[0]+ == absolute_path+ )