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.

feat: Automatically loading env vars using dotenv + specify custom env files (#4280)

Luis Chaves Rodriguez053490eed263
diff --git a/.env.testing b/.env.testing
new file mode 100644
index 0000000000..315d23f101
--- /dev/null
+++ b/.env.testing
@@ -0,0 +1 @@
+FOO_BAR_SECRET=foo_bar_secret
diff --git a/docs/guides/configuration/runtime_configuration.md b/docs/guides/configuration/runtime_configuration.md
index e74038b564..462e335c5a 100644
--- a/docs/guides/configuration/runtime_configuration.md
+++ b/docs/guides/configuration/runtime_configuration.md
@@ -97,3 +97,16 @@ find and import modules from these directories.
[tool.marimo.runtime]
pythonpath = ["project/src"]
```
+
+## Environment variables
+
+### .env files
+
+marimo supports loading environment variables from `.env` files. This is useful for managing configuration that should not be committed to version control, such as API keys or database credentials.
+
+The `.env` next to your `pyproject.toml` is loaded by default. To configure multiple or a different location, you can specify them in your configuration:
+
+```toml title="pyproject.toml"
+[tool.marimo.runtime]
+dotenv = [".env", ".env.testing"]
+```
diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
index ec86cb10f9..06326b8140 100644
--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx
+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
@@ -57,6 +57,7 @@ describe("Cell data attributes", () => {
output_max_bytes: 1_000_000,
std_stream_max_bytes: 1_000_000,
pythonpath: [],
+ dotenv: [".env"],
},
server: {
browser: "default",
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 500904c93e..9781270879 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -123,6 +123,9 @@ class RuntimeConfig(TypedDict):
Directories will be added to the head of sys.path. Similar to the
`PYTHONPATH` environment variable, the directories will be included in
where Python will look for imported modules.
+ - `dotenv`: a list of paths to `.env` files to load.
+ If the file does not exist, it will be silently ignored.
+ The default is `[".env"]` if a pyproject.toml is found, otherwise `[]`.
"""
auto_instantiate: bool
@@ -131,7 +134,8 @@ class RuntimeConfig(TypedDict):
watcher_on_save: Literal["lazy", "autorun"]
output_max_bytes: int
std_stream_max_bytes: int
- pythonpath: list[str]
+ pythonpath: NotRequired[list[str]]
+ dotenv: NotRequired[list[str]]
# TODO(akshayka): remove normal, migrate to compact
@@ -402,7 +406,6 @@ DEFAULT_CONFIG: MarimoConfig = {
"std_stream_max_bytes": int(
os.getenv("MARIMO_STD_STREAM_MAX_BYTES", 1_000_000)
),
- "pythonpath": [],
},
"save": {
"autosave": "after_delay",
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 9c62e875e2..ae6e58d2a7 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -14,6 +14,7 @@ from marimo._config.config import (
LanguageServersConfig,
MarimoConfig,
PartialMarimoConfig,
+ RuntimeConfig,
Theme,
WidthType,
merge_config,
@@ -21,6 +22,7 @@ from marimo._config.config import (
)
from marimo._config.packages import PackageManagerKind
from marimo._config.reader import (
+ find_nearest_pyproject_toml,
get_marimo_config_from_pyproject_dict,
read_marimo_config,
read_pyproject_marimo_config,
@@ -171,13 +173,17 @@ class ProjectConfigManager(PartialMarimoConfigReader):
"""Read the project configuration"""
def __init__(self, start_path: str) -> None:
- self.start_path = start_path
+ self.pyproject_path = find_nearest_pyproject_toml(start_path)
def get_config(self, *, hide_secrets: bool = True) -> PartialMarimoConfig:
try:
- project_config = read_pyproject_marimo_config(self.start_path)
+ if self.pyproject_path is None:
+ return {}
+ project_config = read_pyproject_marimo_config(self.pyproject_path)
if project_config is None:
return {}
+ project_config = self._resolve_pythonpath(project_config)
+ project_config = self._resolve_dotenv(project_config)
except Exception as e:
LOGGER.warning("Failed to read project config: %s", e)
return {}
@@ -186,6 +192,53 @@ class ProjectConfigManager(PartialMarimoConfigReader):
return mask_secrets_partial(project_config)
return project_config
+ def _resolve_pythonpath(
+ self, config: PartialMarimoConfig
+ ) -> PartialMarimoConfig:
+ if self.pyproject_path is None:
+ return config
+
+ if "runtime" not in config:
+ return config
+
+ if "pythonpath" not in config["runtime"]:
+ return config
+
+ pythonpath = config["runtime"]["pythonpath"]
+
+ if not isinstance(pythonpath, list):
+ return config
+
+ resolved_pythonpath = [
+ str((self.pyproject_path.parent / path).absolute())
+ for path in pythonpath
+ ]
+ return {
+ **config,
+ "runtime": {
+ **config["runtime"],
+ "pythonpath": resolved_pythonpath,
+ },
+ }
+
+ def _resolve_dotenv(
+ self, config: PartialMarimoConfig
+ ) -> PartialMarimoConfig:
+ if self.pyproject_path is None:
+ return config
+
+ runtime = config.get("runtime", cast(RuntimeConfig, {}))
+ dotenv = runtime.get("dotenv", [".env"])
+
+ if not isinstance(dotenv, list):
+ return config
+
+ resolved_dotenv = [
+ str((self.pyproject_path.parent / path).absolute())
+ for path in dotenv
+ ]
+ return {**config, "runtime": {**runtime, "dotenv": resolved_dotenv}}
+
class ScriptConfigManager(PartialMarimoConfigReader):
"""Read the script configuration following PEP 723
diff --git a/marimo/_config/reader.py b/marimo/_config/reader.py
index d6f935d775..d32c15fc39 100644
--- a/marimo/_config/reader.py
+++ b/marimo/_config/reader.py
@@ -17,19 +17,16 @@ def read_marimo_config(path: str) -> PartialMarimoConfig:
def read_pyproject_marimo_config(
- start_path: Union[str, Path],
+ pyproject_path: Union[str, Path],
) -> Optional[PartialMarimoConfig]:
- """Find the nearest pyproject.toml file, then read the marimo tool config."""
- path = find_nearest_pyproject_toml(start_path)
- if path is None:
- return None
- pyproject_config = read_toml(path)
+ """Read the marimo tool config from a pyproject.toml file."""
+ pyproject_config = read_toml(pyproject_path)
marimo_tool_config = get_marimo_config_from_pyproject_dict(
pyproject_config
)
if marimo_tool_config is None:
return None
- LOGGER.debug("Found marimo config in pyproject.toml at %s", path)
+ LOGGER.debug("Found marimo config in pyproject.toml at %s", pyproject_path)
return marimo_tool_config
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 3eab36d528..f994f4e330 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -196,6 +196,7 @@ class DependencyManager:
pytest = Dependency("pytest")
vegafusion = Dependency("vegafusion")
vl_convert_python = Dependency("vl_convert")
+ dotenv = Dependency("dotenv")
# Version requirements to properly support the new superfences introduced in
# pymdown#2470
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 1283dcb32e..d17584793a 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -16,6 +16,7 @@ import time
import traceback
from copy import copy, deepcopy
from multiprocessing import connection
+from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Optional, cast
from uuid import uuid4
@@ -1992,6 +1993,8 @@ class Kernel:
During instantiation, UIElements can check for an initial value
with `get_initial_value`
"""
+ self.load_dotenv()
+
if self.graph.cells:
del request
LOGGER.debug("App already instantiated.")
@@ -2011,6 +2014,21 @@ class Kernel:
for cid in self._uninstantiated_execution_requests:
CellOp.broadcast_stale(cell_id=cid, stale=True)
+ def load_dotenv(self) -> None:
+ if not DependencyManager.dotenv.has():
+ return
+
+ from dotenv import load_dotenv # type: ignore[import-not-found]
+
+ for env in self.user_config["runtime"]["dotenv"]:
+ if Path(env).exists():
+ try:
+ load_dotenv(env)
+ except Exception as e:
+ LOGGER.error(
+ "Failed to load dotenv file %s", env, exc_info=e
+ )
+
async def install_missing_packages(
self, request: InstallMissingPackagesRequest
) -> None:
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 2865f4d6c2..966207e3bb 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1478,6 +1478,10 @@ components:
- lazy
- autorun
type: string
+ dotenv:
+ items:
+ type: string
+ type: array
on_cell_change:
enum:
- lazy
@@ -1503,7 +1507,6 @@ components:
- watcher_on_save
- output_max_bytes
- std_stream_max_bytes
- - pythonpath
type: object
save:
properties:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index a7f628f0ff..750da6d365 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2839,10 +2839,11 @@ export interface components {
auto_instantiate: boolean;
/** @enum {string} */
auto_reload: "off" | "lazy" | "autorun";
+ dotenv?: string[];
/** @enum {string} */
on_cell_change: "lazy" | "autorun";
output_max_bytes: number;
- pythonpath: string[];
+ pythonpath?: string[];
std_stream_max_bytes: number;
/** @enum {string} */
watcher_on_save: "lazy" | "autorun";
diff --git a/pyproject.toml b/pyproject.toml
index cbf87db3ae..3279041117 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -525,3 +525,4 @@ dataframes = "rich"
watcher_on_save = "autorun"
output_max_bytes = 10_000_000
std_stream_max_bytes = 2_000_000
+dotenv = [".env.testing"]
\ No newline at end of file
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index 9c88cb6135..579be5ca63 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -201,6 +201,9 @@ def test_project_config_manager_with_script_metadata(tmp_path: Path) -> None:
"format_on_save": True, # From pyproject.toml
"autosave": "after_delay", # From pyproject.toml
},
+ "runtime": {
+ "dotenv": [str(tmp_path / ".env")],
+ },
}
@@ -271,3 +274,77 @@ def test_marimo_config_reader_properties() -> None:
assert manager.default_width is not None
assert manager.theme is not None
assert manager.package_manager is not None
+
+
+def test_project_config_manager_resolve_paths(tmp_path: Path) -> None:
+ # Create a pyproject.toml with pythonpath and dotenv settings
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = """
+ [tool.marimo.runtime]
+ pythonpath = ["src", "lib"]
+ dotenv = [".env", "config/.env"]
+ """
+ pyproject_path.write_text(textwrap.dedent(pyproject_content))
+
+ # Create the directory structure
+ (tmp_path / "src").mkdir()
+ (tmp_path / "lib").mkdir()
+ (tmp_path / "config").mkdir()
+ (tmp_path / ".env").touch()
+ (tmp_path / "config" / ".env").touch()
+
+ # Initialize ProjectConfigManager
+ manager = get_default_config_manager(current_path=str(pyproject_path))
+ config = manager.get_config(hide_secrets=False)
+
+ # Verify pythonpath resolution
+ expected_pythonpath = [
+ str((tmp_path / "src").absolute()),
+ str((tmp_path / "lib").absolute()),
+ ]
+ assert config["runtime"]["pythonpath"] == expected_pythonpath
+
+ # Verify dotenv resolution
+ expected_dotenv = [
+ str((tmp_path / ".env").absolute()),
+ str((tmp_path / "config" / ".env").absolute()),
+ ]
+ assert config["runtime"]["dotenv"] == expected_dotenv
+
+
+def test_project_config_manager_resolve_invalid_paths(tmp_path: Path) -> None:
+ # Create a pyproject.toml with invalid path types
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = """
+ [tool.marimo.runtime]
+ pythonpath = "not_a_list"
+ dotenv = 123
+ """
+ pyproject_path.write_text(textwrap.dedent(pyproject_content))
+
+ # Initialize ProjectConfigManager
+ manager = get_default_config_manager(current_path=str(pyproject_path))
+ config = manager.get_config(hide_secrets=False)
+
+ # Verify invalid paths are not modified
+ assert config["runtime"]["pythonpath"] == "not_a_list"
+ assert config["runtime"]["dotenv"] == 123
+
+
+def test_project_config_manager_resolve_missing_paths(tmp_path: Path) -> None:
+ # Create a pyproject.toml without path settings
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = """
+ [tool.marimo.runtime]
+ other_setting = "value"
+ """
+ pyproject_path.write_text(textwrap.dedent(pyproject_content))
+
+ # Initialize ProjectConfigManager
+ manager = get_default_config_manager(current_path=str(pyproject_path))
+ config = manager.get_config(hide_secrets=False)
+
+ # Verify missing paths don't cause issues
+ assert config["runtime"].get("pythonpath", []) == []
+ assert config["runtime"]["dotenv"] == [str(tmp_path / ".env")]
+ assert config["runtime"]["other_setting"] == "value"
diff --git a/tests/_config/test_reader.py b/tests/_config/test_reader.py
index 397fdec297..b65365e726 100644
--- a/tests/_config/test_reader.py
+++ b/tests/_config/test_reader.py
@@ -51,7 +51,7 @@ def test_read_marimo_config():
}
-def test_read_pyproject_config_with_marimo_section():
+def test_read_pyproject_config_with_marimo_section(tmp_path: Path):
pyproject_content = """
[tool.marimo]
formatting = {line_length = 79}
@@ -64,55 +64,51 @@ def test_read_pyproject_config_with_marimo_section():
[tool.marimo.novalidate]
old_keys_are_ok = true
"""
- with patch("builtins.open", mock_open(read_data=pyproject_content)):
- with patch(
- "marimo._config.reader.find_nearest_pyproject_toml"
- ) as mock_find:
- mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_marimo_config("/some/path")
- assert result == {
- "formatting": {"line_length": 79},
- "save": {
- "autosave_delay": 1000,
- "format_on_save": True,
- "autosave": "after_delay",
- },
- "novalidate": {"old_keys_are_ok": True},
- }
-
-
-def test_read_pyproject_config_without_marimo_section():
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_path.write_text(pyproject_content)
+ nearest_pyproject_toml = find_nearest_pyproject_toml(tmp_path)
+ assert nearest_pyproject_toml is not None
+ result = read_pyproject_marimo_config(nearest_pyproject_toml)
+ assert result == {
+ "formatting": {"line_length": 79},
+ "save": {
+ "autosave_delay": 1000,
+ "format_on_save": True,
+ "autosave": "after_delay",
+ },
+ "novalidate": {"old_keys_are_ok": True},
+ }
+
+
+def test_read_pyproject_config_without_marimo_section(tmp_path: Path):
pyproject_content = """
[tool.idk]
name = "foo"
"""
- with patch("builtins.open", mock_open(read_data=pyproject_content)):
- with patch(
- "marimo._config.reader.find_nearest_pyproject_toml"
- ) as mock_find:
- mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_marimo_config("/some/path")
- assert result is None
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_path.write_text(pyproject_content)
+ nearest_pyproject_toml = find_nearest_pyproject_toml(tmp_path)
+ assert nearest_pyproject_toml is not None
+ result = read_pyproject_marimo_config(nearest_pyproject_toml)
+ assert result is None
-def test_read_pyproject_config_invalid_marimo_section():
+def test_read_pyproject_config_invalid_marimo_section(tmp_path: Path):
pyproject_content = """
[tool]
marimo = "invalid"
"""
- with patch("builtins.open", mock_open(read_data=pyproject_content)):
- with patch(
- "marimo._config.reader.find_nearest_pyproject_toml"
- ) as mock_find:
- mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_marimo_config("/some/path")
- assert result is None
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_path.write_text(pyproject_content)
+ nearest_pyproject_toml = find_nearest_pyproject_toml(tmp_path)
+ assert nearest_pyproject_toml is not None
+ result = read_pyproject_marimo_config(nearest_pyproject_toml)
+ assert result is None
-def test_read_pyproject_config_no_file():
- with tempfile.TemporaryDirectory() as temp_dir:
- result = read_pyproject_marimo_config(temp_dir)
- assert result is None
+def test_read_pyproject_config_no_file(tmp_path: Path):
+ nearest_pyproject_toml = find_nearest_pyproject_toml(tmp_path)
+ assert nearest_pyproject_toml is None
def testfind_nearest_pyproject_toml():
diff --git a/tests/_runtime/test_dotenv.py b/tests/_runtime/test_dotenv.py
new file mode 100644
index 0000000000..42d496d06a
--- /dev/null
+++ b/tests/_runtime/test_dotenv.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+import os
+import tempfile
+
+import pytest
+
+from marimo._config.config import merge_default_config
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.requests import (
+ CreationRequest,
+ SetUIElementValueRequest,
+)
+from tests.conftest import MockedKernel
+
+
+ not DependencyManager.dotenv.has(), reason="dotenv is not installed"
+)
+class TestDotEnv:
+ def test_load_dotenv_success(self, mocked_kernel: MockedKernel):
+ # Create a temporary .env file
+ with tempfile.NamedTemporaryFile(suffix=".env", mode="w+") as env_file:
+ env_file.write("TEST_VAR=test_value\n")
+ env_file.write("ANOTHER_VAR=another_value\n")
+ env_file.flush()
+
+ # Create a custom config with the path to our temp .env file
+ custom_config = merge_default_config(
+ {
+ "runtime": {
+ "dotenv": [env_file.name],
+ },
+ }
+ )
+ mocked_kernel.k.user_config = custom_config
+
+ # Load the .env file
+ mocked_kernel.k.load_dotenv()
+
+ # Check that the environment variables were set
+ assert os.environ.get("TEST_VAR") == "test_value"
+ assert os.environ.get("ANOTHER_VAR") == "another_value"
+
+ def test_load_dotenv_nonexistent_file(self, mocked_kernel: MockedKernel):
+ # Create a config with a nonexistent .env file
+ custom_config = merge_default_config(
+ {
+ "runtime": {
+ "dotenv": ["nonexistent.env"],
+ },
+ }
+ )
+ mocked_kernel.k.user_config = custom_config
+
+ # Create a kernel with our custom config
+ # This should not raise an exception
+ mocked_kernel.k.load_dotenv()
+
+ async def test_load_dotenv_on_instantiate(
+ self, mocked_kernel: MockedKernel
+ ):
+ # Create a temporary .env file
+ with tempfile.NamedTemporaryFile(suffix=".env", mode="w+") as env_file:
+ env_file.write("INSTANTIATE_TEST_VAR=instantiate_value\n")
+ env_file.flush()
+
+ # Create a custom config with the path to our temp .env file
+ custom_config = merge_default_config(
+ {
+ "runtime": {
+ "dotenv": [env_file.name],
+ },
+ }
+ )
+ mocked_kernel.k.user_config = custom_config
+
+ # Create a CreationRequest
+ request = CreationRequest(
+ execution_requests=(),
+ set_ui_element_value_request=SetUIElementValueRequest(
+ object_ids=[],
+ values=[],
+ ),
+ auto_run=True,
+ )
+
+ # Call instantiate, which should call load_dotenv
+ await mocked_kernel.k.instantiate(request)
+
+ # Check that the environment variable was set
+ assert (
+ os.environ.get("INSTANTIATE_TEST_VAR") == "instantiate_value"
+ )
+
+
+ DependencyManager.dotenv.has(), reason="dotenv should not be installed"
+)
+class TestDotEnvNotInstalled:
+ def test_load_dotenv_import_error(self, mocked_kernel: MockedKernel):
+ # This should not raise an exception
+ mocked_kernel.k.load_dotenv()
+
+ # No environment variables should be set
+ assert os.environ.get("TEST_VAR") is None
+ assert os.environ.get("ANOTHER_VAR") is None
+
+ async def test_instantiate_without_dotenv(
+ self, mocked_kernel: MockedKernel
+ ):
+ # Create a temporary .env file
+ with tempfile.NamedTemporaryFile(suffix=".env", mode="w+") as env_file:
+ env_file.write("ENV_VAR_SHOULD_NOT_LOAD=test_value\n")
+ env_file.flush()
+
+ # Create a custom config with the path to our temp .env file
+ custom_config = merge_default_config(
+ {
+ "runtime": {
+ "dotenv": [env_file.name],
+ },
+ }
+ )
+ mocked_kernel.k.user_config = custom_config
+
+ # Create a CreationRequest
+ request = CreationRequest(
+ execution_requests=(),
+ set_ui_element_value_request=SetUIElementValueRequest(
+ object_ids=[],
+ values=[],
+ ),
+ auto_run=True,
+ )
+
+ # Call instantiate, which tries to call load_dotenv
+ await mocked_kernel.k.instantiate(request)
+
+ # Verify that no environment variables were set
+ assert os.environ.get("ENV_VAR_SHOULD_NOT_LOAD") is None
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index 9aac1f2d18..6893ca2695 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -55,7 +55,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 423f520a56..379ab51a1f 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -55,7 +55,7 @@
<marimo-filename hidden></marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>marimo</title>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index 2dbb46bf2a..c3536f9238 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -55,7 +55,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index 75e2fb6421..dd07d607ce 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -55,7 +55,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"css_file": "custom.css", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index c5d2231427..762fcd0270 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -55,7 +55,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"app_title": "My App", "html_head_file": "head.html", "width": "compact"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>My App</title>
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
index 5033a0ee3e..7e6c1af617 100644
--- a/tests/_server/templates/test_templates.py
+++ b/tests/_server/templates/test_templates.py
@@ -1,13 +1,19 @@
from __future__ import annotations
import json
-import os
+import shutil
+import tempfile
import unittest
+from pathlib import Path
from typing import Literal
from marimo._ast.app import _AppConfig
from marimo._ast.cell import CellConfig
-from marimo._config.config import DEFAULT_CONFIG, PartialMarimoConfig
+from marimo._config.config import (
+ MarimoConfig,
+ PartialMarimoConfig,
+ merge_default_config,
+)
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._server.export.exporter import hash_code
from marimo._server.model import SessionMode
@@ -17,25 +23,28 @@ from tests._server.templates.utils import normalize_index_html
from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
+default_config = merge_default_config({})
class TestNotebookPageTemplate(unittest.TestCase):
def setUp(self) -> None:
- root = os.path.realpath(
- os.path.join(os.path.dirname(__file__), "data")
- )
- index_html = os.path.join(root, "index.html")
- with open(index_html) as f:
- self.html = f.read()
+ tmp_path = Path(tempfile.mkdtemp())
+ self.tmp_path = tmp_path
+ root = Path(__file__).parent / "data"
+ index_html = root / "index.html"
+ self.html = index_html.read_text(encoding="utf-8")
self.base_url = "/subpath"
- self.user_config = DEFAULT_CONFIG
+ self.user_config: MarimoConfig = default_config
self.config_overrides: PartialMarimoConfig = {}
self.server_token = SkewProtectionToken("token")
self.app_config = _AppConfig()
- self.filename = "notebook.py"
+ self.filename = tmp_path / "notebook.py"
self.mode = SessionMode.RUN
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp_path)
+
def test_notebook_page_template(self) -> None:
result = templates.notebook_page_template(
self.html,
@@ -44,13 +53,13 @@ class TestNotebookPageTemplate(unittest.TestCase):
self.config_overrides,
self.server_token,
self.app_config,
- self.filename,
+ str(self.filename),
self.mode,
)
assert self.base_url not in result
assert str(self.server_token) in result
- assert self.filename in result
+ assert self.filename.name in result
assert "read" in result
def test_notebook_page_template_no_filename(self) -> None:
@@ -78,38 +87,34 @@ class TestNotebookPageTemplate(unittest.TestCase):
self.config_overrides,
self.server_token,
self.app_config,
- self.filename,
+ str(self.filename),
SessionMode.EDIT,
)
assert self.base_url not in result
assert str(self.server_token) in result
- assert self.filename in result
+ assert self.filename.name in result
assert "edit" in result
def test_notebook_page_template_custom_css(self) -> None:
# Create css file
css = "/* custom css */"
- css_file = os.path.join(os.path.dirname(self.filename), "custom.css")
- with open(css_file, "w") as f:
- f.write(css)
-
- try:
- result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(css_file="custom.css"),
- self.filename,
- self.mode,
- )
+ css_file = self.filename.parent / "custom.css"
+ css_file.write_text(css)
+
+ result = templates.notebook_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.config_overrides,
+ self.server_token,
+ _AppConfig(css_file="custom.css"),
+ str(self.filename),
+ self.mode,
+ )
- assert css in result
- finally:
- os.remove(css_file)
+ assert css in result
def test_notebook_page_template_custom_head(self) -> None:
# Create html head file
@@ -125,43 +130,40 @@ class TestNotebookPageTemplate(unittest.TestCase):
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
"""
- head_file = os.path.join(os.path.dirname(self.filename), "head.html")
- with open(head_file, "w") as f:
- f.write(head)
-
- try:
- result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(html_head_file="head.html"),
- self.filename,
- self.mode,
- )
+ head_file = self.filename.parent / "head.html"
+ head_file.write_text(head)
+
+ result = templates.notebook_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.config_overrides,
+ self.server_token,
+ _AppConfig(html_head_file="head.html"),
+ str(self.filename),
+ self.mode,
+ )
- assert head in result
- finally:
- os.remove(head_file)
+ assert head in result
class TestHomePageTemplate(unittest.TestCase):
def setUp(self) -> None:
- root = os.path.realpath(
- os.path.join(os.path.dirname(__file__), "data")
- )
- index_html = os.path.join(root, "index.html")
- with open(index_html) as f:
- self.html = f.read()
+ self.tmp_path = Path(tempfile.mkdtemp())
+ root = Path(__file__).parent / "data"
+ index_html = root / "index.html"
+ self.html = index_html.read_text(encoding="utf-8")
self.base_url = "/subpath"
- self.user_config = DEFAULT_CONFIG
+ self.user_config: MarimoConfig = default_config
self.config_overrides: PartialMarimoConfig = {
"formatting": {"line_length": 100},
}
self.server_token = SkewProtectionToken("token")
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp_path)
+
def test_home_page_template(self) -> None:
result = templates.home_page_template(
self.html,
@@ -182,20 +184,19 @@ class TestHomePageTemplate(unittest.TestCase):
class TestStaticNotebookTemplate(unittest.TestCase):
def setUp(self) -> None:
- root = os.path.realpath(
- os.path.join(os.path.dirname(__file__), "data")
- )
- index_html = os.path.join(root, "index.html")
- with open(index_html) as f:
- self.html = f.read()
+ tmp_path = Path(tempfile.mkdtemp())
+ self.tmp_path = tmp_path
+ root = Path(__file__).parent / "data"
+ index_html = root / "index.html"
+ self.html = index_html.read_text(encoding="utf-8")
- self.user_config = DEFAULT_CONFIG
+ self.user_config = default_config
self.config_overrides: PartialMarimoConfig = {
"formatting": {"line_length": 100},
}
self.server_token = SkewProtectionToken("token")
self.app_config = _AppConfig()
- self.filename = "notebook.py"
+ self.filename = tmp_path / "notebook.py"
self.filepath = "path/to/notebook.py"
self.code = "print('Hello, World!')"
self.cell_ids = ["cell1", "cell2"]
@@ -229,6 +230,9 @@ class TestStaticNotebookTemplate(unittest.TestCase):
}
self.files = {"file1": "File 1 content", "file2": "File 2 content"}
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp_path)
+
def test_static_notebook_template(self) -> None:
result = templates.static_notebook_template(
self.html,
@@ -296,32 +300,28 @@ class TestStaticNotebookTemplate(unittest.TestCase):
# Create css file
css = "/* custom css */"
- css_file = os.path.join(os.path.dirname(self.filename), "custom.css")
- with open(css_file, "w") as f:
- f.write(css)
-
- try:
- result = templates.static_notebook_template(
- self.html,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(css_file="custom.css"),
- self.filename,
- "",
- hash_code(self.code),
- [],
- [],
- [],
- [],
- {},
- {},
- {},
- )
+ css_file = self.filename.parent / "custom.css"
+ css_file.write_text(css)
+
+ result = templates.static_notebook_template(
+ self.html,
+ self.user_config,
+ self.config_overrides,
+ self.server_token,
+ _AppConfig(css_file="custom.css"),
+ str(self.filename),
+ "",
+ hash_code(self.code),
+ [],
+ [],
+ [],
+ [],
+ {},
+ {},
+ {},
+ )
- snapshot("export4.txt", normalize_index_html(result))
- finally:
- os.remove(css_file)
+ snapshot("export4.txt", normalize_index_html(result))
def test_static_notebook_template_with_head(self) -> None:
# Create html head file
@@ -337,56 +337,54 @@ class TestStaticNotebookTemplate(unittest.TestCase):
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
"""
- head_file = os.path.join(os.path.dirname(self.filename), "head.html")
- with open(head_file, "w") as f:
- f.write(head)
-
- try:
- result = templates.static_notebook_template(
- self.html,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(html_head_file="head.html", app_title="My App"),
- self.filename,
- "",
- hash_code(self.code),
- [],
- [],
- [],
- [],
- {},
- {},
- {},
- )
+ head_file = self.filename.parent / "head.html"
+ head_file.write_text(head)
- snapshot("export5.txt", normalize_index_html(result))
- finally:
- os.remove(head_file)
+ result = templates.static_notebook_template(
+ self.html,
+ self.user_config,
+ self.config_overrides,
+ self.server_token,
+ _AppConfig(html_head_file="head.html", app_title="My App"),
+ str(self.filename),
+ "",
+ hash_code(self.code),
+ [],
+ [],
+ [],
+ [],
+ {},
+ {},
+ {},
+ )
+
+ snapshot("export5.txt", normalize_index_html(result))
class TestWasmNotebookTemplate(unittest.TestCase):
def setUp(self) -> None:
- root = os.path.realpath(
- os.path.join(os.path.dirname(__file__), "data")
- )
- index_html = os.path.join(root, "index.html")
- with open(index_html) as f:
- self.html = f.read()
+ tmp_path = Path(tempfile.mkdtemp())
+ self.tmp_path = tmp_path
+ root = Path(__file__).parent / "data"
+ index_html = root / "index.html"
+ self.html = index_html.read_text(encoding="utf-8")
self.version = "1.0.0"
- self.filename = "notebook.py"
+ self.filename = tmp_path / "notebook.py"
self.mode: Literal["edit", "run"] = "run"
- self.user_config = DEFAULT_CONFIG
+ self.user_config: MarimoConfig = default_config
self.app_config = _AppConfig()
self.code = "print('Hello, World!')"
self.config_overrides: PartialMarimoConfig = {}
+ def tearDown(self) -> None:
+ shutil.rmtree(self.tmp_path)
+
def test_wasm_notebook_template(self) -> None:
result = templates.wasm_notebook_template(
html=self.html,
version=self.version,
- filename=self.filename,
+ filename=str(self.filename),
mode=self.mode,
user_config=self.user_config,
config_overrides=self.config_overrides,
@@ -395,7 +393,7 @@ class TestWasmNotebookTemplate(unittest.TestCase):
show_code=False,
)
- assert self.filename in result
+ assert self.filename.name in result
assert self.mode in result
assert json.dumps(self.user_config) in result
assert '<marimo-wasm hidden="">' in result
@@ -406,30 +404,26 @@ class TestWasmNotebookTemplate(unittest.TestCase):
# Create css file
css = "/* custom css */"
- css_file = os.path.join(os.path.dirname(self.filename), "custom.css")
- with open(css_file, "w") as f:
- f.write(css)
-
- try:
- result = templates.wasm_notebook_template(
- html=self.html,
- version=self.version,
- filename=self.filename,
- mode=self.mode,
- user_config=self.user_config,
- config_overrides=self.config_overrides,
- app_config=_AppConfig(css_file="custom.css"),
- code=self.code,
- asset_url="https://my.cdn.com",
- show_code=True,
- )
+ css_file = self.filename.parent / "custom.css"
+ css_file.write_text(css)
- assert css in result
- assert '<marimo-wasm hidden="">' in result
- assert "https://my.cdn.com/assets/" in result
- assert '<marimo-code hidden="" data-show-code="true">' in result
- finally:
- os.remove(css_file)
+ result = templates.wasm_notebook_template(
+ html=self.html,
+ version=self.version,
+ filename=str(self.filename),
+ mode=self.mode,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ app_config=_AppConfig(css_file="custom.css"),
+ code=self.code,
+ asset_url="https://my.cdn.com",
+ show_code=True,
+ )
+
+ assert css in result
+ assert '<marimo-wasm hidden="">' in result
+ assert "https://my.cdn.com/assets/" in result
+ assert '<marimo-code hidden="" data-show-code="true">' in result
def test_wasm_notebook_template_custom_head(self) -> None:
# Create html head file
@@ -445,30 +439,26 @@ class TestWasmNotebookTemplate(unittest.TestCase):
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
"""
- head_file = os.path.join(os.path.dirname(self.filename), "head.html")
- with open(head_file, "w") as f:
- f.write(head)
-
- try:
- result = templates.wasm_notebook_template(
- html=self.html,
- version=self.version,
- filename=self.filename,
- mode=self.mode,
- user_config=self.user_config,
- config_overrides=self.config_overrides,
- app_config=_AppConfig(
- html_head_file="head.html", app_title="My App"
- ),
- code=self.code,
- show_code=False,
- )
+ head_file = self.filename.parent / "head.html"
+ head_file.write_text(head)
- assert head in result
- assert '<marimo-wasm hidden="">' in result
- assert '<marimo-code hidden="" data-show-code="false">' in result
- assert "#save-button" in result
- assert "#filename-input" in result
- assert "<title>My App</title>" in result
- finally:
- os.remove(head_file)
+ result = templates.wasm_notebook_template(
+ html=self.html,
+ version=self.version,
+ filename=str(self.filename),
+ mode=self.mode,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ app_config=_AppConfig(
+ html_head_file="head.html", app_title="My App"
+ ),
+ code=self.code,
+ show_code=False,
+ )
+
+ assert head in result
+ assert '<marimo-wasm hidden="">' in result
+ assert '<marimo-code hidden="" data-show-code="false">' in result
+ assert "#save-button" in result
+ assert "#filename-input" in result
+ assert "<title>My App</title>" in result