Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog/+isolation-worker-processes.doc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Document how to isolate directories inside spawned worker processes.
31 changes: 31 additions & 0 deletions docs/howto.rst
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,37 @@ root until the child exits. A spawned child starts with the original paths. With
inherits the server's state. Isolation applies to :data:`~platformdirs.PlatformDirs`. Other platform classes, such as
:class:`~platformdirs.unix.Unix` on macOS, keep their original paths.

To isolate a spawned worker, enter ``isolated_dirs`` inside the worker. Define the worker at module level and guard
process creation with ``if __name__ == "__main__"``, so the child can import the worker without starting another pool:

.. code-block:: python

from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
from pathlib import Path
from tempfile import TemporaryDirectory

from platformdirs import PlatformDirs
from platformdirs.testing import isolated_dirs


def write_config(root: Path) -> Path:
with isolated_dirs(root):
config = PlatformDirs("MyApp").place_config_file("settings.toml")
config.write_text('theme = "dark"', encoding="utf-8")
return config


if __name__ == "__main__":
with TemporaryDirectory() as temporary:
root = Path(temporary)
with ProcessPoolExecutor(max_workers=1, mp_context=get_context("spawn")) as pool:
config = pool.submit(write_config, root / "worker").result()
assert config == root / "worker" / "user_config" / "MyApp" / "settings.toml"

Give concurrent workers separate roots when their files must not overlap. Keep each root available until its workers
have exited, as the temporary directory above does.

Overriding directories with environment variables
=================================================

Expand Down
46 changes: 45 additions & 1 deletion tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from contextlib import ExitStack
from multiprocessing import get_context
from pathlib import Path
from subprocess import check_output # ruff:ignore[suspicious-subprocess-import] # bound the deadlock regression
from subprocess import check_output # ruff:ignore[suspicious-subprocess-import] # run checks in a fresh interpreter
from threading import Event
from types import MappingProxyType
from typing import TYPE_CHECKING, Final
Expand Down Expand Up @@ -182,6 +182,50 @@ def test_isolated_dirs_restores_after_exception(tmp_path: Path) -> None:
assert _resolve_all() == _ORIGINAL


def test_isolated_dirs_spawned_process(tmp_path: Path) -> None:
# A real script makes the worker importable under spawn, including on Windows.
script = tmp_path / "check_spawned_process.py"
code = """
from multiprocessing import get_context
from pathlib import Path
from sys import argv

import platformdirs
from platformdirs.testing import isolated_dirs


def check_child(parent_root: Path, child_root: Path) -> None:
dirs = platformdirs.PlatformDirs("app", version="1.0")
original = dirs.user_config_path
assert not original.is_relative_to(parent_root)
assert not platformdirs.user_cache_path("app").is_relative_to(parent_root)
with isolated_dirs(child_root):
assert dirs.user_config_path == child_root / "user_config/app/1.0"
assert platformdirs.user_cache_path("app") == child_root / "user_cache/app"
dirs.place_config_file("settings.toml").write_text("enabled = true", encoding="utf-8")
assert dirs.user_config_path == original


if __name__ == "__main__":
parent_root, child_root = Path(argv[1]) / "parent", Path(argv[1]) / "child"
original = platformdirs.user_config_path("app")
with isolated_dirs(parent_root):
process = get_context("spawn").Process(target=check_child, args=(parent_root, child_root))
process.start()
process.join(timeout=10)
process.kill()
process.join()
assert process.exitcode == 0, process.exitcode
assert platformdirs.user_config_path("app") == parent_root / "user_config/app"
assert not parent_root.exists()
assert platformdirs.user_config_path("app") == original
assert (child_root / "user_config/app/1.0/settings.toml").read_text(encoding="utf-8") == "enabled = true"
print("ok")
"""
script.write_text(code, encoding="utf-8")
assert check_output([sys.executable, str(script), str(tmp_path)], text=True, timeout=20).strip() == "ok"


def test_isolated_dirs_nested_restores_outer(tmp_path: Path) -> None:
with isolated_dirs(tmp_path / "outer"):
with isolated_dirs(tmp_path / "inner"):
Expand Down
Loading