From df22becd95a551b078db0c6b070ea3d40896560c Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 12:18:24 -0400 Subject: [PATCH 1/7] fix(Unix.user_runtime_dir): nonexistent runtime dir This fixes cases where XDG_RUNTIME_DIR is unset and the default runtime dir does not exist by getting a directory using Python's built-in tempfile. Fixes #368 --- pyproject.toml | 1 + src/platformdirs/unix.py | 19 ++++++++++++------- tests/test_unix.py | 37 ++++++++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 10 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 80b93ff..d8ae722 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,6 +53,7 @@ optional-dependencies.docs = [ optional-dependencies.test = [ "appdirs==1.4.4", "covdefaults>=2.3", + "pyfakefs>=5.9.2", "pytest>=8.3.4", "pytest-cov>=6", "pytest-mock>=3.14", diff --git a/src/platformdirs/unix.py b/src/platformdirs/unix.py index fc75d8d..53726a9 100644 --- a/src/platformdirs/unix.py +++ b/src/platformdirs/unix.py @@ -6,6 +6,7 @@ import sys from configparser import ConfigParser from pathlib import Path +from tempfile import gettempdir from typing import TYPE_CHECKING, NoReturn from .api import PlatformDirsABC @@ -175,13 +176,17 @@ def user_runtime_dir(self) -> str: is not set. """ path = os.environ.get("XDG_RUNTIME_DIR", "") - if not path.strip(): - if sys.platform.startswith(("freebsd", "openbsd", "netbsd")): - path = f"/var/run/user/{getuid()}" - if not Path(path).exists(): - path = f"/tmp/runtime-{getuid()}" # noqa: S108 - else: - path = f"/run/user/{getuid()}" + if path.strip(): + return self._append_app_name_and_version(path) + + if sys.platform.startswith(("freebsd", "openbsd", "netbsd")): + path = f"/var/run/user/{getuid()}" + else: + path = f"/run/user/{getuid()}" + + if not os.access(path, os.W_OK): + path = f"{gettempdir()}/runtime-{getuid()}" + return self._append_app_name_and_version(path) @property diff --git a/tests/test_unix.py b/tests/test_unix.py index 326f8d7..e1b89db 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -4,6 +4,7 @@ import os import sys import typing +from tempfile import gettempdir import pytest @@ -13,6 +14,7 @@ if typing.TYPE_CHECKING: from pathlib import Path + from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture @@ -97,7 +99,7 @@ def _func_to_path(func: str) -> XDGVariable | None: "user_cache_dir": XDGVariable("XDG_CACHE_HOME", "~/.cache"), "user_state_dir": XDGVariable("XDG_STATE_HOME", "~/.local/state"), "user_log_dir": XDGVariable("XDG_STATE_HOME", "~/.local/state"), - "user_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/run/user/1234"), + "user_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/tmp/runtime-1234"), # noqa: S108 "site_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/run"), } return mapping.get(func) @@ -154,10 +156,10 @@ def test_platform_on_bsd(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, assert Unix().site_runtime_dir == "/var/run" - mocker.patch("pathlib.Path.exists", return_value=True) + mocker.patch("os.access", return_value=True) assert Unix().user_runtime_dir == "/var/run/user/1234" - mocker.patch("pathlib.Path.exists", return_value=False) + mocker.patch("os.access", return_value=False) assert Unix().user_runtime_dir == "/tmp/runtime-1234" # noqa: S108 @@ -173,6 +175,35 @@ def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixtur sys.modules["platformdirs.unix"] = prev_unix +@pytest.mark.usefixtures("_getuid") +@pytest.mark.parametrize( + ("platform", "default_dir"), + [ + ("freebsd", "/var/run/user/1234"), + ("linux", "/run/user/1234"), + ], +) +def test_xdg_runtime_dir_unset( + monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, fs: FakeFilesystem, platform: str, default_dir: str +) -> None: + monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False) + mocker.patch("sys.platform", platform) + + fs.create_dir(default_dir) + + assert Unix().user_runtime_dir.startswith(default_dir) + + # If the default directory isn't writable, we shouldn't use it. + fs.chmod(default_dir, 0o000) + assert not Unix().user_runtime_dir.startswith(default_dir) + assert Unix().user_runtime_dir.startswith(gettempdir()) + + # If the runtime directory doesn't exist, we shouldn't use it. + fs.rmdir(default_dir) + assert not Unix().user_runtime_dir.startswith(default_dir) + assert Unix().user_runtime_dir.startswith(gettempdir()) + + def test_ensure_exists_creates_folder(mocker: MockerFixture, tmp_path: Path) -> None: mocker.patch.dict(os.environ, {"XDG_DATA_HOME": str(tmp_path)}) data_path = Unix(appname="acme", ensure_exists=True).user_data_path From 28d5d80c3e19cd4c0be9e149fc83412618c99305 Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 12:22:06 -0400 Subject: [PATCH 2/7] fix: docstring --- src/platformdirs/unix.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/platformdirs/unix.py b/src/platformdirs/unix.py index 53726a9..260f15f 100644 --- a/src/platformdirs/unix.py +++ b/src/platformdirs/unix.py @@ -168,12 +168,11 @@ def user_desktop_dir(self) -> str: @property def user_runtime_dir(self) -> str: """ - :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or - ``$XDG_RUNTIME_DIR/$appname/$version``. + :return: runtime directory tied to the user, e.g. ``$XDG_RUNTIME_DIR/$appname/$version``. - For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if - exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR`` - is not set. + If ``$XDG_RUNTIME_DIR`` is unset, it tries the platform default location of that runtime directory + (``/var/run/user/$(id -u)`` on FreeBSD/OpenBSD/NetBSD, ``/run/user/$(id -u)`` otherwise). + If the default location is not writable, it uses a temporary directory instead. """ path = os.environ.get("XDG_RUNTIME_DIR", "") if path.strip(): From c6f435a8e962488af31e9e7ed9cfe6fc7386c437 Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 12:34:20 -0400 Subject: [PATCH 3/7] fix: ci on windows/mac --- tests/test_unix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_unix.py b/tests/test_unix.py index e1b89db..d185f3a 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -99,7 +99,7 @@ def _func_to_path(func: str) -> XDGVariable | None: "user_cache_dir": XDGVariable("XDG_CACHE_HOME", "~/.cache"), "user_state_dir": XDGVariable("XDG_STATE_HOME", "~/.local/state"), "user_log_dir": XDGVariable("XDG_STATE_HOME", "~/.local/state"), - "user_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/tmp/runtime-1234"), # noqa: S108 + "user_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", f"{gettempdir()}/runtime-1234"), "site_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/run"), } return mapping.get(func) @@ -160,7 +160,7 @@ def test_platform_on_bsd(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, assert Unix().user_runtime_dir == "/var/run/user/1234" mocker.patch("os.access", return_value=False) - assert Unix().user_runtime_dir == "/tmp/runtime-1234" # noqa: S108 + assert Unix().user_runtime_dir == f"{gettempdir()}/runtime-1234" def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None: From 569d313e13b51fa3a86e50bb00841abbcbcbe03e Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 12:57:02 -0400 Subject: [PATCH 4/7] fix: reload after tests that modify behaviour --- tests/test_unix.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_unix.py b/tests/test_unix.py index d185f3a..dc93888 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -18,6 +18,14 @@ from pytest_mock import MockerFixture +@pytest.fixture +def _reload_after_test() -> typing.Iterator[None]: + global Unix # noqa: PLW0603 - we need to rewrite this full import. + yield + importlib.reload(unix) + Unix = unix.Unix + + @pytest.mark.parametrize( "prop", [ @@ -175,7 +183,7 @@ def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixtur sys.modules["platformdirs.unix"] = prev_unix -@pytest.mark.usefixtures("_getuid") +@pytest.mark.usefixtures("_getuid", "_reload_after_test") @pytest.mark.parametrize( ("platform", "default_dir"), [ From 52eaeac6e10ec7286c1a8379f83a06397048c6f1 Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 13:07:28 -0400 Subject: [PATCH 5/7] fix: ignore unix runtimedir on Windows --- tests/test_unix.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/tests/test_unix.py b/tests/test_unix.py index dc93888..a5bb09c 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -18,14 +18,6 @@ from pytest_mock import MockerFixture -@pytest.fixture -def _reload_after_test() -> typing.Iterator[None]: - global Unix # noqa: PLW0603 - we need to rewrite this full import. - yield - importlib.reload(unix) - Unix = unix.Unix - - @pytest.mark.parametrize( "prop", [ @@ -168,7 +160,7 @@ def test_platform_on_bsd(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, assert Unix().user_runtime_dir == "/var/run/user/1234" mocker.patch("os.access", return_value=False) - assert Unix().user_runtime_dir == f"{gettempdir()}/runtime-1234" + assert Unix().user_runtime_dir == "/tmp/runtime-1234" # noqa: S108 def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None: @@ -183,7 +175,11 @@ def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixtur sys.modules["platformdirs.unix"] = prev_unix -@pytest.mark.usefixtures("_getuid", "_reload_after_test") +@pytest.mark.skipif( + sys.platform == "win32", + reason="Running on Windows would require multiple reloads and make this test excessively complex.", +) +@pytest.mark.usefixtures("_getuid") @pytest.mark.parametrize( ("platform", "default_dir"), [ From 52cbd55fb58ff982d9089501ae2a0f9233904d14 Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 13:11:31 -0400 Subject: [PATCH 6/7] fix: tempdir on bsd MacOS runners use a different default tempdir --- tests/test_unix.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_unix.py b/tests/test_unix.py index a5bb09c..46911e8 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -153,6 +153,7 @@ def test_xdg_variable_custom_value(monkeypatch: pytest.MonkeyPatch, dirs_instanc def test_platform_on_bsd(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, platform: str) -> None: monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False) mocker.patch("sys.platform", platform) + mocker.patch("tempfile.tempdir", "/tmp") # noqa: S108 assert Unix().site_runtime_dir == "/var/run" From 0a3999df5e0732af2f6dbd3b877e0d94ac7fab8d Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 22 Aug 2025 13:32:08 -0400 Subject: [PATCH 7/7] ? --- tests/test_unix.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/test_unix.py b/tests/test_unix.py index 46911e8..794d782 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -18,6 +18,12 @@ from pytest_mock import MockerFixture +@pytest.fixture(autouse=True) +def _reload_after_test() -> typing.Iterator[None]: + yield + importlib.reload(unix) + + @pytest.mark.parametrize( "prop", [ @@ -176,10 +182,6 @@ def test_platform_on_win32(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixtur sys.modules["platformdirs.unix"] = prev_unix -@pytest.mark.skipif( - sys.platform == "win32", - reason="Running on Windows would require multiple reloads and make this test excessively complex.", -) @pytest.mark.usefixtures("_getuid") @pytest.mark.parametrize( ("platform", "default_dir"),