File size: 11,167 Bytes
1041734
 
e7b4937
1041734
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""
Tests for vision tool (multimodal image analysis)
Author: @mangubee
Date: 2026-01-02

Tests cover:
- Image loading and encoding
- Gemini vision analysis
- Claude vision analysis
- Fallback mechanism
- Retry logic
- Error handling
"""

import pytest
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
from src.tools.vision import (
    load_and_encode_image,
    analyze_image_gemini,
    analyze_image_claude,
    analyze_image,
)


# ============================================================================
# Test Fixtures
# ============================================================================

FIXTURES_DIR = Path(__file__).parent / "fixtures"


@pytest.fixture
def test_image_path():
    """Path to test image"""
    return str(FIXTURES_DIR / "test_image.jpg")


@pytest.fixture
def mock_gemini_response():
    """Mock Gemini API response"""
    mock_response = Mock()
    mock_response.text = "This image shows a red square."
    return mock_response


@pytest.fixture
def mock_claude_response():
    """Mock Claude API response"""
    mock_content = Mock()
    mock_content.text = "The image contains a red colored square."

    mock_response = Mock()
    mock_response.content = [mock_content]
    return mock_response


@pytest.fixture
def mock_settings_gemini():
    """Mock Settings with Gemini API key"""
    with patch('src.tools.vision.Settings') as mock:
        settings_instance = Mock()
        settings_instance.google_api_key = "test_google_key"
        settings_instance.anthropic_api_key = None
        mock.return_value = settings_instance
        yield mock


@pytest.fixture
def mock_settings_claude():
    """Mock Settings with Claude API key"""
    with patch('src.tools.vision.Settings') as mock:
        settings_instance = Mock()
        settings_instance.google_api_key = None
        settings_instance.anthropic_api_key = "test_anthropic_key"
        mock.return_value = settings_instance
        yield mock


@pytest.fixture
def mock_settings_both():
    """Mock Settings with both API keys"""
    with patch('src.tools.vision.Settings') as mock:
        settings_instance = Mock()
        settings_instance.google_api_key = "test_google_key"
        settings_instance.anthropic_api_key = "test_anthropic_key"
        mock.return_value = settings_instance
        yield mock


# ============================================================================
# Image Loading Tests
# ============================================================================

def test_load_and_encode_image_success(test_image_path):
    """Test successful image loading and encoding"""
    result = load_and_encode_image(test_image_path)

    assert "data" in result
    assert "mime_type" in result
    assert result["mime_type"] == "image/jpeg"
    assert result["size_mb"] > 0
    assert len(result["data"]) > 0  # Base64 encoded data


def test_load_image_file_not_found():
    """Test image loading with missing file"""
    with pytest.raises(FileNotFoundError):
        load_and_encode_image("nonexistent_image.jpg")


def test_load_image_unsupported_format(tmp_path):
    """Test image loading with unsupported format"""
    # Create a text file with .mp4 extension
    fake_video = tmp_path / "video.mp4"
    fake_video.write_text("not a real video")

    with pytest.raises(ValueError, match="Unsupported image format"):
        load_and_encode_image(str(fake_video))


# ============================================================================
# Gemini Vision Tests
# ============================================================================

def test_analyze_image_gemini_success(mock_settings_gemini, test_image_path, mock_gemini_response):
    """Test successful Gemini vision analysis"""
    with patch('google.genai.Client') as mock_client_class:
        # Mock Gemini client
        mock_client = Mock()
        mock_client.models.generate_content.return_value = mock_gemini_response
        mock_client_class.return_value = mock_client

        result = analyze_image_gemini(test_image_path, "What is in this image?")

        assert result["model"] == "gemini-2.0-flash"
        assert result["answer"] == "This image shows a red square."
        assert result["question"] == "What is in this image?"
        assert result["image_path"] == test_image_path


def test_analyze_image_gemini_default_question(mock_settings_gemini, test_image_path, mock_gemini_response):
    """Test Gemini with default question"""
    with patch('google.genai.Client') as mock_client_class:
        mock_client = Mock()
        mock_client.models.generate_content.return_value = mock_gemini_response
        mock_client_class.return_value = mock_client

        result = analyze_image_gemini(test_image_path)

        assert result["question"] == "Describe this image in detail."


def test_analyze_image_gemini_missing_api_key():
    """Test Gemini with missing API key"""
    with patch('src.tools.vision.Settings') as mock_settings:
        settings_instance = Mock()
        settings_instance.google_api_key = None
        mock_settings.return_value = settings_instance

        with pytest.raises(ValueError, match="GOOGLE_API_KEY not configured"):
            analyze_image_gemini("test.jpg")


def test_analyze_image_gemini_connection_error(mock_settings_gemini, test_image_path):
    """Test Gemini with connection error (triggers retry)"""
    with patch('google.genai.Client') as mock_client_class:
        mock_client = Mock()
        mock_client.models.generate_content.side_effect = ConnectionError("Network error")
        mock_client_class.return_value = mock_client

        with pytest.raises(ConnectionError):
            analyze_image_gemini(test_image_path)

        # Verify retry happened
        assert mock_client.models.generate_content.call_count == 3


# ============================================================================
# Claude Vision Tests
# ============================================================================

def test_analyze_image_claude_success(mock_settings_claude, test_image_path, mock_claude_response):
    """Test successful Claude vision analysis"""
    with patch('anthropic.Anthropic') as mock_anthropic_class:
        # Mock Claude client
        mock_client = Mock()
        mock_client.messages.create.return_value = mock_claude_response
        mock_anthropic_class.return_value = mock_client

        result = analyze_image_claude(test_image_path, "What is in this image?")

        assert result["model"] == "claude-sonnet-4.5"
        assert result["answer"] == "The image contains a red colored square."
        assert result["question"] == "What is in this image?"
        assert result["image_path"] == test_image_path


def test_analyze_image_claude_default_question(mock_settings_claude, test_image_path, mock_claude_response):
    """Test Claude with default question"""
    with patch('anthropic.Anthropic') as mock_anthropic_class:
        mock_client = Mock()
        mock_client.messages.create.return_value = mock_claude_response
        mock_anthropic_class.return_value = mock_client

        result = analyze_image_claude(test_image_path)

        assert result["question"] == "Describe this image in detail."


def test_analyze_image_claude_missing_api_key():
    """Test Claude with missing API key"""
    with patch('src.tools.vision.Settings') as mock_settings:
        settings_instance = Mock()
        settings_instance.anthropic_api_key = None
        mock_settings.return_value = settings_instance

        with pytest.raises(ValueError, match="ANTHROPIC_API_KEY not configured"):
            analyze_image_claude("test.jpg")


def test_analyze_image_claude_connection_error(mock_settings_claude, test_image_path):
    """Test Claude with connection error (triggers retry)"""
    with patch('anthropic.Anthropic') as mock_anthropic_class:
        mock_client = Mock()
        mock_client.messages.create.side_effect = ConnectionError("Network error")
        mock_anthropic_class.return_value = mock_client

        with pytest.raises(ConnectionError):
            analyze_image_claude(test_image_path)

        # Verify retry happened
        assert mock_client.messages.create.call_count == 3


# ============================================================================
# Unified Vision Analysis Tests
# ============================================================================

def test_analyze_image_uses_gemini(mock_settings_both, test_image_path, mock_gemini_response):
    """Test unified analysis prefers Gemini when both APIs available"""
    with patch('google.genai.Client') as mock_gemini_class:
        mock_client = Mock()
        mock_client.models.generate_content.return_value = mock_gemini_response
        mock_gemini_class.return_value = mock_client

        result = analyze_image(test_image_path, "What is this?")

        assert result["model"] == "gemini-2.0-flash"
        assert "red square" in result["answer"].lower()


def test_analyze_image_fallback_to_claude(mock_settings_both, test_image_path, mock_claude_response):
    """Test unified analysis falls back to Claude when Gemini fails"""
    with patch('google.genai.Client') as mock_gemini_class:
        with patch('anthropic.Anthropic') as mock_claude_class:
            # Gemini fails
            mock_gemini_client = Mock()
            mock_gemini_client.models.generate_content.side_effect = Exception("Gemini error")
            mock_gemini_class.return_value = mock_gemini_client

            # Claude succeeds
            mock_claude_client = Mock()
            mock_claude_client.messages.create.return_value = mock_claude_response
            mock_claude_class.return_value = mock_claude_client

            result = analyze_image(test_image_path, "What is this?")

            assert result["model"] == "claude-sonnet-4.5"
            assert "red" in result["answer"].lower()


def test_analyze_image_no_api_keys():
    """Test unified analysis with no API keys configured"""
    with patch('src.tools.vision.Settings') as mock_settings:
        settings_instance = Mock()
        settings_instance.google_api_key = None
        settings_instance.anthropic_api_key = None
        mock_settings.return_value = settings_instance

        with pytest.raises(ValueError, match="No vision API configured"):
            analyze_image("test.jpg")


def test_analyze_image_both_fail(mock_settings_both, test_image_path):
    """Test unified analysis when both APIs fail"""
    with patch('google.genai.Client') as mock_gemini_class:
        with patch('anthropic.Anthropic') as mock_claude_class:
            # Both fail
            mock_gemini_client = Mock()
            mock_gemini_client.models.generate_content.side_effect = Exception("Gemini error")
            mock_gemini_class.return_value = mock_gemini_client

            mock_claude_client = Mock()
            mock_claude_client.messages.create.side_effect = Exception("Claude error")
            mock_claude_class.return_value = mock_claude_client

            with pytest.raises(Exception, match="both failed"):
                analyze_image(test_image_path)