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.

cleanup: xdg config commons and migrate utils to use Path (#6101)

Myles Scolnickf83e966be00f
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
index efb227b2cc..a4a90cb264 100644
--- a/marimo/_cli/upgrade.py
+++ b/marimo/_cli/upgrade.py
@@ -76,7 +76,7 @@ def _update_with_latest_version(state: MarimoCLIState) -> MarimoCLIState:
# querying pypi is +250kb and there is not a better API
# this endpoint just returns the version
# so we only use pypi in tests
- is_test = os.environ.get("MARIMO_PYTEST_HOME_DIR") is not None
+ is_test = os.environ.get("PYTEST_CURRENT_TEST") is not None
if is_test:
api_url = "https://pypi.org/pypi/marimo/json"
else:
diff --git a/marimo/_config/cli_state.py b/marimo/_config/cli_state.py
index 61501eeb1a..2626b1b15e 100644
--- a/marimo/_config/cli_state.py
+++ b/marimo/_config/cli_state.py
@@ -17,12 +17,8 @@ class MarimoCLIState:
FILE_NAME = "state.toml"
-def get_cli_state() -> Optional[MarimoCLIState]:
+def get_cli_state() -> MarimoCLIState:
config_reader = ConfigReader.for_filename(FILE_NAME)
- if not config_reader:
- # Couldn't find home directory, so do nothing
- return None
-
# Load the state file or create a default state if it doesn't exist
state = config_reader.read_toml(MarimoCLIState, fallback=MarimoCLIState())
return state
@@ -30,7 +26,4 @@ def get_cli_state() -> Optional[MarimoCLIState]:
def write_cli_state(state: MarimoCLIState) -> None:
config_reader = ConfigReader.for_filename(FILE_NAME)
- if not config_reader:
- # Couldn't find home directory, so do nothing
- return
config_reader.write_toml(state)
diff --git a/marimo/_config/utils.py b/marimo/_config/utils.py
index 4728647633..0d904e2f4a 100644
--- a/marimo/_config/utils.py
+++ b/marimo/_config/utils.py
@@ -5,6 +5,7 @@ import os
from typing import Any, Optional
from marimo import _loggers
+from marimo._utils.xdg import marimo_config_path
LOGGER = _loggers.marimo_logger()
@@ -29,16 +30,6 @@ def _check_directory_for_file(directory: str, filename: str) -> Optional[str]:
return None
-def _xdg_config_path() -> str:
- """Search XDG paths for marimo config file"""
- home_expansion = os.path.expanduser("~")
- home_directory = os.path.realpath(home_expansion)
- xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
- home_directory, ".config"
- )
- return os.path.join(xdg_config_home, "marimo", "marimo.toml")
-
-
def get_or_create_user_config_path() -> str:
"""Find path of config file, or create it
@@ -49,10 +40,11 @@ def get_or_create_user_config_path() -> str:
if current_config_path:
return current_config_path
else:
- config_path = _xdg_config_path()
- os.makedirs(os.path.dirname(config_path), exist_ok=True)
- open(config_path, "ab", buffering=0).close()
- return config_path
+ config_path = marimo_config_path()
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ # Create an empty file
+ config_path.touch()
+ return str(config_path)
def get_user_config_path() -> Optional[str]:
@@ -107,9 +99,9 @@ def get_user_config_path() -> Optional[str]:
if os.path.isfile(config_path):
return config_path
- xdg_config_path = _xdg_config_path()
- if os.path.isfile(xdg_config_path):
- return xdg_config_path
+ xdg_config_path = marimo_config_path()
+ if xdg_config_path.is_file():
+ return str(xdg_config_path)
return None
diff --git a/marimo/_loggers.py b/marimo/_loggers.py
index 9175c0590b..8a958afbb1 100644
--- a/marimo/_loggers.py
+++ b/marimo/_loggers.py
@@ -4,13 +4,13 @@ from __future__ import annotations
import logging
from contextlib import contextmanager
from logging.handlers import TimedRotatingFileHandler
-from pathlib import Path
from typing import TYPE_CHECKING, Optional
from marimo._utils.log_formatter import LogFormatter
if TYPE_CHECKING:
from collections.abc import Generator
+ from pathlib import Path
# This file manages and creates loggers used throughout marimo.
#
@@ -145,12 +145,9 @@ def marimo_logger() -> logging.Logger:
def get_log_directory() -> Path:
- import os
+ from marimo._utils.xdg import marimo_log_dir
- xdg_cache_home = os.getenv("XDG_CACHE_HOME", None)
- if xdg_cache_home is None:
- return Path.home() / ".cache" / "marimo" / "logs"
- return Path(xdg_cache_home) / "marimo" / "logs"
+ return marimo_log_dir()
def make_log_directory() -> None:
diff --git a/marimo/_server/recents.py b/marimo/_server/recents.py
index b4947a5c56..3fe7825d88 100644
--- a/marimo/_server/recents.py
+++ b/marimo/_server/recents.py
@@ -36,9 +36,6 @@ class RecentFilesManager:
self.config = ConfigReader.for_filename(self.LOCATION)
def touch(self, filename: str) -> None:
- if not self.config:
- return
-
if _is_tmp_file(filename):
return
diff --git a/marimo/_tracer.py b/marimo/_tracer.py
index 19b3e2c1f8..ae8e06a635 100644
--- a/marimo/_tracer.py
+++ b/marimo/_tracer.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import os
from contextlib import contextmanager
-from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from marimo import _loggers
@@ -16,6 +15,7 @@ LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
from collections.abc import Sequence
+ from pathlib import Path
from opentelemetry import trace
@@ -104,8 +104,8 @@ def _set_tracer_provider() -> None:
return
class FileExporter(SpanExporter):
- def __init__(self, file_path: str) -> None:
- self.file_path = Path(file_path)
+ def __init__(self, file_path: Path) -> None:
+ self.file_path = file_path
# Clear file
self.file_path.write_bytes(b"")
@@ -125,13 +125,8 @@ def _set_tracer_provider() -> None:
# Create a directory for logs if it doesn't exist
config_ready = ConfigReader.for_filename(TRACE_FILENAME)
- if config_ready is None:
- raise FileNotFoundError(
- f"Could not local config file {TRACE_FILENAME}"
- )
-
filepath = config_ready.filepath
- os.makedirs(os.path.dirname(filepath), exist_ok=True)
+ filepath.parent.mkdir(parents=True, exist_ok=True)
# Create a file exporter
file_exporter: FileExporter = FileExporter(filepath)
diff --git a/marimo/_utils/config/config.py b/marimo/_utils/config/config.py
index 0b327a8a98..c90b04a745 100644
--- a/marimo/_utils/config/config.py
+++ b/marimo/_utils/config/config.py
@@ -1,47 +1,33 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
from dataclasses import asdict
-from pathlib import Path
-from tempfile import TemporaryDirectory
-from typing import Any, Optional, TypeVar
+from typing import TYPE_CHECKING, Any, TypeVar
from marimo._utils.parse_dataclass import parse_raw
from marimo._utils.toml import is_toml_error, read_toml
+from marimo._utils.xdg import marimo_state_dir
+if TYPE_CHECKING:
+ from pathlib import Path
-def xdg_state_marimo_dir() -> Path:
- if os.name == "posix":
- # for Linux/macOS/Unix
- _user_home = Path.home()
- _state_home = os.environ.get(
- "XDG_STATE_HOME", _user_home / ".local/state"
- )
- return Path(_state_home).relative_to(_user_home) / "marimo"
- else:
- return Path(".marimo")
-
-
-ROOT_DIR = xdg_state_marimo_dir()
+ROOT_DIR = marimo_state_dir()
T = TypeVar("T")
class ConfigReader:
- """Read the configuration file."""
+ """Read the configuration file.
- def __init__(self, filepath: str) -> None:
+ Read/writes state to $XDG_STATE_HOME/marimo or ~/.local/state/marimo
+ """
+
+ def __init__(self, filepath: Path) -> None:
self.filepath = filepath
@staticmethod
- def for_filename(filename: str) -> Optional[ConfigReader]:
- home_expansion = ConfigReader._get_home_directory()
- if home_expansion == "~":
- # path expansion failed
- return None
- home_directory = os.path.realpath(home_expansion)
- filepath = os.path.join(home_directory, ROOT_DIR, filename)
+ def for_filename(filename: str) -> ConfigReader:
+ filepath = ROOT_DIR / filename
return ConfigReader(filepath)
def read_toml(self, cls: type[T], *, fallback: T) -> T:
@@ -56,31 +42,10 @@ class ConfigReader:
def write_toml(self, data: Any) -> None:
import tomlkit
- _maybe_create_directory(self.filepath)
+ self.filepath.parent.mkdir(parents=True, exist_ok=True)
dict_data = asdict(data)
# None values is not valid toml, so we remove them
dict_data = {k: v for k, v in dict_data.items() if v is not None}
- with open(self.filepath, "w", encoding="utf-8") as file:
- tomlkit.dump(dict_data, file)
-
- @staticmethod
- def _get_home_directory() -> str:
- # If in pytest, we want to set a temporary directory
- if os.environ.get("PYTEST_CURRENT_TEST"):
- # If the home directory is given by test, take it
- home_dir = os.environ.get("MARIMO_PYTEST_HOME_DIR")
- if home_dir is not None:
- return home_dir
- else:
- tmpdir = TemporaryDirectory()
- return tmpdir.name
- else:
- return os.path.expanduser("~")
-
-
-def _maybe_create_directory(file_path: str) -> None:
- marimo_directory = os.path.dirname(file_path)
- if not os.path.exists(marimo_directory):
- os.makedirs(marimo_directory)
+ self.filepath.write_text(tomlkit.dumps(dict_data))
diff --git a/marimo/_utils/xdg.py b/marimo/_utils/xdg.py
new file mode 100644
index 0000000000..af58c18408
--- /dev/null
+++ b/marimo/_utils/xdg.py
@@ -0,0 +1,93 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+
+def home_path() -> Path:
+ """Get home directory or temp directory if home directory is not available.
+
+ Returns:
+ Path: The home directory.
+ """
+ try:
+ return Path.home().resolve()
+ except RuntimeError:
+ # Can't get home directory, so use temp directory
+ return Path("/tmp")
+
+
+def xdg_config_home() -> Path:
+ """Get XDG config home directory.
+
+ Returns $XDG_CONFIG_HOME if set and non-empty, otherwise ~/.config
+ """
+ xdg_config_home_env = os.getenv("XDG_CONFIG_HOME")
+ if xdg_config_home_env and xdg_config_home_env.strip():
+ return Path(xdg_config_home_env)
+ return home_path() / ".config"
+
+
+def xdg_cache_home() -> Path:
+ """Get XDG cache home directory.
+
+ Returns $XDG_CACHE_HOME if set and non-empty, otherwise ~/.cache
+ """
+ xdg_cache_home_env = os.getenv("XDG_CACHE_HOME")
+ if xdg_cache_home_env and xdg_cache_home_env.strip():
+ return Path(xdg_cache_home_env)
+ return home_path() / ".cache"
+
+
+def xdg_state_home() -> Path:
+ """Get XDG state home directory.
+
+ Returns $XDG_STATE_HOME if set and non-empty, otherwise ~/.local/state
+ """
+ if os.name == "posix":
+ xdg_state_home_env = os.getenv("XDG_STATE_HOME")
+ if xdg_state_home_env and xdg_state_home_env.strip():
+ return Path(xdg_state_home_env)
+ return home_path() / ".local" / "state"
+ else:
+ return home_path()
+
+
+def marimo_config_path() -> Path:
+ """Get marimo config file path using XDG specification.
+
+ $XDG_CONFIG_HOME/marimo/marimo.toml if set, otherwise ~/.config/marimo/marimo.toml
+ """
+ return xdg_config_home() / "marimo" / "marimo.toml"
+
+
+def marimo_cache_dir() -> Path:
+ """Get marimo cache directory using XDG specification.
+
+ $XDG_CACHE_HOME/marimo if set, otherwise ~/.cache/marimo
+ """
+ return xdg_cache_home() / "marimo"
+
+
+def marimo_state_dir() -> Path:
+ """Get marimo state directory using XDG specification.
+
+ On Linux/macOS/Unix, returns:
+ $XDG_STATE_HOME/marimo if set, otherwise ~/.local/state/marimo
+
+ On Windows, returns:
+ ~/.marimo
+ """
+ if os.name == "posix":
+ return xdg_state_home() / "marimo"
+ else:
+ return home_path() / ".marimo"
+
+
+def marimo_log_dir() -> Path:
+ """Get marimo log directory using XDG specification.
+
+ $XDG_CACHE_HOME/marimo/logs if set, otherwise ~/.cache/marimo/logs
+ """
+ return marimo_cache_dir() / "logs"
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index 45bed9a7c5..6093d3d90a 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -27,7 +27,6 @@ from marimo._ast import codegen
from marimo._ast.cell import CellConfig
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.templates.templates import get_version
-from marimo._utils.config.config import ROOT_DIR as CONFIG_ROOT_DIR
from marimo._utils.platform import is_windows
from marimo._utils.toml import read_toml
from tests.utils import try_assert_n_times
@@ -150,8 +149,8 @@ def _get_port() -> int:
raise OSError("Could not find an unused port.")
-def _read_toml(filepath: str) -> Optional[dict[str, Any]]:
- if not os.path.exists(filepath):
+def _read_toml(filepath: Path) -> Optional[dict[str, Any]]:
+ if not filepath.exists():
return None
return read_toml(filepath)
@@ -378,58 +377,52 @@ def test_cli_edit_with_additional_args(temp_marimo_file: str) -> None:
@pytest.mark.skipif(
- condition=not _can_access_pypi(),
- reason="update check won't work without access to pypi",
+ condition=not _can_access_pypi() or is_windows(),
+ reason="update check won't work without access to pypi, or on Windows",
)
-def test_cli_edit_update_check() -> None:
- with tempfile.TemporaryDirectory() as tempdir:
- port = _get_port()
- env = {**os.environ, "MARIMO_PYTEST_HOME_DIR": tempdir}
- # pop off MARIMO_SKIP_UPDATE_CHECK
- env.pop("MARIMO_SKIP_UPDATE_CHECK", None)
- p = subprocess.Popen(
- ["marimo", "edit", "-p", str(port), "--headless", "--no-token"],
- env=env,
- )
- contents = _try_fetch(port)
- _check_contents(p, b'"mode": "home"', contents)
+def test_cli_edit_update_check(tmp_path: Path) -> None:
+ port = _get_port()
+ env = {**os.environ, "XDG_STATE_HOME": str(tmp_path)}
+ # pop off MARIMO_SKIP_UPDATE_CHECK
+ env.pop("MARIMO_SKIP_UPDATE_CHECK", None)
+ p = subprocess.Popen(
+ ["marimo", "edit", "-p", str(port), "--headless", "--no-token"],
+ env=env,
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b'"mode": "home"', contents)
- state_contents = _read_toml(
- os.path.join(tempdir, CONFIG_ROOT_DIR, "state.toml")
- )
- assert state_contents is not None
- assert state_contents.get("last_checked_at") is not None
+ state_contents = _read_toml(tmp_path / "marimo" / "state.toml")
+ assert state_contents is not None
+ assert state_contents.get("last_checked_at") is not None
@pytest.mark.skipif(
condition=not _can_access_pypi(),
reason="update check skip is only detectable if pypi is accessible",
)
-def test_cli_edit_skip_update_check() -> None:
- with tempfile.TemporaryDirectory() as tempdir:
- port = _get_port()
- p = subprocess.Popen(
- [
- "marimo",
- "edit",
- "-p",
- str(port),
- "--headless",
- "--no-token",
- "--skip-update-check",
- ],
- env={**os.environ, "MARIMO_PYTEST_HOME_DIR": tempdir},
- )
- contents = _try_fetch(port)
- _check_contents(p, b'"mode": "home"', contents)
+def test_cli_edit_skip_update_check(tmp_path: Path) -> None:
+ port = _get_port()
+ env = {**os.environ, "XDG_STATE_HOME": str(tmp_path)}
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ "--skip-update-check",
+ ],
+ env=env,
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b'"mode": "home"', contents)
- state_contents = _read_toml(
- os.path.join(tempdir, CONFIG_ROOT_DIR, "state.toml")
- )
- assert (
- state_contents is None
- or state_contents.get("last_checked_at") is None
- )
+ state_contents = _read_toml(tmp_path / "marimo" / "state.toml")
+ assert (
+ state_contents is None or state_contents.get("last_checked_at") is None
+ )
def test_cli_new() -> None:
diff --git a/tests/_cli/test_upgrade.py b/tests/_cli/test_upgrade.py
index 3db246f404..bca9ac64cb 100644
--- a/tests/_cli/test_upgrade.py
+++ b/tests/_cli/test_upgrade.py
@@ -5,7 +5,7 @@ import json
import urllib.error
from datetime import datetime
from typing import Any
-from unittest.mock import mock_open, patch
+from unittest.mock import MagicMock, patch
from marimo._cli.upgrade import (
_update_with_latest_version,
@@ -16,34 +16,20 @@ from marimo._config.cli_state import MarimoCLIState
@patch("marimo._cli.upgrade.current_version", "0.1.0")
-@patch("marimo._utils.config.config.os.path.exists")
-@patch("marimo._utils.config.config.os.makedirs")
-@patch(
- "__main__.open",
- new_callable=mock_open,
-)
@patch("marimo._cli.upgrade._update_with_latest_version")
@patch("marimo._cli.upgrade.echo")
def test_check_for_updates(
mock_echo: Any,
mock_update_with_latest_version: Any,
- mock_open_file: Any,
- mock_makedirs: Any,
- mock_path_exists: Any,
) -> None:
# Mocks
mock_update_with_latest_version.return_value = MarimoCLIState(
latest_version="0.1.2", last_checked_at="2020-01-01"
)
- mock_path_exists.return_value = True
- mock_open_file.side_effect = FileNotFoundError()
# Call the function to test
check_for_updates(print_latest_version)
- # Assert that the makedirs function was not called
- mock_makedirs.assert_not_called()
-
mock_echo.assert_called()
# Assert prints
@@ -113,25 +99,23 @@ def test_update_with_within_the_same_day(
@patch("marimo._cli.upgrade.current_version", "0.1.0")
@patch("marimo._cli.upgrade._fetch_data_from_url")
def test_version_comparison_edge_cases(mock_fetch_data_from_url: Any) -> None:
+ mock_print_latest_version = MagicMock()
# Test same version
mock_fetch_data_from_url.return_value = {"info": {"version": "0.1.0"}}
- with patch("marimo._cli.upgrade.echo") as mock_echo:
- check_for_updates(print_latest_version)
- mock_echo.assert_not_called()
+ check_for_updates(mock_print_latest_version)
+ mock_print_latest_version.assert_not_called()
# Test pre-release version
mock_fetch_data_from_url.return_value = {
"info": {"version": "0.2.0-alpha.1"}
}
- with patch("marimo._cli.upgrade.echo") as mock_echo:
- check_for_updates(print_latest_version)
- mock_echo.assert_called()
+ check_for_updates(mock_print_latest_version)
+ mock_print_latest_version.assert_not_called()
# Test lower version (shouldn't happen in practice)
mock_fetch_data_from_url.return_value = {"info": {"version": "0.0.9"}}
- with patch("marimo._cli.upgrade.echo") as mock_echo:
- check_for_updates(print_latest_version)
- mock_echo.assert_not_called()
+ check_for_updates(mock_print_latest_version)
+ mock_print_latest_version.assert_not_called()
@patch("marimo._cli.upgrade._fetch_data_from_url")
diff --git a/tests/_config/test_config_utils.py b/tests/_config/test_config_utils.py
index db5f79ce64..28db64ca8a 100644
--- a/tests/_config/test_config_utils.py
+++ b/tests/_config/test_config_utils.py
@@ -33,9 +33,15 @@ def _mock_file_exists(
return False
return isfile(check_path)
- with mock.patch(
- "marimo._config.utils.os.path.isfile",
- side_effect=mock_exists,
+ def mock_path_is_file(self: Path) -> bool:
+ return mock_exists(str(self))
+
+ with (
+ mock.patch(
+ "marimo._config.utils.os.path.isfile",
+ side_effect=mock_exists,
+ ),
+ mock.patch.object(Path, "is_file", mock_path_is_file),
):
yield
diff --git a/tests/_utils/config/test_config_reader.py b/tests/_utils/config/test_config_reader.py
index 0f014db6af..97b68d8274 100644
--- a/tests/_utils/config/test_config_reader.py
+++ b/tests/_utils/config/test_config_reader.py
@@ -1,13 +1,14 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
from dataclasses import dataclass
-from tempfile import NamedTemporaryFile
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from marimo._utils.config.config import ConfigReader
+if TYPE_CHECKING:
+ from pathlib import Path
+
@dataclass
class TestConfig:
@@ -16,54 +17,39 @@ class TestConfig:
nullable_value: Optional[str] = None
-def test_read_toml_invalid_syntax() -> None:
- with NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
- # Write invalid TOML content (missing value after comma)
- f.write("key = 'value',")
- f.flush()
-
- reader = ConfigReader(f.name)
- fallback = TestConfig(value="fallback")
- result = reader.read_toml(TestConfig, fallback=fallback)
- assert result == fallback
-
- os.unlink(f.name)
-
-
-def test_read_toml_valid() -> None:
- with NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
- f.write('value = "test"')
- f.flush()
+def test_read_toml_invalid_syntax(tmp_path: Path) -> None:
+ (tmp_path / "invalid.toml").write_text("key = 'value',")
- reader = ConfigReader(f.name)
- fallback = TestConfig(value="fallback")
- result = reader.read_toml(TestConfig, fallback=fallback)
- assert result == TestConfig(value="test")
+ reader = ConfigReader(tmp_path / "invalid.toml")
+ fallback = TestConfig(value="fallback")
+ result = reader.read_toml(TestConfig, fallback=fallback)
+ assert result == fallback
- os.unlink(f.name)
+def test_read_toml_valid(tmp_path: Path) -> None:
+ (tmp_path / "valid.toml").write_text('value = "test"')
-def test_write_toml_valid() -> None:
- with NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
- config = ConfigReader(f.name)
- written = TestConfig(value="test", nullable_value="value")
- config.write_toml(written)
+ reader = ConfigReader(tmp_path / "valid.toml")
+ fallback = TestConfig(value="fallback")
+ result = reader.read_toml(TestConfig, fallback=fallback)
+ assert result == TestConfig(value="test")
- fallback = TestConfig(value="fallback")
- result = config.read_toml(TestConfig, fallback=fallback)
- assert result == written
- os.unlink(f.name)
+def test_write_toml_valid(tmp_path: Path) -> None:
+ config = ConfigReader(tmp_path / "valid.toml")
+ written = TestConfig(value="test", nullable_value="value")
+ config.write_toml(written)
+ fallback = TestConfig(value="fallback")
+ result = config.read_toml(TestConfig, fallback=fallback)
+ assert result == written
-def test_write_toml_invalid_values() -> None:
- with NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
- config = ConfigReader(f.name)
- # None is not valid toml
- config.write_toml(TestConfig(value="test", nullable_value=None))
- fallback = TestConfig(value="fallback")
- result = config.read_toml(TestConfig, fallback=fallback)
- assert result == TestConfig(value="test")
+def test_write_toml_invalid_values(tmp_path: Path) -> None:
+ config = ConfigReader(tmp_path / "invalid.toml")
+ # None is not valid toml
+ config.write_toml(TestConfig(value="test", nullable_value=None))
- os.unlink(f.name)
+ fallback = TestConfig(value="fallback")
+ result = config.read_toml(TestConfig, fallback=fallback)
+ assert result == TestConfig(value="test")
diff --git a/tests/_utils/test_xdg.py b/tests/_utils/test_xdg.py
new file mode 100644
index 0000000000..217512467e
--- /dev/null
+++ b/tests/_utils/test_xdg.py
@@ -0,0 +1,287 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+import tempfile
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from marimo._utils.platform import is_windows
+from marimo._utils.xdg import (
+ home_path,
+ marimo_cache_dir,
+ marimo_config_path,
+ marimo_log_dir,
+ marimo_state_dir,
+ xdg_cache_home,
+ xdg_config_home,
+ xdg_state_home,
+)
+
+
+class TestHomePathFunction:
+ """Test home_path function behavior."""
+
+ @patch("pathlib.Path.home")
+ def test_home_path_normal(self, mock_home) -> None:
+ """Test home_path returns home directory when available."""
+ expected_home = Path("/home/user")
+ mock_home.return_value = expected_home
+ result = home_path()
+ assert result == expected_home.resolve()
+
+ @patch("pathlib.Path.home")
+ def test_home_path_runtime_error_fallback(self, mock_home) -> None:
+ """Test home_path falls back to /tmp on RuntimeError."""
+ mock_home.side_effect = RuntimeError("Unable to get home directory")
+ result = home_path()
+ assert result == Path("/tmp")
+
+
+class TestXDGBasicFunctions:
+ """Test basic XDG directory functions."""
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_xdg_config_home_default(self, mock_home_path) -> None:
+ """Test default XDG config home returns ~/.config."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_config_home()
+ assert result == Path("/home/user/.config")
+
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": "/custom/config"})
+ def test_xdg_config_home_env_set(self) -> None:
+ """Test XDG config home respects XDG_CONFIG_HOME environment variable."""
+ result = xdg_config_home()
+ assert result == Path("/custom/config")
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_xdg_cache_home_default(self, mock_home_path) -> None:
+ """Test default XDG cache home returns ~/.cache."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_cache_home()
+ assert result == Path("/home/user/.cache")
+
+ @patch.dict(os.environ, {"XDG_CACHE_HOME": "/custom/cache"})
+ def test_xdg_cache_home_env_set(self) -> None:
+ """Test XDG cache home respects XDG_CACHE_HOME environment variable."""
+ result = xdg_cache_home()
+ assert result == Path("/custom/cache")
+
+ @pytest.mark.skipif(is_windows(), reason="POSIX-specific test")
+ @patch("os.name", "posix")
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_xdg_state_home_posix_default(self, mock_home_path) -> None:
+ """Test default XDG state home on POSIX systems."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_state_home()
+ assert result == Path("/home/user/.local/state")
+
+ @pytest.mark.skipif(is_windows(), reason="POSIX-specific test")
+ @patch("os.name", "posix")
+ @patch.dict(os.environ, {"XDG_STATE_HOME": "/custom/state"})
+ def test_xdg_state_home_posix_env_set(self) -> None:
+ """Test XDG state home on POSIX respects XDG_STATE_HOME environment variable."""
+ result = xdg_state_home()
+ assert result == Path("/custom/state")
+
+ @pytest.mark.skipif(not is_windows(), reason="Windows-specific test")
+ def test_xdg_state_home_non_posix(self) -> None:
+ """Test XDG state home on non-POSIX systems returns home directory."""
+ with patch("marimo._utils.xdg.home_path") as mock_home_path:
+ mock_home_path.return_value = Path.home()
+ result = xdg_state_home()
+ # On Windows, should return home directory directly
+ assert result == Path.home()
+
+
+class TestMarimoSpecificFunctions:
+ """Test marimo-specific XDG functions."""
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_marimo_config_path_default(self, mock_home_path) -> None:
+ """Test marimo config path with default XDG config home."""
+ mock_home_path.return_value = Path("/home/user")
+ result = marimo_config_path()
+ assert result == Path("/home/user/.config/marimo/marimo.toml")
+
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": "/custom/config"})
+ def test_marimo_config_path_custom_xdg(self) -> None:
+ """Test marimo config path with custom XDG_CONFIG_HOME."""
+ result = marimo_config_path()
+ assert result == Path("/custom/config/marimo/marimo.toml")
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_marimo_cache_dir_default(self, mock_home_path) -> None:
+ """Test marimo cache directory with default XDG cache home."""
+ mock_home_path.return_value = Path("/home/user")
+ result = marimo_cache_dir()
+ assert result == Path("/home/user/.cache/marimo")
+
+ @patch.dict(os.environ, {"XDG_CACHE_HOME": "/custom/cache"})
+ def test_marimo_cache_dir_custom_xdg(self) -> None:
+ """Test marimo cache directory with custom XDG_CACHE_HOME."""
+ result = marimo_cache_dir()
+ assert result == Path("/custom/cache/marimo")
+
+ @pytest.mark.skipif(is_windows(), reason="POSIX-specific test")
+ @patch("os.name", "posix")
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_marimo_state_dir_posix_default(self, mock_home_path) -> None:
+ """Test marimo state directory on POSIX with default XDG state home."""
+ mock_home_path.return_value = Path("/home/user")
+ result = marimo_state_dir()
+ assert result == Path("/home/user/.local/state/marimo")
+
+ @pytest.mark.skipif(is_windows(), reason="POSIX-specific test")
+ @patch("os.name", "posix")
+ @patch.dict(os.environ, {"XDG_STATE_HOME": "/custom/state"})
+ def test_marimo_state_dir_posix_custom_xdg(self) -> None:
+ """Test marimo state directory on POSIX with custom XDG_STATE_HOME."""
+ result = marimo_state_dir()
+ assert result == Path("/custom/state/marimo")
+
+ @pytest.mark.skipif(not is_windows(), reason="Windows-specific test")
+ def test_marimo_state_dir_non_posix(self) -> None:
+ """Test marimo state directory on non-POSIX systems."""
+ with patch("marimo._utils.xdg.home_path") as mock_home_path:
+ mock_home_path.return_value = Path.home()
+ result = marimo_state_dir()
+ # On Windows, should return home/.marimo
+ assert result == Path.home() / ".marimo"
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {}, clear=True)
+ def test_marimo_log_dir_default(self, mock_home_path) -> None:
+ """Test marimo log directory with default XDG cache home."""
+ mock_home_path.return_value = Path("/home/user")
+ result = marimo_log_dir()
+ assert result == Path("/home/user/.cache/marimo/logs")
+
+ @patch.dict(os.environ, {"XDG_CACHE_HOME": "/custom/cache"})
+ def test_marimo_log_dir_custom_xdg(self) -> None:
+ """Test marimo log directory with custom XDG_CACHE_HOME."""
+ result = marimo_log_dir()
+ assert result == Path("/custom/cache/marimo/logs")
+
+
+class TestEnvironmentVariableHandling:
+ """Test environment variable handling edge cases."""
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": ""})
+ def test_empty_xdg_config_home(self, mock_home_path) -> None:
+ """Test behavior with empty XDG_CONFIG_HOME."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_config_home()
+ assert result == Path("/home/user/.config")
+
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {"XDG_CACHE_HOME": ""})
+ def test_empty_xdg_cache_home(self, mock_home_path) -> None:
+ """Test behavior with empty XDG_CACHE_HOME."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_cache_home()
+ assert result == Path("/home/user/.cache")
+
+ @pytest.mark.skipif(is_windows(), reason="POSIX-specific test")
+ @patch("os.name", "posix")
+ @patch("marimo._utils.xdg.home_path")
+ @patch.dict(os.environ, {"XDG_STATE_HOME": ""})
+ def test_empty_xdg_state_home_posix(self, mock_home_path) -> None:
+ """Test behavior with empty XDG_STATE_HOME on POSIX."""
+ mock_home_path.return_value = Path("/home/user")
+ result = xdg_state_home()
+ assert result == Path("/home/user/.local/state")
+
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": "relative/path"})
+ def test_relative_paths_in_env_vars(self) -> None:
+ """Test behavior with relative paths in environment variables."""
+ result = xdg_config_home()
+ assert result == Path("relative/path")
+
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": " /path/with/spaces "})
+ def test_whitespace_in_env_vars(self) -> None:
+ """Test behavior with whitespace in environment variables."""
+ result = xdg_config_home()
+ assert result == Path(" /path/with/spaces ")
+
+
+class TestIntegration:
+ """Integration tests using temporary directories."""
+
+ def test_with_temp_directories(self) -> None:
+ """Test XDG functions work with real temporary directories."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ temp_path = Path(temp_dir)
+ config_dir = temp_path / "config"
+ cache_dir = temp_path / "cache"
+ state_dir = temp_path / "state"
+
+ # Create directories
+ config_dir.mkdir()
+ cache_dir.mkdir()
+ state_dir.mkdir()
+
+ with patch.dict(
+ os.environ,
+ {
+ "XDG_CONFIG_HOME": str(config_dir),
+ "XDG_CACHE_HOME": str(cache_dir),
+ "XDG_STATE_HOME": str(state_dir),
+ },
+ ):
+ # Test basic functions
+ assert xdg_config_home() == config_dir
+ assert xdg_cache_home() == cache_dir
+
+ if not is_windows():
+ with patch("os.name", "posix"):
+ assert xdg_state_home() == state_dir
+
+ # Test marimo functions
+ assert (
+ marimo_config_path()
+ == config_dir / "marimo" / "marimo.toml"
+ )
+ assert marimo_cache_dir() == cache_dir / "marimo"
+ assert marimo_log_dir() == cache_dir / "marimo" / "logs"
+
+ if not is_windows():
+ with patch("os.name", "posix"):
+ assert marimo_state_dir() == state_dir / "marimo"
+
+ @patch.dict(os.environ, {"XDG_CONFIG_HOME": "/test/config"})
+ def test_path_composition(self) -> None:
+ """Test that Path objects compose correctly."""
+ config_path = marimo_config_path()
+
+ # Test that we can use Path methods
+ assert config_path.parent == Path("/test/config/marimo")
+ assert config_path.name == "marimo.toml"
+ assert config_path.suffix == ".toml"
+
+ # Test that we can compose new paths
+ backup_path = config_path.with_suffix(".toml.bak")
+ assert backup_path == Path("/test/config/marimo/marimo.toml.bak")
+
+ @patch.dict(os.environ, {})
+ def test_return_types(self) -> None:
+ """Test that all functions return the correct types."""
+ # Basic XDG functions should return Path objects
+ assert isinstance(xdg_config_home(), Path)
+ assert isinstance(xdg_cache_home(), Path)
+ assert isinstance(xdg_state_home(), Path)
+
+ # Marimo functions should return Path objects
+ assert isinstance(marimo_config_path(), Path)
+ assert isinstance(marimo_cache_dir(), Path)
+ assert isinstance(marimo_state_dir(), Path)
+ assert isinstance(marimo_log_dir(), Path)