File size: 6,968 Bytes
8cbe6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Integration tests for GoogleSpeechProvider with the provider manager system.

This module tests the integration of GoogleSpeechProvider with other components
in the voice control system.
"""

import pytest
from unittest.mock import Mock, patch
import asyncio

from voice_control.providers.google_speech_provider import (
    GoogleSpeechProvider, 
    create_google_speech_provider
)
from voice_control.provider_manager import ProviderManager
from voice_control.models import (
    ProviderConfig, 
    ProviderType, 
    TranscriptionResult
)


class TestGoogleSpeechProviderIntegration:
    """Integration tests for GoogleSpeechProvider."""
    
    @pytest.fixture
    def mock_google_speech(self):
        """Mock Google Cloud Speech modules."""
        with patch('voice_control.providers.google_speech_provider.GOOGLE_SPEECH_AVAILABLE', True):
            with patch('voice_control.providers.google_speech_provider.speech') as mock_speech:
                with patch('voice_control.providers.google_speech_provider.service_account') as mock_sa:
                    # Setup mock speech client
                    mock_client = Mock()
                    mock_speech.SpeechClient.return_value = mock_client
                    
                    # Setup mock recognition config
                    mock_config = Mock()
                    mock_speech.RecognitionConfig.return_value = mock_config
                    mock_speech.RecognitionConfig.AudioEncoding = Mock()
                    mock_speech.RecognitionConfig.AudioEncoding.LINEAR16 = "LINEAR16"
                    
                    # Setup mock audio
                    mock_audio = Mock()
                    mock_speech.RecognitionAudio.return_value = mock_audio
                    
                    yield {
                        'speech': mock_speech,
                        'service_account': mock_sa,
                        'client': mock_client
                    }
    
    @pytest.mark.asyncio
    async def test_provider_manager_integration(self, mock_google_speech):
        """Test GoogleSpeechProvider integration with ProviderManager."""
        # Create Google Speech provider
        provider = create_google_speech_provider(
            name="test_google_speech",
            priority=2,
            api_credentials={"service_account_key": "test_key"}
        )
        
        # Create provider manager
        manager = ProviderManager()
        
        # Register the provider
        await manager.register_provider(provider)
        
        # Mock successful transcription
        mock_alternative = Mock()
        mock_alternative.transcript = "Hello from Google Speech"
        mock_alternative.confidence = 0.95
        mock_alternative.words = []
        
        mock_result = Mock()
        mock_result.alternatives = [mock_alternative]
        
        mock_response = Mock()
        mock_response.results = [mock_result]
        
        mock_google_speech['client'].recognize.return_value = mock_response
        
        # Test transcription through provider manager
        audio_data = b'\x00\x01' * 1000
        result = await manager.transcribe_audio(audio_data, "wav", "en-US")
        
        # Verify result
        assert isinstance(result, TranscriptionResult)
        assert result.text == "Hello from Google Speech"
        assert result.confidence == 0.95
        assert result.provider == "test_google_speech"
        assert result.language == "en-US"
    
    @pytest.mark.asyncio
    async def test_quota_management_integration(self, mock_google_speech):
        """Test quota management integration."""
        provider = create_google_speech_provider(
            api_credentials={"service_account_key": "test"}
        )
        
        # Mock successful responses
        mock_alternative = Mock()
        mock_alternative.transcript = "Test"
        mock_alternative.confidence = 0.9
        mock_alternative.words = []
        
        mock_result = Mock()
        mock_result.alternatives = [mock_alternative]
        
        mock_response = Mock()
        mock_response.results = [mock_result]
        
        mock_google_speech['client'].recognize.return_value = mock_response
        
        # Make multiple requests to test quota tracking
        audio_data = b'\x00\x01' * 500
        for i in range(3):
            result = await provider.transcribe_audio(audio_data, "wav", "en-US")
            assert result.text == "Test"
        
        # Check quota status
        quota_status = await provider.get_quota_status()
        
        # Verify quota tracking
        assert quota_status["requests_per_minute"].current_usage == 3
        assert quota_status["audio_minutes_per_month"].current_usage > 0
        
        # Verify cost estimation
        cost = await provider.estimate_cost(300)  # 5 minutes
        assert cost == 0.0  # Should be free within tier
    
    @pytest.mark.asyncio
    async def test_error_handling_integration(self, mock_google_speech):
        """Test error handling integration."""
        provider = create_google_speech_provider(
            api_credentials={"service_account_key": "test"}
        )
        
        # Test unsupported format
        with pytest.raises(Exception):  # Should raise UnsupportedFormatError
            await provider.transcribe_audio(b'test', "unsupported_format")
        
        # Test unsupported language
        with pytest.raises(Exception):  # Should raise UnsupportedLanguageError
            await provider.transcribe_audio(b'test', "wav", "xx-XX")
    
    @pytest.mark.asyncio
    async def test_health_check_integration(self, mock_google_speech):
        """Test health check integration."""
        provider = create_google_speech_provider(
            api_credentials={"service_account_key": "test"}
        )
        
        # Mock successful health check
        mock_response = Mock()
        mock_google_speech['client'].recognize.return_value = mock_response
        
        health = await provider.check_health()
        assert health is True
        
        # Mock failed health check
        mock_google_speech['client'].recognize.side_effect = Exception("API Error")
        
        health = await provider.check_health()
        assert health is False
    
    def test_factory_function(self, mock_google_speech):
        """Test the factory function creates provider correctly."""
        provider = create_google_speech_provider(
            name="custom_google",
            priority=5,
            api_credentials={"service_account_key": "test_key"}
        )
        
        assert provider.name == "custom_google"
        assert provider.config.priority == 5
        assert provider.config.api_credentials["service_account_key"] == "test_key"
        assert provider.config.provider_type == ProviderType.GOOGLE_SPEECH
        assert provider.supports_format("wav")
        assert provider.supports_language("en-US")