Testing Helpers
Tests that exercise code using platformdirs should never touch the real home directory or system folders. platformdirs ships two helpers for that: the platformdirs.testing.isolated_dirs() context manager and the platformdirs_isolated pytest fixture built on it. This page explains how they redirect directories, the layout they produce, and their behavior with threads and subprocesses.
Quick Example
Code under test:
# my_app.py
import json
from platformdirs import PlatformDirs
def load_config(dirs: PlatformDirs) -> dict:
config_file = dirs.user_config_path / "config.json"
if config_file.exists():
return json.loads(config_file.read_text(encoding="utf-8"))
return {}
With pytest, request the fixture:
# test_my_app.py
from platformdirs import PlatformDirs
from my_app import load_config
def test_loads_config(platformdirs_isolated):
config_file = PlatformDirs("MyApp", ensure_exists=True).user_config_path / "config.json"
config_file.write_text('{"theme": "dark"}', encoding="utf-8")
assert load_config(PlatformDirs("MyApp")) == {"theme": "dark"}
assert config_file == platformdirs_isolated / "user_config" / "MyApp" / "config.json"
Without pytest, use the context manager:
import tempfile
from platformdirs import PlatformDirs
from platformdirs.testing import isolated_dirs
with tempfile.TemporaryDirectory() as tmp, isolated_dirs(tmp) as root:
print(PlatformDirs("MyApp").user_cache_path) # <root>/user_cache/MyApp
isolated_dirs(root)
from platformdirs.testing import isolated_dirs
with isolated_dirs(root) as base:
...
rootis astror path-like object. A relative root is made absolute on entry, so changing the working directory inside the context does not move it.- The context yields that absolute root as a
pathlib.Path. - On exit, the original directory properties are restored.
Directory Layout
Inside the context, every directory property of PlatformDirs resolves to <root>/<kind>, where kind is the property name without _dir:
| Property | Inside isolated_dirs(root) with PlatformDirs("MyApp", version="1.0") |
|---|---|
user_data_dir |
<root>/user_data/MyApp/1.0 |
user_config_dir |
<root>/user_config/MyApp/1.0 |
user_cache_dir |
<root>/user_cache/MyApp/1.0 |
user_state_dir |
<root>/user_state/MyApp/1.0 |
user_log_dir |
<root>/user_log/MyApp/1.0 |
user_runtime_dir |
<root>/user_runtime/MyApp/1.0 |
user_preference_dir |
<root>/user_preference/MyApp/1.0 |
site_data_dir (and other site_* app kinds) |
<root>/site_data/MyApp/1.0 |
user_documents_dir |
<root>/user_documents |
user_fonts_dir |
<root>/user_fonts |
user_bin_dir, site_bin_dir |
<root>/user_bin, <root>/site_bin |
user_applications_dir, site_applications_dir |
<root>/user_applications, <root>/site_applications |
Only the 13 app kinds (user and site data, config, cache, state, log and runtime, plus user_preference) append appname and version. Media, fonts, bin and applications kinds do not. appauthor, roaming, opinion and the platform's own subfolders (Cache, Logs, log) play no part in the isolated layout, so the same test produces the same paths on every operating system. The *_path properties, iterators, place_*_file and find_*_file methods, and the module functions all follow the redirect.
What Else Changes Inside the Context
- Site lists collapse to one entry.
XDG_DATA_DIRS,XDG_CONFIG_DIRSand the Homebrew lists are ignored, soiter_config_paths()yields<root>/user_config/MyAppthen<root>/site_config/MyApp. use_site_for_rootis ignored, so user and site kinds stay separate even when tests run as root.- No runtime directory checks. The
XDG_RUNTIME_DIRvalidation and theRuntimeDirWarningare bypassed. ensure_existsstill works for the app kinds: user kinds are created with mode0700, site kinds with the default mode. Media, fonts, bin and applications kinds are never created.
Scope: Threads, Forks and Spawned Processes
The redirect patches the PlatformDirs class itself, so:
- All threads of the process see it. When contexts overlap (nested, or entered by different threads), every thread sees the newest active root. Closing an older context while a newer one is open leaves the newer root in effect; the original paths come back only when every context has closed.
- Forked children inherit the redirect active at the fork. A lock held around fork guarantees the child never sees a half-applied redirect. Parent and child then share the same directories, so keep the root until the child exits.
- Spawned children (the
spawnstart method, the default on Windows and macOS) start with the original paths. Enterisolated_dirsinside the worker. Withforkserver, the child inherits the server's state. - Other classes are not patched. Only
platformdirs.PlatformDirs(and its aliasAppDirs) is redirected; a directly imported class such asplatformdirs.unix.Unixon macOS keeps its real paths.
Use separate processes if concurrent tests need different roots.
Example of isolating a spawned worker:
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"
The worker is defined at module level and process creation is guarded by if __name__ == "__main__", so the child can import the worker without starting another pool.
The platformdirs_isolated Fixture
Installing platformdirs registers a pytest plugin through the pytest11 entry point (platformdirs.pytest_plugin), so the fixture is available in every test without any conftest.py setup. It wraps isolated_dirs(tmp_path) and yields the root, which is tmp_path:
def test_cache_location(platformdirs_isolated):
from platformdirs import user_cache_path
assert user_cache_path("MyApp") == platformdirs_isolated / "user_cache" / "MyApp"
The plugin imports platformdirs.testing only when a test requests the fixture, so having platformdirs installed adds no startup cost to unrelated test suites. To apply isolation to every test, wrap it in an autouse fixture:
# conftest.py
import pytest
@pytest.fixture(autouse=True)
def _isolate_platformdirs(platformdirs_isolated):
return platformdirs_isolated
Note: If your project disables plugin autoloading (
PYTEST_DISABLE_PLUGIN_AUTOLOAD=1), enable the plugin explicitly with-p platformdirs.pytest_plugin.
Alternatives
You can also isolate tests by setting environment variables (XDG_CONFIG_HOME, HOME, WIN_PD_OVERRIDE_*) or by mocking properties. That works, but environment variables only affect some platforms and some directories, and leave most site_* directories pointing at real system paths. isolated_dirs covers all 27 directories on every platform.