Coverage for backend/tests/utils/files.py: 76%
46 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-22 15:38 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-22 15:38 +0000
1"""
2File loading utilities for test data
3"""
5import base64
6import mimetypes
7from pathlib import Path
10def get_resources_path() -> Path:
11 """Get the path to the resources folder"""
13 current_dir = Path(__file__).parent
14 return current_dir / "../resources"
17def load_file_as_base64(filename: str) -> str | None:
18 """Load a file from the resources folder and return as base64 string"""
19 resources_path = get_resources_path()
20 file_path = resources_path / filename
22 try:
23 with open(file_path, "rb") as file:
24 file_content = file.read()
25 return base64.b64encode(file_content).decode("utf-8")
26 except Exception as e:
27 print(f"❌ Error reading file {filename}: {e}")
28 return None
31def get_file_info(filename) -> tuple[int | None, str | None]:
32 """Get file size and MIME type"""
34 resources_path = get_resources_path()
35 file_path = resources_path / filename
37 if not file_path.exists():
38 return None, None
40 try:
41 # Get file size
42 file_size = file_path.stat().st_size
44 # Get MIME type
45 mime_type, _ = mimetypes.guess_type(str(file_path))
46 if mime_type is None:
47 # Default MIME types for common file extensions
48 ext = file_path.suffix.lower()
49 mime_defaults = {
50 ".pdf": "application/pdf",
51 ".doc": "application/msword",
52 ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
53 ".txt": "text/plain",
54 }
55 mime_type = mime_defaults.get(ext, "application/octet-stream")
57 return file_size, mime_type
58 except Exception as e:
59 print(f"❌ Error getting file info for {filename}: {e}")
60 return None, None
63def load_all_resource_files() -> dict[str, dict[str, str | int]]:
64 """Load all files from the resources folder"""
66 resources_path = get_resources_path()
67 loaded_files = {}
69 print(f"📁 Loading files from: {resources_path}")
71 for file_path in resources_path.iterdir():
72 if file_path.is_file():
73 file_content = load_file_as_base64(file_path.name)
74 file_size, mime_type = get_file_info(file_path.name)
76 if file_content:
77 loaded_files[file_path.name] = {"content": file_content, "size": file_size, "type": mime_type}
79 if not loaded_files:
80 print("📂 No files found in resources folder")
81 else:
82 print(f"📊 Total files loaded: {len(loaded_files)}")
84 return loaded_files