From 3292f77d7628be247d920f375709a4856578f67a Mon Sep 17 00:00:00 2001 From: Christopher Pruijsen Date: Fri, 9 Oct 2026 03:04:17 +0100 Subject: [PATCH 1/3] fix(paths): prefer SCRATCH, TMPDIR, MNE_DATA and platform cache over cwd for the default cache directory --- eegdash/paths.py | 82 ++++++++++++++---- pyproject.toml | 1 + tests/unit_tests/test_paths.py | 146 +++++++++++++++++++++++++++++++-- 3 files changed, 206 insertions(+), 23 deletions(-) diff --git a/eegdash/paths.py b/eegdash/paths.py index 0da3e0525..68465aea4 100644 --- a/eegdash/paths.py +++ b/eegdash/paths.py @@ -11,10 +11,42 @@ from __future__ import annotations +import logging import os from pathlib import Path from mne.utils import get_config as mne_get_config +from platformdirs import user_cache_dir + +logger = logging.getLogger(__name__) + +_cache_dir_logged = False + + +def _is_writable_dir(path: Path) -> bool: + """Return True when *path* is an existing, writable directory.""" + try: + return path.is_dir() and os.access(path, os.W_OK) + except OSError: + return False + + +def _create_and_check_writable(path: Path) -> bool: + """Create *path* including parents and return True when it is writable.""" + try: + path.mkdir(parents=True, exist_ok=True) + except OSError: + return False + return os.access(path, os.W_OK) + + +def _log_resolved(path: Path) -> Path: + """Log the resolved cache directory once per process and return it.""" + global _cache_dir_logged + if not _cache_dir_logged: + logger.info("EEGDash cache directory: %s", path) + _cache_dir_logged = True + return path def get_default_cache_dir() -> Path: @@ -24,10 +56,18 @@ def get_default_cache_dir() -> Path: priority order: 1. The path specified by the ``EEGDASH_CACHE_DIR`` environment variable. - 2. A hidden directory named ``.eegdash_cache`` in the current working - directory. - 3. The path specified by the ``MNE_DATA`` configuration in the MNE-Python - config file (fallback). + 2. An ``eegdash`` directory inside ``$SCRATCH`` when it points to a + writable directory (common on HPC clusters). + 3. An ``eegdash`` directory inside ``$TMPDIR`` when it points to a + writable directory. + 4. The path specified by the ``MNE_DATA`` configuration in the + MNE-Python config file. + 5. The platform user-cache directory + (:func:`platformdirs.user_cache_dir`). + 6. A hidden directory named ``.eegdash_cache`` in the current working + directory (last resort). + + The resolved path is logged once per process at first use. Returns ------- @@ -38,23 +78,35 @@ def get_default_cache_dir() -> Path: # 1) Explicit env var wins env_dir = os.environ.get("EEGDASH_CACHE_DIR") if env_dir: - return Path(env_dir).expanduser().resolve() + return _log_resolved(Path(env_dir).expanduser().resolve()) - # 2) Default to a project-local hidden folder (best for CI & reproducibility) + # 2) HPC scratch space if usable + scratch = os.environ.get("SCRATCH") + if scratch and _is_writable_dir(Path(scratch).expanduser()): + return _log_resolved(Path(scratch).expanduser().resolve() / "eegdash") + + # 3) TMPDIR if usable + tmpdir = os.environ.get("TMPDIR") + if tmpdir and _is_writable_dir(Path(tmpdir).expanduser()): + return _log_resolved(Path(tmpdir).expanduser().resolve() / "eegdash") + + # 4) MNE's configured data directory + mne_data = mne_get_config("MNE_DATA") + if mne_data: + return _log_resolved(Path(mne_data).expanduser().resolve()) + + # 5) Platform user-cache directory + platform_cache = Path(user_cache_dir("eegdash", appauthor=False)) + if _create_and_check_writable(platform_cache): + return _log_resolved(platform_cache) + + # 6) Last resort: a hidden folder in the current working directory local = Path.cwd() / ".eegdash_cache" try: local.mkdir(exist_ok=True, parents=True) - return local except Exception: pass - - # 3) Fall back to MNE's data cache location if configured - mne_data = mne_get_config("MNE_DATA") - if mne_data: - return Path(mne_data).expanduser().resolve() - - # Last-resort: local path without pre-creating - return local + return _log_resolved(local) __all__ = ["get_default_cache_dir"] diff --git a/pyproject.toml b/pyproject.toml index 13865b2f8..5485c9dd3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,6 +65,7 @@ dependencies = [ # install stays lean. "nemar-py>=0.2.0", "pandas", + "platformdirs", "pydantic", "pymatreader", "requests>=2.25.0", diff --git a/tests/unit_tests/test_paths.py b/tests/unit_tests/test_paths.py index 9564ab50c..85cd14442 100644 --- a/tests/unit_tests/test_paths.py +++ b/tests/unit_tests/test_paths.py @@ -1,11 +1,21 @@ +import logging +import os from pathlib import Path from unittest.mock import patch import pytest +import eegdash.paths as paths_module from eegdash.paths import get_default_cache_dir +@pytest.fixture(autouse=True) +def _clean_cache_env(monkeypatch): + """Clear every environment variable consulted by get_default_cache_dir.""" + for var in ("EEGDASH_CACHE_DIR", "SCRATCH", "TMPDIR"): + monkeypatch.delenv(var, raising=False) + + @pytest.mark.parametrize("env_value", ["~/custom_eegdash_cache", "/opt/eegdash-cache"]) def test_get_default_cache_dir_from_env(monkeypatch, env_value): monkeypatch.setenv("EEGDASH_CACHE_DIR", env_value) @@ -13,13 +23,82 @@ def test_get_default_cache_dir_from_env(monkeypatch, env_value): assert get_default_cache_dir() == Path(env_value).expanduser().resolve() -def test_get_default_cache_dir_prefers_local_hidden_folder(monkeypatch, tmp_path): - monkeypatch.delenv("EEGDASH_CACHE_DIR", raising=False) +def test_get_default_cache_dir_prefers_scratch_over_tmpdir(monkeypatch, tmp_path): + scratch = tmp_path / "scratch" + tmpdir = tmp_path / "tmpdir" + scratch.mkdir() + tmpdir.mkdir() + monkeypatch.setenv("SCRATCH", str(scratch)) + monkeypatch.setenv("TMPDIR", str(tmpdir)) + + assert get_default_cache_dir() == scratch / "eegdash" + + +def test_get_default_cache_dir_uses_tmpdir(monkeypatch, tmp_path): + tmpdir = tmp_path / "tmpdir" + tmpdir.mkdir() + monkeypatch.setenv("TMPDIR", str(tmpdir)) + + assert get_default_cache_dir() == tmpdir / "eegdash" + + +@pytest.mark.parametrize("var", ["SCRATCH", "TMPDIR"]) +def test_get_default_cache_dir_skips_unwritable_env_dirs(monkeypatch, tmp_path, var): + not_writable = tmp_path / var.lower() + not_writable.mkdir() + mne_dir = tmp_path / "mne_data" + monkeypatch.setenv(var, str(not_writable)) + + real_access = os.access + monkeypatch.setattr( + os, + "access", + lambda path, mode: ( + False if Path(path) == not_writable else real_access(path, mode) + ), + ) + + with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): + assert get_default_cache_dir() == mne_dir - with patch("eegdash.paths.mne_get_config", return_value=str(tmp_path / "mne_data")): - with patch.object(Path, "cwd", return_value=tmp_path): + +def test_get_default_cache_dir_skips_missing_scratch(monkeypatch, tmp_path): + monkeypatch.setenv("SCRATCH", str(tmp_path / "does-not-exist")) + mne_dir = tmp_path / "mne_data" + + with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): + assert get_default_cache_dir() == mne_dir + + +def test_get_default_cache_dir_uses_mne_data(monkeypatch, tmp_path): + mne_dir = tmp_path / "mne_data" + + with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): + assert get_default_cache_dir() == mne_dir + + +def test_get_default_cache_dir_uses_platform_user_cache(monkeypatch, tmp_path): + platform_cache = tmp_path / "user-cache" / "eegdash" + + with patch("eegdash.paths.mne_get_config", return_value=None): + with patch("eegdash.paths.user_cache_dir", return_value=str(platform_cache)): resolved = get_default_cache_dir() + assert resolved == platform_cache + assert resolved.exists() + + +def test_get_default_cache_dir_falls_back_to_local_hidden_folder(monkeypatch, tmp_path): + with patch("eegdash.paths.mne_get_config", return_value=None): + with patch( + "eegdash.paths.user_cache_dir", + return_value=str(tmp_path / "a-file" / "eegdash"), + ): + # The platform cache cannot be created below an existing file. + (tmp_path / "a-file").touch() + with patch.object(Path, "cwd", return_value=tmp_path): + resolved = get_default_cache_dir() + assert resolved == tmp_path / ".eegdash_cache" assert resolved.exists() @@ -31,18 +110,69 @@ def test_get_default_cache_dir_prefers_local_hidden_folder(monkeypatch, tmp_path (None, ".eegdash_cache"), ], ) -def test_get_default_cache_dir_fallbacks_when_local_mkdir_fails( +def test_get_default_cache_dir_local_last_resort_when_mkdir_fails( monkeypatch, tmp_path, mne_value, expected_name ): - monkeypatch.delenv("EEGDASH_CACHE_DIR", raising=False) - with patch.object(Path, "cwd", return_value=tmp_path): with patch.object(Path, "mkdir", side_effect=PermissionError("readonly")): with patch("eegdash.paths.mne_get_config", return_value=mne_value): - resolved = get_default_cache_dir() + with patch( + "eegdash.paths.user_cache_dir", + return_value=str(tmp_path / "user-cache"), + ): + resolved = get_default_cache_dir() assert resolved.name == expected_name if mne_value is None: assert resolved == tmp_path / ".eegdash_cache" + assert not resolved.exists() else: assert resolved == Path(mne_value).expanduser().resolve() + + +def test_get_default_cache_dir_resolution_order(monkeypatch, tmp_path): + scratch = tmp_path / "scratch" + tmpdir = tmp_path / "tmpdir" + scratch.mkdir() + tmpdir.mkdir() + env_dir = tmp_path / "from-env" + mne_dir = tmp_path / "mne-data" + platform_cache = tmp_path / "user-cache" / "eegdash" + + monkeypatch.setenv("EEGDASH_CACHE_DIR", str(env_dir)) + monkeypatch.setenv("SCRATCH", str(scratch)) + monkeypatch.setenv("TMPDIR", str(tmpdir)) + + with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): + with patch("eegdash.paths.user_cache_dir", return_value=str(platform_cache)): + with patch.object(Path, "cwd", return_value=tmp_path): + assert get_default_cache_dir() == env_dir + + monkeypatch.delenv("EEGDASH_CACHE_DIR") + assert get_default_cache_dir() == scratch / "eegdash" + + monkeypatch.delenv("SCRATCH") + assert get_default_cache_dir() == tmpdir / "eegdash" + + monkeypatch.delenv("TMPDIR") + assert get_default_cache_dir() == mne_dir + + with patch("eegdash.paths.mne_get_config", return_value=None): + assert get_default_cache_dir() == platform_cache + + +def test_get_default_cache_dir_logs_once(monkeypatch, tmp_path, caplog): + monkeypatch.setattr(paths_module, "_cache_dir_logged", False) + monkeypatch.setenv("SCRATCH", str(tmp_path)) + + with caplog.at_level(logging.INFO, logger="eegdash.paths"): + get_default_cache_dir() + get_default_cache_dir() + + messages = [ + record.getMessage() + for record in caplog.records + if "cache directory" in record.getMessage().lower() + ] + assert len(messages) == 1 + assert str(tmp_path / "eegdash") in messages[0] From 46745d9a6ee3f273694c24587c0ee02051f23e7a Mon Sep 17 00:00:00 2001 From: Christopher Pruijsen Date: Fri, 9 Oct 2026 03:04:17 +0100 Subject: [PATCH 2/3] docs(examples): stop describing the working-directory cache as the default --- examples/tutorials/40_features/plot_42_features_to_sklearn.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/tutorials/40_features/plot_42_features_to_sklearn.py b/examples/tutorials/40_features/plot_42_features_to_sklearn.py index 418c7e353..7a48568cc 100644 --- a/examples/tutorials/40_features/plot_42_features_to_sklearn.py +++ b/examples/tutorials/40_features/plot_42_features_to_sklearn.py @@ -11,8 +11,8 @@ ---------------- Install EEGDash's dependencies and run ``plot_40_first_features.py`` first. Use exactly the same ``EEGDASH_CACHE_DIR`` for both scripts; the default -``.eegdash_cache`` is relative to the working directory. You need the CSV and -its adjacent JSON schema, but no live signal download for this page. +location depends on the environment (``$SCRATCH``, ``$TMPDIR``, ...). You need +the CSV and its adjacent JSON schema, but no live signal download for this page. Tutorial 11 explains the participant split used below. """ From c3c68f04694bf4c7a43cf8055342bf5716a34d46 Mon Sep 17 00:00:00 2001 From: Bruno Aristimunha Date: Wed, 18 Nov 2026 12:43:12 +0000 Subject: [PATCH 3/3] Keep an existing working-directory cache; MNE_DATA before TMPDIR, drop TMPDIR - An existing ./.eegdash_cache (the previous default) is used before the new locations, so upgrading does not download every dataset again. - TMPDIR is purged by macOS and wiped after a Slurm job, and placed before MNE_DATA it overrode a user's explicit MNE_DATA (macOS always sets it). After the platform cache it would never be reached, so it is dropped. - Stale ./.eegdash_cache defaults in corpus.py (docstring, --cache-dir help) and base.py; CHANGELOG entry. - test_paths.py: every test runs in an empty working directory; one test per step (8 tests). --- CHANGELOG.md | 1 + eegdash/corpus.py | 6 +- eegdash/dataset/base.py | 6 +- eegdash/paths.py | 38 ++-- .../plot_42_features_to_sklearn.py | 2 +- tests/unit_tests/test_paths.py | 194 +++++------------- 6 files changed, 72 insertions(+), 175 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e0b84c56..f70023f81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Changed +- The default cache directory is no longer the working directory: after `EEGDASH_CACHE_DIR` and an existing `./.eegdash_cache` (kept, so nothing is downloaded again), it is `$SCRATCH/eegdash` when `$SCRATCH` is writable, then `MNE_DATA`, then the platform user cache (`platformdirs`); `./.eegdash_cache` is the last resort. The resolved path is logged once (#400, #435 by Christopher Pruijsen). - Requires `mne>=1.13` and `mne_bids>=0.20` (were 1.11 / 0.19). MNE 1.11 has no `read_raw_mef`, so MNE-BIDS left `.mefd` out of its readers and EEGDash silently dropped the 640 MEF3 records; 1.13 also reuses the MEF session across reads (mne-python#14254). ### Added diff --git a/eegdash/corpus.py b/eegdash/corpus.py index abfeb3b5f..4f50b4c87 100644 --- a/eegdash/corpus.py +++ b/eegdash/corpus.py @@ -264,8 +264,8 @@ class EEGDashCorpus: or the path of a CSV with a ``dataset_id`` column (an ``n_subjects`` column is checked against the catalogue when present). cache_dir : str | Path | None - As for :class:`EEGDashDataset` (``EEGDASH_CACHE_DIR``, else - ``./.eegdash_cache``). + As for :class:`EEGDashDataset` (see + :func:`eegdash.paths.get_default_cache_dir`). eeg_dash_instance : EEGDash | None The catalogue client, created when first needed (verify, status and records never need one). @@ -536,7 +536,7 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("command", choices=("plan", "download", "verify", "status")) parser.add_argument("corpus", help="a CSV with a dataset_id column, or ids a,b,c") parser.add_argument( - "--cache-dir", help="default EEGDASH_CACHE_DIR or ./.eegdash_cache" + "--cache-dir", help="default: eegdash.paths.get_default_cache_dir()" ) parser.add_argument("--n-jobs", type=int, default=8) parser.add_argument("--n-datasets", type=int, default=2, help="download") diff --git a/eegdash/dataset/base.py b/eegdash/dataset/base.py index 1a69b4f66..d2d781367 100644 --- a/eegdash/dataset/base.py +++ b/eegdash/dataset/base.py @@ -510,9 +510,9 @@ def _destination_lock(dest: Path) -> threading.Lock: """ # resolve(), not absolute(): two spellings of one file must map to one lock. # absolute() leaves symlinks and ".." in place and is cwd-dependent, and - # cache_dir is frequently relative (EEGDASH_CACHE_DIR defaults to - # ".eegdash_cache"), so absolute() would hand two callers different locks - # for the same destination and serialize nothing. + # cache_dir is frequently relative (EEGDASH_CACHE_DIR or a cache_dir + # argument such as ".eegdash_cache"), so absolute() would hand two callers + # different locks for the same destination and serialize nothing. key = dest.resolve() with _DESTINATION_LOCKS_GUARD: return _DESTINATION_LOCKS.setdefault(key, threading.Lock()) diff --git a/eegdash/paths.py b/eegdash/paths.py index 68465aea4..696dcf6e0 100644 --- a/eegdash/paths.py +++ b/eegdash/paths.py @@ -52,59 +52,49 @@ def _log_resolved(path: Path) -> Path: def get_default_cache_dir() -> Path: """Resolve the default cache directory for EEGDash data. - The function determines the cache directory based on the following - priority order: + The first match wins: - 1. The path specified by the ``EEGDASH_CACHE_DIR`` environment variable. - 2. An ``eegdash`` directory inside ``$SCRATCH`` when it points to a + 1. The ``EEGDASH_CACHE_DIR`` environment variable. + 2. An existing ``.eegdash_cache`` in the current working directory (the + previous default), so an existing cache is not downloaded again. + 3. An ``eegdash`` directory inside ``$SCRATCH`` when it points to a writable directory (common on HPC clusters). - 3. An ``eegdash`` directory inside ``$TMPDIR`` when it points to a - writable directory. - 4. The path specified by the ``MNE_DATA`` configuration in the - MNE-Python config file. + 4. The ``MNE_DATA`` configuration of MNE-Python. 5. The platform user-cache directory (:func:`platformdirs.user_cache_dir`). - 6. A hidden directory named ``.eegdash_cache`` in the current working - directory (last resort). + 6. ``.eegdash_cache`` in the current working directory (last resort). - The resolved path is logged once per process at first use. + The resolved path is logged once per process. Returns ------- - pathlib.Path + Path The resolved, absolute path to the default cache directory. """ - # 1) Explicit env var wins env_dir = os.environ.get("EEGDASH_CACHE_DIR") if env_dir: return _log_resolved(Path(env_dir).expanduser().resolve()) - # 2) HPC scratch space if usable + local = Path.cwd() / ".eegdash_cache" + if local.is_dir(): + return _log_resolved(local) + scratch = os.environ.get("SCRATCH") if scratch and _is_writable_dir(Path(scratch).expanduser()): return _log_resolved(Path(scratch).expanduser().resolve() / "eegdash") - # 3) TMPDIR if usable - tmpdir = os.environ.get("TMPDIR") - if tmpdir and _is_writable_dir(Path(tmpdir).expanduser()): - return _log_resolved(Path(tmpdir).expanduser().resolve() / "eegdash") - - # 4) MNE's configured data directory mne_data = mne_get_config("MNE_DATA") if mne_data: return _log_resolved(Path(mne_data).expanduser().resolve()) - # 5) Platform user-cache directory platform_cache = Path(user_cache_dir("eegdash", appauthor=False)) if _create_and_check_writable(platform_cache): return _log_resolved(platform_cache) - # 6) Last resort: a hidden folder in the current working directory - local = Path.cwd() / ".eegdash_cache" try: local.mkdir(exist_ok=True, parents=True) - except Exception: + except OSError: pass return _log_resolved(local) diff --git a/examples/tutorials/40_features/plot_42_features_to_sklearn.py b/examples/tutorials/40_features/plot_42_features_to_sklearn.py index 7a48568cc..1689b5b4d 100644 --- a/examples/tutorials/40_features/plot_42_features_to_sklearn.py +++ b/examples/tutorials/40_features/plot_42_features_to_sklearn.py @@ -11,7 +11,7 @@ ---------------- Install EEGDash's dependencies and run ``plot_40_first_features.py`` first. Use exactly the same ``EEGDASH_CACHE_DIR`` for both scripts; the default -location depends on the environment (``$SCRATCH``, ``$TMPDIR``, ...). You need +location depends on the environment (``$SCRATCH``, ``MNE_DATA``, ...). You need the CSV and its adjacent JSON schema, but no live signal download for this page. Tutorial 11 explains the participant split used below. """ diff --git a/tests/unit_tests/test_paths.py b/tests/unit_tests/test_paths.py index 85cd14442..c8a40d703 100644 --- a/tests/unit_tests/test_paths.py +++ b/tests/unit_tests/test_paths.py @@ -1,7 +1,6 @@ import logging import os from pathlib import Path -from unittest.mock import patch import pytest @@ -10,169 +9,76 @@ @pytest.fixture(autouse=True) -def _clean_cache_env(monkeypatch): - """Clear every environment variable consulted by get_default_cache_dir.""" +def isolated(monkeypatch, tmp_path): + """Empty working directory, no cache env vars, no MNE_DATA, a temp user cache.""" for var in ("EEGDASH_CACHE_DIR", "SCRATCH", "TMPDIR"): monkeypatch.delenv(var, raising=False) + cwd = tmp_path / "cwd" + cwd.mkdir() + monkeypatch.chdir(cwd) + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: None) + monkeypatch.setattr( + paths_module, "user_cache_dir", lambda *a, **k: str(tmp_path / "user-cache") + ) + return tmp_path @pytest.mark.parametrize("env_value", ["~/custom_eegdash_cache", "/opt/eegdash-cache"]) -def test_get_default_cache_dir_from_env(monkeypatch, env_value): +def test_env_var_wins(monkeypatch, env_value): monkeypatch.setenv("EEGDASH_CACHE_DIR", env_value) - assert get_default_cache_dir() == Path(env_value).expanduser().resolve() -def test_get_default_cache_dir_prefers_scratch_over_tmpdir(monkeypatch, tmp_path): - scratch = tmp_path / "scratch" - tmpdir = tmp_path / "tmpdir" +def test_resolution_order(monkeypatch, isolated): + scratch, mne_dir = isolated / "scratch", isolated / "mne" scratch.mkdir() - tmpdir.mkdir() monkeypatch.setenv("SCRATCH", str(scratch)) - monkeypatch.setenv("TMPDIR", str(tmpdir)) + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: str(mne_dir)) + local = Path.cwd() / ".eegdash_cache" + local.mkdir() # an existing working-directory cache is kept + assert get_default_cache_dir() == local + local.rmdir() assert get_default_cache_dir() == scratch / "eegdash" + monkeypatch.delenv("SCRATCH") + assert get_default_cache_dir() == mne_dir + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: None) + assert get_default_cache_dir() == isolated / "user-cache" + assert not local.exists() + + +def test_tmpdir_is_not_used(monkeypatch, isolated): + # TMPDIR is purged by macOS and wiped after a Slurm job: never a default. + monkeypatch.setenv("TMPDIR", str(isolated)) + assert get_default_cache_dir() == isolated / "user-cache" + + +@pytest.mark.parametrize("writable", [False, None]) # unwritable, missing +def test_unusable_scratch_is_skipped(monkeypatch, isolated, writable): + scratch = isolated / "scratch" + if writable is False: + scratch.mkdir() + real = os.access + monkeypatch.setattr( + os, "access", lambda p, m: False if Path(p) == scratch else real(p, m) + ) + monkeypatch.setenv("SCRATCH", str(scratch)) + assert get_default_cache_dir() == isolated / "user-cache" -def test_get_default_cache_dir_uses_tmpdir(monkeypatch, tmp_path): - tmpdir = tmp_path / "tmpdir" - tmpdir.mkdir() - monkeypatch.setenv("TMPDIR", str(tmpdir)) - - assert get_default_cache_dir() == tmpdir / "eegdash" - - -@pytest.mark.parametrize("var", ["SCRATCH", "TMPDIR"]) -def test_get_default_cache_dir_skips_unwritable_env_dirs(monkeypatch, tmp_path, var): - not_writable = tmp_path / var.lower() - not_writable.mkdir() - mne_dir = tmp_path / "mne_data" - monkeypatch.setenv(var, str(not_writable)) - - real_access = os.access +def test_working_directory_is_the_last_resort(monkeypatch, isolated): + (isolated / "a-file").touch() # the user cache cannot be created below a file monkeypatch.setattr( - os, - "access", - lambda path, mode: ( - False if Path(path) == not_writable else real_access(path, mode) - ), + paths_module, "user_cache_dir", lambda *a, **k: str(isolated / "a-file" / "x") ) - - with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): - assert get_default_cache_dir() == mne_dir - - -def test_get_default_cache_dir_skips_missing_scratch(monkeypatch, tmp_path): - monkeypatch.setenv("SCRATCH", str(tmp_path / "does-not-exist")) - mne_dir = tmp_path / "mne_data" - - with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): - assert get_default_cache_dir() == mne_dir - - -def test_get_default_cache_dir_uses_mne_data(monkeypatch, tmp_path): - mne_dir = tmp_path / "mne_data" - - with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): - assert get_default_cache_dir() == mne_dir - - -def test_get_default_cache_dir_uses_platform_user_cache(monkeypatch, tmp_path): - platform_cache = tmp_path / "user-cache" / "eegdash" - - with patch("eegdash.paths.mne_get_config", return_value=None): - with patch("eegdash.paths.user_cache_dir", return_value=str(platform_cache)): - resolved = get_default_cache_dir() - - assert resolved == platform_cache - assert resolved.exists() + resolved = get_default_cache_dir() + assert resolved == Path.cwd() / ".eegdash_cache" + assert resolved.is_dir() -def test_get_default_cache_dir_falls_back_to_local_hidden_folder(monkeypatch, tmp_path): - with patch("eegdash.paths.mne_get_config", return_value=None): - with patch( - "eegdash.paths.user_cache_dir", - return_value=str(tmp_path / "a-file" / "eegdash"), - ): - # The platform cache cannot be created below an existing file. - (tmp_path / "a-file").touch() - with patch.object(Path, "cwd", return_value=tmp_path): - resolved = get_default_cache_dir() - - assert resolved == tmp_path / ".eegdash_cache" - assert resolved.exists() - - -@pytest.mark.parametrize( - "mne_value,expected_name", - [ - ("~/mne-data", "mne-data"), - (None, ".eegdash_cache"), - ], -) -def test_get_default_cache_dir_local_last_resort_when_mkdir_fails( - monkeypatch, tmp_path, mne_value, expected_name -): - with patch.object(Path, "cwd", return_value=tmp_path): - with patch.object(Path, "mkdir", side_effect=PermissionError("readonly")): - with patch("eegdash.paths.mne_get_config", return_value=mne_value): - with patch( - "eegdash.paths.user_cache_dir", - return_value=str(tmp_path / "user-cache"), - ): - resolved = get_default_cache_dir() - - assert resolved.name == expected_name - if mne_value is None: - assert resolved == tmp_path / ".eegdash_cache" - assert not resolved.exists() - else: - assert resolved == Path(mne_value).expanduser().resolve() - - -def test_get_default_cache_dir_resolution_order(monkeypatch, tmp_path): - scratch = tmp_path / "scratch" - tmpdir = tmp_path / "tmpdir" - scratch.mkdir() - tmpdir.mkdir() - env_dir = tmp_path / "from-env" - mne_dir = tmp_path / "mne-data" - platform_cache = tmp_path / "user-cache" / "eegdash" - - monkeypatch.setenv("EEGDASH_CACHE_DIR", str(env_dir)) - monkeypatch.setenv("SCRATCH", str(scratch)) - monkeypatch.setenv("TMPDIR", str(tmpdir)) - - with patch("eegdash.paths.mne_get_config", return_value=str(mne_dir)): - with patch("eegdash.paths.user_cache_dir", return_value=str(platform_cache)): - with patch.object(Path, "cwd", return_value=tmp_path): - assert get_default_cache_dir() == env_dir - - monkeypatch.delenv("EEGDASH_CACHE_DIR") - assert get_default_cache_dir() == scratch / "eegdash" - - monkeypatch.delenv("SCRATCH") - assert get_default_cache_dir() == tmpdir / "eegdash" - - monkeypatch.delenv("TMPDIR") - assert get_default_cache_dir() == mne_dir - - with patch("eegdash.paths.mne_get_config", return_value=None): - assert get_default_cache_dir() == platform_cache - - -def test_get_default_cache_dir_logs_once(monkeypatch, tmp_path, caplog): +def test_logs_once(monkeypatch, caplog): monkeypatch.setattr(paths_module, "_cache_dir_logged", False) - monkeypatch.setenv("SCRATCH", str(tmp_path)) - with caplog.at_level(logging.INFO, logger="eegdash.paths"): get_default_cache_dir() get_default_cache_dir() - - messages = [ - record.getMessage() - for record in caplog.records - if "cache directory" in record.getMessage().lower() - ] - assert len(messages) == 1 - assert str(tmp_path / "eegdash") in messages[0] + assert sum("cache directory" in r.getMessage() for r in caplog.records) == 1