clan-core/pkgs/clan-cli/tests/temporary_dir.py
Jörg Thalheim b8ed607658 also override XDG_DATA_HOME in tests
otherwise tests will fail if XDG_DATA_HOME is set by a user
2023-11-09 17:45:24 +01:00

28 lines
862 B
Python

import logging
import os
import tempfile
from pathlib import Path
from typing import Iterator
import pytest
log = logging.getLogger(__name__)
@pytest.fixture
def temporary_home(monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
env_dir = os.getenv("TEST_TEMPORARY_DIR")
if env_dir is not None:
path = Path(env_dir).resolve()
log.debug("Temp HOME directory: %s", str(path))
monkeypatch.setenv("HOME", str(path))
monkeypatch.chdir(str(path))
yield path
else:
with tempfile.TemporaryDirectory(prefix="pytest-") as dirpath:
monkeypatch.setenv("HOME", str(dirpath))
monkeypatch.setenv("XDG_DATA_HOME", str(Path(dirpath) / ".local/share"))
monkeypatch.chdir(str(dirpath))
log.debug("Temp HOME directory: %s", str(dirpath))
yield Path(dirpath)