-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_image_processor.py
More file actions
174 lines (139 loc) · 6.39 KB
/
test_image_processor.py
File metadata and controls
174 lines (139 loc) · 6.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python3
"""
Test script for image processor functionality.
This script tests the image processor without requiring actual image files.
"""
import json
from unittest.mock import Mock, patch
from src.file_processors.image_processor import ImageProcessor
def test_image_processor_initialization():
"""Test that the ImageProcessor can be initialized with mocked APIs."""
print("Testing ImageProcessor initialization...")
try:
# Mock the API initialization to avoid requiring real API keys
with patch('src.file_processors.image_processor.OpenAI') as mock_openai, \
patch('src.file_processors.image_processor.genai') as mock_genai, \
patch('src.file_processors.image_processor.Config') as mock_config:
# Setup mock config
mock_config.OPENAI_API_KEY = "test_key"
mock_config.GOOGLE_API_KEY = "test_key"
mock_config.IMAGE_SUPPORTED_EXTENSIONS = {'.jpg', '.png', '.gif'}
mock_config.MAX_FILE_SIZE_MB = 100
# Mock OpenAI client
mock_openai_client = Mock()
mock_openai.return_value = mock_openai_client
# Mock Gemini model
mock_gemini_model = Mock()
mock_genai.GenerativeModel.return_value = mock_gemini_model
# Create processor
processor = ImageProcessor()
print("✓ ImageProcessor initialized successfully")
print(f"✓ Supported extensions: {processor.supported_extensions}")
return processor
except Exception as e:
print(f"✗ ImageProcessor initialization failed: {e}")
return None
def test_can_process():
"""Test the can_process method."""
print("\nTesting can_process method...")
try:
with patch('src.file_processors.image_processor.Config') as mock_config:
mock_config.IMAGE_SUPPORTED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
mock_config.OPENAI_API_KEY = "test_key"
mock_config.MAX_FILE_SIZE_MB = 100
with patch('src.file_processors.image_processor.OpenAI'):
processor = ImageProcessor()
# Test supported extensions
test_cases = [
("image.jpg", True),
("photo.jpeg", True),
("picture.png", True),
("animation.gif", True),
("bitmap.bmp", True),
("document.pdf", False),
("video.mp4", False),
("audio.mp3", False),
("text.txt", False),
]
for file_path, expected in test_cases:
result = processor.can_process(file_path)
status = "✓" if result == expected else "✗"
print(f" {status} {file_path}: {result} (expected: {expected})")
except Exception as e:
print(f"✗ can_process test failed: {e}")
def test_json_output_format():
"""Test that the JSON output has the correct format."""
print("\nTesting JSON output format...")
try:
# Create a mock response that would come from extract_image_data
mock_result = {
'success': True,
'error': None,
'title': 'Test Image Title',
'description': 'A detailed description of the test image.',
'extracted_text': 'Some text found in the image',
'processor_used': 'Mock Processor'
}
with patch('src.file_processors.image_processor.Config') as mock_config:
mock_config.IMAGE_SUPPORTED_EXTENSIONS = {'.jpg'}
mock_config.OPENAI_API_KEY = "test_key"
mock_config.MAX_FILE_SIZE_MB = 100
with patch('src.file_processors.image_processor.OpenAI'):
processor = ImageProcessor()
# Mock the extract_image_data method
processor.extract_image_data = Mock(return_value=mock_result)
# Test JSON output
json_output = processor.extract_to_json("test.jpg")
# Parse JSON to verify structure
result = json.loads(json_output)
expected_keys = {'title', 'description', 'extracted_text', 'file_path', 'processor_used'}
actual_keys = set(result.keys())
if expected_keys.issubset(actual_keys):
print("✓ JSON output has correct structure")
print(f"✓ Keys present: {sorted(actual_keys)}")
print(f"✓ Title: {result['title']}")
print(f"✓ Description: {result['description']}")
print(f"✓ Extracted text: {result['extracted_text']}")
else:
missing_keys = expected_keys - actual_keys
print(f"✗ Missing keys: {missing_keys}")
except Exception as e:
print(f"✗ JSON output test failed: {e}")
def test_error_handling():
"""Test error handling in the image processor."""
print("\nTesting error handling...")
try:
# Test with no API keys available
with patch('src.file_processors.image_processor.Config') as mock_config:
mock_config.OPENAI_API_KEY = None
mock_config.GOOGLE_API_KEY = None
mock_config.IMAGE_SUPPORTED_EXTENSIONS = {'.jpg'}
try:
processor = ImageProcessor()
print("✗ Should have raised an error with no API keys")
except ValueError as e:
if "No vision API available" in str(e):
print("✓ Correctly raised error when no API keys available")
else:
print(f"✗ Unexpected error message: {e}")
except Exception as e:
print(f"✗ Error handling test failed: {e}")
def main():
"""Run all tests."""
print("Image Processor Test Suite")
print("=" * 40)
# Run tests
processor = test_image_processor_initialization()
if processor:
test_can_process()
test_json_output_format()
test_error_handling()
print("\n" + "=" * 40)
print("Test suite completed!")
print()
print("Note: These are basic functionality tests with mocked APIs.")
print("For full testing with real images, ensure you have:")
print("1. Valid API keys (OPENAI_API_KEY or GOOGLE_API_KEY)")
print("2. Actual image files to test with")
if __name__ == "__main__":
main()