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

1""" 

2File loading utilities for test data 

3""" 

4 

5import base64 

6import mimetypes 

7from pathlib import Path 

8 

9 

10def get_resources_path() -> Path: 

11 """Get the path to the resources folder""" 

12 

13 current_dir = Path(__file__).parent 

14 return current_dir / "../resources" 

15 

16 

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 

21 

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 

29 

30 

31def get_file_info(filename) -> tuple[int | None, str | None]: 

32 """Get file size and MIME type""" 

33 

34 resources_path = get_resources_path() 

35 file_path = resources_path / filename 

36 

37 if not file_path.exists(): 

38 return None, None 

39 

40 try: 

41 # Get file size 

42 file_size = file_path.stat().st_size 

43 

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") 

56 

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 

61 

62 

63def load_all_resource_files() -> dict[str, dict[str, str | int]]: 

64 """Load all files from the resources folder""" 

65 

66 resources_path = get_resources_path() 

67 loaded_files = {} 

68 

69 print(f"📁 Loading files from: {resources_path}") 

70 

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) 

75 

76 if file_content: 

77 loaded_files[file_path.name] = {"content": file_content, "size": file_size, "type": mime_type} 

78 

79 if not loaded_files: 

80 print("📂 No files found in resources folder") 

81 else: 

82 print(f"📊 Total files loaded: {len(loaded_files)}") 

83 

84 return loaded_files