""" Test utilities for consistent test workspace and registry management. This module provides utilities to ensure all tests use project tmp/ directory and isolated test registries to prevent contamination of production assets. """ import time import shutil from contextlib import contextmanager from pathlib import Path from typing import Optional, Dict, Any from markitect.assets.constants import ( DEFAULT_TEST_ASSETS_DIR, DEFAULT_TEST_REGISTRY_FILENAME ) def get_project_root() -> Path: """Get the project root directory.""" return Path(__file__).parent.parent def create_test_workspace(prefix: str = "test") -> Path: """Create a test workspace in the project tmp directory. Args: prefix: Prefix for the test directory name Returns: Path to the created test workspace """ project_root = get_project_root() temp_dir = project_root / "tmp" / "test_artifacts" / f"{prefix}_{int(time.time() * 1000000)}" temp_dir.mkdir(parents=True, exist_ok=True) return temp_dir @contextmanager def test_workspace(prefix: str = "test"): """Context manager for test workspace that auto-cleans up. Args: prefix: Prefix for the test directory name Yields: Path to the test workspace """ temp_dir = create_test_workspace(prefix) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) def get_test_asset_config(workspace_dir: Path, registry_name: Optional[str] = None) -> Dict[str, Any]: """Get asset configuration for testing that uses isolated test paths. Args: workspace_dir: The test workspace directory registry_name: Optional custom registry filename Returns: Configuration dictionary for AssetManager """ if registry_name is None: registry_name = "test_registry.json" return { "assets": { "storage_path": str(workspace_dir / "assets"), "registry_path": str(workspace_dir / registry_name), "database_path": str(workspace_dir / "test_assets.db"), "enable_deduplication": True, "default_conflict_resolution": "backup" } } def ensure_test_tmp_structure(): """Ensure the test tmp directory structure exists.""" project_root = get_project_root() test_artifacts_dir = project_root / "tmp" / "test_artifacts" test_artifacts_dir.mkdir(parents=True, exist_ok=True) return test_artifacts_dir # Backward compatibility functions for existing tests def temp_workspace(): """Backward compatibility alias for test_workspace().""" return test_workspace() def create_temp_workspace(): """Backward compatibility alias for create_test_workspace().""" return create_test_workspace()