import gc
import re
import shutil
from pathlib import Path
from uuid import uuid4
import pytest
_NODE_DIR_MAX = 30
def _safe_node_dirname(node_name: str) -> str:
cleaned = re.sub(r"[\W]", "_", node_name)[:_NODE_DIR_MAX]
return cleaned or "test"
@pytest.fixture
def tmp_path(request):
root = Path.cwd() / "scratch" / "pytest-managed"
root.mkdir(parents=True, exist_ok=True)
path = root / f"{_safe_node_dirname(request.node.name)}-{uuid4().hex}"
path.mkdir()
try:
yield path
finally:
gc.collect()
shutil.rmtree(path, ignore_errors=True)
try:
root.rmdir()
root.parent.rmdir()
except OSError:
pass