Spaces:
Runtime error
Runtime error
File size: 25,534 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 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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | """
Unit tests for GoogleSpeechProvider.
This module contains comprehensive tests for the Google Speech-to-Text provider
implementation, including quota management, error handling, and transcription
functionality.
"""
import pytest
import asyncio
from unittest.mock import Mock, AsyncMock, patch, MagicMock
from datetime import datetime, timezone, timedelta
import json
from voice_control.providers.google_speech_provider import (
GoogleSpeechProvider,
create_google_speech_provider,
GOOGLE_SPEECH_AVAILABLE
)
from voice_control.models import (
ProviderConfig,
ProviderType,
TranscriptionResult,
QuotaStatus,
QuotaType,
WordTimestamp
)
from voice_control.exceptions import (
ProviderError,
ProviderUnavailableError,
ProviderAuthenticationError,
UnsupportedFormatError,
UnsupportedLanguageError,
QuotaExceededError,
RateLimitExceededError,
TranscriptionError
)
class TestGoogleSpeechProvider:
"""Test cases for GoogleSpeechProvider class."""
@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:
with patch('voice_control.providers.google_speech_provider.google_exceptions') as mock_exc:
# 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"
mock_speech.RecognitionConfig.AudioEncoding.FLAC = "FLAC"
mock_speech.RecognitionConfig.AudioEncoding.MP3 = "MP3"
mock_speech.RecognitionConfig.AudioEncoding.WEBM_OPUS = "WEBM_OPUS"
# Setup mock audio
mock_audio = Mock()
mock_speech.RecognitionAudio.return_value = mock_audio
# Setup mock streaming config
mock_streaming_config = Mock()
mock_speech.StreamingRecognitionConfig.return_value = mock_streaming_config
# Setup mock streaming request
mock_streaming_request = Mock()
mock_speech.StreamingRecognizeRequest.return_value = mock_streaming_request
yield {
'speech': mock_speech,
'service_account': mock_sa,
'exceptions': mock_exc,
'client': mock_client
}
@pytest.fixture
def provider_config(self):
"""Create a test provider configuration."""
return ProviderConfig(
name="test_google_speech",
provider_type=ProviderType.GOOGLE_SPEECH,
enabled=True,
priority=2,
free_tier_limits={
"audio_minutes_per_month": 60.0,
"requests_per_minute": 1000,
"requests_per_day": 50000
},
rate_limits={
"requests_per_minute": 1000,
"requests_per_day": 50000
},
supported_formats=["wav", "flac", "mp3", "webm"],
supported_languages=["en-US", "es-ES", "fr-FR"],
cost_per_minute=0.006,
api_credentials={
"service_account_key": '{"type": "service_account", "project_id": "test"}'
},
timeout_seconds=60,
max_retries=3
)
@pytest.fixture
def sample_audio_data(self):
"""Create sample audio data for testing."""
return b'\x00\x01' * 8000 # 16KB of sample audio data
def test_provider_initialization_without_library(self):
"""Test provider initialization when Google Speech library is not available."""
with patch('voice_control.providers.google_speech_provider.GOOGLE_SPEECH_AVAILABLE', False):
config = ProviderConfig(
name="test",
provider_type=ProviderType.GOOGLE_SPEECH,
enabled=True,
priority=1,
free_tier_limits={},
rate_limits={},
supported_formats=["wav"],
supported_languages=["en-US"],
cost_per_minute=0.0,
api_credentials={}
)
with pytest.raises(ImportError, match="Google Cloud Speech library not available"):
GoogleSpeechProvider(config)
def test_provider_initialization_invalid_type(self, mock_google_speech):
"""Test provider initialization with invalid provider type."""
config = ProviderConfig(
name="invalid",
provider_type=ProviderType.WEB_SPEECH_API, # Wrong type
enabled=True,
priority=1,
free_tier_limits={},
rate_limits={},
supported_formats=["wav"],
supported_languages=["en-US"],
cost_per_minute=0.0,
api_credentials={}
)
with pytest.raises(ValueError, match="Invalid provider type"):
GoogleSpeechProvider(config)
@pytest.mark.asyncio
async def test_provider_initialization_success(self, mock_google_speech, provider_config):
"""Test successful provider initialization."""
provider = GoogleSpeechProvider(provider_config)
# Wait for initialization to complete
await asyncio.sleep(0.1)
assert provider.name == "test_google_speech"
assert provider.provider_type == ProviderType.GOOGLE_SPEECH
assert provider.config == provider_config
def test_supports_format(self, mock_google_speech, provider_config):
"""Test format support checking."""
provider = GoogleSpeechProvider(provider_config)
# Test supported formats
assert provider.supports_format("wav")
assert provider.supports_format("WAV") # Case insensitive
assert provider.supports_format("flac")
assert provider.supports_format("mp3")
assert provider.supports_format("webm")
# Test unsupported formats
assert not provider.supports_format("aac")
assert not provider.supports_format("m4a")
assert not provider.supports_format("unknown")
def test_supports_language(self, mock_google_speech, provider_config):
"""Test language support checking."""
provider = GoogleSpeechProvider(provider_config)
# Test supported languages
assert provider.supports_language("en-US")
assert provider.supports_language("es-ES")
assert provider.supports_language("fr-FR")
assert provider.supports_language("de-DE")
assert provider.supports_language("ja-JP")
# Test unsupported languages
assert not provider.supports_language("xx-XX")
assert not provider.supports_language("invalid")
@pytest.mark.asyncio
async def test_estimate_cost_free_tier(self, mock_google_speech, provider_config):
"""Test cost estimation within free tier."""
provider = GoogleSpeechProvider(provider_config)
# Test within free tier (60 minutes/month)
cost = await provider.estimate_cost(1800) # 30 minutes
assert cost == 0.0
# Test at free tier limit
cost = await provider.estimate_cost(3600) # 60 minutes
assert cost == 0.0
@pytest.mark.asyncio
async def test_estimate_cost_exceeding_free_tier(self, mock_google_speech, provider_config):
"""Test cost estimation exceeding free tier."""
provider = GoogleSpeechProvider(provider_config)
# Simulate some usage
provider._usage_stats["audio_minutes_this_month"] = 50.0 # 50 minutes used
# Test exceeding free tier
cost = await provider.estimate_cost(1800) # 30 minutes (20 minutes over limit)
expected_cost = 20.0 * 0.006 # 20 minutes at $0.006/minute
assert abs(cost - expected_cost) < 0.001
@pytest.mark.asyncio
async def test_check_health_success(self, mock_google_speech, provider_config):
"""Test successful health check."""
provider = GoogleSpeechProvider(provider_config)
# Mock successful recognition
mock_response = Mock()
mock_google_speech['client'].recognize.return_value = mock_response
health = await provider.check_health()
assert health is True
@pytest.mark.asyncio
async def test_check_health_failure(self, mock_google_speech, provider_config):
"""Test health check failure."""
provider = GoogleSpeechProvider(provider_config)
# Mock recognition failure
mock_google_speech['client'].recognize.side_effect = Exception("API Error")
health = await provider.check_health()
assert health is False
@pytest.mark.asyncio
async def test_get_quota_status(self, mock_google_speech, provider_config):
"""Test quota status retrieval."""
provider = GoogleSpeechProvider(provider_config)
# Set some usage
provider._usage_stats["requests_this_minute"] = 10
provider._usage_stats["requests_today"] = 100
provider._usage_stats["audio_minutes_this_month"] = 15.5
quota_status = await provider.get_quota_status()
assert "requests_per_minute" in quota_status
assert "requests_per_day" in quota_status
assert "audio_minutes_per_month" in quota_status
# Check requests per minute
rpm_status = quota_status["requests_per_minute"]
assert rpm_status.provider == provider.name
assert rpm_status.quota_type == QuotaType.REQUESTS_PER_MINUTE
assert rpm_status.current_usage == 10
assert rpm_status.limit == 1000
# Check audio minutes per month
ampm_status = quota_status["audio_minutes_per_month"]
assert ampm_status.current_usage == 15.5
assert ampm_status.limit == 60.0
assert abs(ampm_status.percentage_used - (15.5 / 60.0)) < 0.001
@pytest.mark.asyncio
async def test_transcribe_audio_unsupported_format(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription with unsupported format."""
provider = GoogleSpeechProvider(provider_config)
with pytest.raises(UnsupportedFormatError):
await provider.transcribe_audio(sample_audio_data, "aac")
@pytest.mark.asyncio
async def test_transcribe_audio_unsupported_language(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription with unsupported language."""
provider = GoogleSpeechProvider(provider_config)
with pytest.raises(UnsupportedLanguageError):
await provider.transcribe_audio(sample_audio_data, "wav", "xx-XX")
@pytest.mark.asyncio
async def test_transcribe_audio_quota_exceeded(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription when quota is exceeded."""
provider = GoogleSpeechProvider(provider_config)
# Set usage to exceed monthly limit
provider._usage_stats["audio_minutes_this_month"] = 59.5 # Close to 60 minute limit
with pytest.raises(QuotaExceededError):
await provider.transcribe_audio(sample_audio_data, "wav", audio_duration=120) # 2 minutes
@pytest.mark.asyncio
async def test_transcribe_audio_rate_limit_exceeded(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription when rate limit is exceeded."""
provider = GoogleSpeechProvider(provider_config)
# Set usage to exceed per-minute limit
provider._usage_stats["requests_this_minute"] = 1000
with pytest.raises(RateLimitExceededError):
await provider.transcribe_audio(sample_audio_data, "wav")
@pytest.mark.asyncio
async def test_transcribe_audio_success(self, mock_google_speech, provider_config, sample_audio_data):
"""Test successful audio transcription."""
provider = GoogleSpeechProvider(provider_config)
# Mock successful recognition response
mock_alternative = Mock()
mock_alternative.transcript = "Hello world"
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
result = await provider.transcribe_audio(sample_audio_data, "wav", "en-US")
assert isinstance(result, TranscriptionResult)
assert result.text == "Hello world"
assert result.confidence == 0.95
assert result.provider == provider.name
assert result.language == "en-US"
assert result.is_final is True
@pytest.mark.asyncio
async def test_transcribe_audio_with_word_timestamps(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription with word timestamps."""
provider = GoogleSpeechProvider(provider_config)
# Mock word info
mock_word1 = Mock()
mock_word1.word = "Hello"
mock_word1.start_time = Mock()
mock_word1.start_time.total_seconds.return_value = 0.0
mock_word1.end_time = Mock()
mock_word1.end_time.total_seconds.return_value = 0.5
mock_word1.confidence = 0.98
mock_word2 = Mock()
mock_word2.word = "world"
mock_word2.start_time = Mock()
mock_word2.start_time.total_seconds.return_value = 0.6
mock_word2.end_time = Mock()
mock_word2.end_time.total_seconds.return_value = 1.0
mock_word2.confidence = 0.92
mock_alternative = Mock()
mock_alternative.transcript = "Hello world"
mock_alternative.confidence = 0.95
mock_alternative.words = [mock_word1, mock_word2]
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
result = await provider.transcribe_audio(
sample_audio_data,
"wav",
"en-US",
enable_word_time_offsets=True
)
assert result.word_timestamps is not None
assert len(result.word_timestamps) == 2
word1 = result.word_timestamps[0]
assert word1.word == "Hello"
assert word1.start_time == 0.0
assert word1.end_time == 0.5
assert word1.confidence == 0.98
word2 = result.word_timestamps[1]
assert word2.word == "world"
assert word2.start_time == 0.6
assert word2.end_time == 1.0
assert word2.confidence == 0.92
@pytest.mark.asyncio
async def test_transcribe_audio_empty_response(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription with empty response."""
provider = GoogleSpeechProvider(provider_config)
# Mock empty response
mock_response = Mock()
mock_response.results = []
mock_google_speech['client'].recognize.return_value = mock_response
result = await provider.transcribe_audio(sample_audio_data, "wav", "en-US")
assert result.text == ""
assert result.confidence == 0.0
assert result.provider == provider.name
@pytest.mark.asyncio
async def test_transcribe_audio_google_api_error(self, mock_google_speech, provider_config, sample_audio_data):
"""Test transcription with Google API error."""
provider = GoogleSpeechProvider(provider_config)
# Mock Google API error
mock_error = Mock()
mock_error.code = 401
mock_google_speech['client'].recognize.side_effect = mock_error
with pytest.raises(ProviderAuthenticationError):
await provider.transcribe_audio(sample_audio_data, "wav", "en-US")
@pytest.mark.asyncio
async def test_transcribe_streaming_unsupported_format(self, mock_google_speech, provider_config):
"""Test streaming transcription with unsupported format."""
provider = GoogleSpeechProvider(provider_config)
async def mock_audio_stream():
yield b'audio_chunk'
with pytest.raises(UnsupportedFormatError):
async for _ in provider.transcribe_streaming(mock_audio_stream(), "aac"):
pass
@pytest.mark.asyncio
async def test_transcribe_streaming_success(self, mock_google_speech, provider_config):
"""Test successful streaming transcription."""
provider = GoogleSpeechProvider(provider_config)
# Mock streaming response
mock_alternative = Mock()
mock_alternative.transcript = "Streaming text"
mock_alternative.confidence = 0.85
mock_result = Mock()
mock_result.alternatives = [mock_alternative]
mock_result.is_final = True
mock_response = Mock()
mock_response.results = [mock_result]
mock_google_speech['client'].streaming_recognize.return_value = [mock_response]
async def mock_audio_stream():
yield b'audio_chunk_1'
yield b'audio_chunk_2'
results = []
async for result in provider.transcribe_streaming(mock_audio_stream(), "wav", "en-US"):
results.append(result)
assert len(results) == 1
assert results[0].text == "Streaming text"
assert results[0].confidence == 0.85
assert results[0].is_final is True
@pytest.mark.asyncio
async def test_usage_stats_reset(self, mock_google_speech, provider_config):
"""Test usage statistics reset functionality."""
provider = GoogleSpeechProvider(provider_config)
# Set usage stats to old values
old_time = datetime.now(timezone.utc) - timedelta(days=2)
provider._usage_stats["last_daily_reset"] = old_time.date()
provider._usage_stats["requests_today"] = 100
# Trigger reset by calling _reset_counters_if_needed
await provider._reset_counters_if_needed()
# Check that daily counter was reset
assert provider._usage_stats["requests_today"] == 0
assert provider._usage_stats["last_daily_reset"] == datetime.now(timezone.utc).date()
def test_create_google_speech_provider_factory(self, mock_google_speech):
"""Test the factory function for creating GoogleSpeechProvider."""
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
class TestGoogleSpeechProviderIntegration:
"""Integration tests for GoogleSpeechProvider."""
@pytest.fixture
def mock_google_speech_integration(self):
"""Mock Google Cloud Speech modules for integration tests."""
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:
with patch('voice_control.providers.google_speech_provider.google_exceptions') as mock_exc:
# 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,
'exceptions': mock_exc,
'client': mock_client
}
@pytest.mark.asyncio
async def test_full_transcription_workflow(self, mock_google_speech_integration):
"""Test complete transcription workflow."""
# Create provider with realistic config
config = ProviderConfig(
name="integration_test",
provider_type=ProviderType.GOOGLE_SPEECH,
enabled=True,
priority=2,
free_tier_limits={
"audio_minutes_per_month": 60.0,
"requests_per_minute": 1000,
"requests_per_day": 50000
},
rate_limits={
"requests_per_minute": 1000,
"requests_per_day": 50000
},
supported_formats=["wav", "mp3", "flac"],
supported_languages=["en-US", "es-ES"],
cost_per_minute=0.006,
api_credentials={
"service_account_key": '{"type": "service_account", "project_id": "test"}'
}
)
provider = GoogleSpeechProvider(config)
# Mock successful transcription
mock_alternative = Mock()
mock_alternative.transcript = "Integration test successful"
mock_alternative.confidence = 0.92
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
audio_data = b'\x00\x01' * 4000 # 8KB sample
result = await provider.transcribe_audio(audio_data, "wav", "en-US")
# Verify result
assert result.text == "Integration test successful"
assert result.confidence == 0.92
assert result.provider == "integration_test"
assert result.language == "en-US"
# Check that usage was tracked
quota_status = await provider.get_quota_status()
assert quota_status["requests_per_minute"].current_usage == 1
assert quota_status["audio_minutes_per_month"].current_usage > 0
@pytest.mark.asyncio
async def test_quota_management_workflow(self, mock_google_speech):
"""Test quota management across multiple requests."""
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
audio_data = b'\x00\x01' * 1000
for i in range(5):
result = await provider.transcribe_audio(audio_data, "wav", "en-US")
assert result.text == "Test"
# Check quota tracking
quota_status = await provider.get_quota_status()
assert quota_status["requests_per_minute"].current_usage == 5
# Verify cost estimation
cost = await provider.estimate_cost(300) # 5 minutes
assert cost == 0.0 # Should be free within tier |