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
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import pytest
from unittest.mock import AsyncMock, patch
pytest.importorskip(
"aiohttp",
reason="Skipping aio tests: aiohttp not installed (whl_no_aio).",
)
from azure.ai.voicelive.aio import (
VoiceLiveConnection,
SessionResource,
ResponseResource,
ConnectionError,
ConnectionClosed,
)
from azure.ai.voicelive.models import (
ClientEventSessionUpdate,
ClientEventResponseCreate,
ClientEventResponseCancel,
RequestSession,
ResponseCreateParams,
Modality,
OpenAIVoiceName,
OpenAIVoice,
)
from azure.core.credentials import AzureKeyCredential
class TestConnectionExceptions:
"""Test connection exception classes."""
def test_connection_error_creation(self):
"""Test ConnectionError exception creation."""
error = ConnectionError("Test connection error")
assert str(error) == "Test connection error"
assert isinstance(error, Exception)
def test_connection_closed_creation(self):
"""Test ConnectionClosed exception creation."""
error = ConnectionClosed(code=1000, reason="Normal closure")
assert error.code == 1000
assert error.reason == "Normal closure"
assert "WebSocket connection closed with code 1000: Normal closure" in str(error)
assert isinstance(error, ConnectionError)
def test_connection_closed_inheritance(self):
"""Test that ConnectionClosed inherits from ConnectionError."""
error = ConnectionClosed(code=1001, reason="Going away")
assert isinstance(error, ConnectionError)
assert isinstance(error, Exception)
class TestSessionResource:
"""Test SessionResource class."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_connection = AsyncMock()
self.session_resource = SessionResource(self.mock_connection)
@pytest.mark.asyncio
async def test_session_update_with_request_session(self):
"""Test session update with RequestSession object."""
session = RequestSession(model="gpt-4o-realtime-preview", modalities=[Modality.TEXT, Modality.AUDIO])
await self.session_resource.update(session=session)
# Verify that send was called with correct event type
self.mock_connection.send.assert_called_once()
call_args = self.mock_connection.send.call_args[0][0]
assert isinstance(call_args, ClientEventSessionUpdate)
@pytest.mark.asyncio
async def test_session_update_with_mapping(self):
"""Test session update with dictionary mapping."""
session_dict = {"model": "gpt-4o-realtime-preview", "modalities": ["text", "audio"], "temperature": 0.7}
await self.session_resource.update(session=session_dict)
# Verify that send was called
self.mock_connection.send.assert_called_once()
call_args = self.mock_connection.send.call_args[0][0]
assert isinstance(call_args, ClientEventSessionUpdate)
@pytest.mark.asyncio
async def test_session_update_with_event_id(self):
"""Test session update with event ID."""
session = RequestSession(model="gpt-4o-realtime-preview")
event_id = "test-event-123"
await self.session_resource.update(session=session, event_id=event_id)
# Verify that send was called
self.mock_connection.send.assert_called_once()
class TestResponseResource:
"""Test ResponseResource class."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_connection = AsyncMock()
self.response_resource = ResponseResource(self.mock_connection)
@pytest.mark.asyncio
async def test_response_create_basic(self):
"""Test basic response creation."""
await self.response_resource.create()
# Verify that send was called with correct event type
self.mock_connection.send.assert_called_once()
call_args = self.mock_connection.send.call_args[0][0]
assert isinstance(call_args, ClientEventResponseCreate)
@pytest.mark.asyncio
async def test_response_create_with_params(self):
"""Test response creation with parameters."""
response_params = ResponseCreateParams()
event_id = "response-event-123"
instructions = "Additional instructions for this response"
await self.response_resource.create(
response=response_params, event_id=event_id, additional_instructions=instructions
)
# Verify that send was called
self.mock_connection.send.assert_called_once()
call_args = self.mock_connection.send.call_args[0][0]
assert isinstance(call_args, ClientEventResponseCreate)
@pytest.mark.asyncio
async def test_response_create_with_dict(self):
"""Test response creation with dictionary parameters."""
response_dict = {"modalities": ["text"]}
await self.response_resource.create(response=response_dict)
# Verify that send was called
self.mock_connection.send.assert_called_once()
@pytest.mark.asyncio
async def test_response_cancel_basic(self):
"""Test basic response cancellation."""
await self.response_resource.cancel()
# Verify that send was called with correct event type
self.mock_connection.send.assert_called_once()
call_args = self.mock_connection.send.call_args[0][0]
assert isinstance(call_args, ClientEventResponseCancel)
@pytest.mark.asyncio
async def test_response_cancel_with_params(self):
"""Test response cancellation with parameters."""
response_id = "response-123"
event_id = "cancel-event-456"
await self.response_resource.cancel(response_id=response_id, event_id=event_id)
# Verify that send was called
self.mock_connection.send.assert_called_once()
@pytest.mark.asyncio
class TestVoiceLiveConnectionMocked:
"""Test VoiceLiveConnection with mocked WebSocket."""
def setup_method(self):
"""Set up test fixtures."""
self.credential = AzureKeyCredential("test-key")
self.endpoint = "wss://test-endpoint.com"
@patch("azure.ai.voicelive.aio._patch.aiohttp.ClientSession.ws_connect")
async def test_connection_initialization(self, mock_ws_connect):
"""Test connection initialization."""
# Mock WebSocket connection
mock_ws = AsyncMock()
mock_ws_connect.return_value.__aenter__.return_value = mock_ws
# This would typically be done through the connect() function
# but we're testing the class directly here
connection = VoiceLiveConnection(self.endpoint, self.credential)
# Verify connection object creation
assert connection is not None
assert hasattr(connection, "session")
assert hasattr(connection, "response")
async def test_session_resource_creation(self):
"""Test that session resource is created correctly."""
connection = VoiceLiveConnection(self.endpoint, self.credential)
assert isinstance(connection.session, SessionResource)
assert connection.session._connection is connection
async def test_response_resource_creation(self):
"""Test that response resource is created correctly."""
connection = VoiceLiveConnection(self.endpoint, self.credential)
assert isinstance(connection.response, ResponseResource)
assert connection.response._connection is connection
class TestVoiceLiveConnectionIntegration:
"""Integration tests for VoiceLiveConnection."""
@pytest.mark.asyncio
async def test_connection_context_manager(self):
"""Test that VoiceLiveConnection can be used as async context manager."""
credential = AzureKeyCredential("test-key")
endpoint = "wss://test-endpoint.com"
# Mock the WebSocket connection
with patch("azure.ai.voicelive.aio._patch.aiohttp.ClientSession.ws_connect") as mock_ws_connect:
mock_ws = AsyncMock()
mock_ws_connect.return_value.__aenter__.return_value = mock_ws
try:
# This is how the connection would typically be used
connection = VoiceLiveConnection(endpoint, credential)
# Test that resources are available
assert hasattr(connection, "session")
assert hasattr(connection, "response")
except Exception as e:
# If the connection setup fails due to mocking limitations,
# that's expected in unit tests
pytest.skip(f"Connection setup failed in test environment: {e}")
@pytest.mark.asyncio
async def test_send_message_flow(self):
"""Test sending a message through the connection."""
credential = AzureKeyCredential("test-key")
endpoint = "wss://test-endpoint.com"
with patch("azure.ai.voicelive.aio._patch.aiohttp.ClientSession.ws_connect") as mock_ws_connect:
mock_ws = AsyncMock()
mock_ws_connect.return_value.__aenter__.return_value = mock_ws
try:
connection = VoiceLiveConnection(endpoint, credential)
# Test session update
session = RequestSession(model="gpt-4o-realtime-preview", voice=OpenAIVoice(name=OpenAIVoiceName.ALLOY))
# Mock the send method
connection.send = AsyncMock()
await connection.session.update(session=session)
# Verify send was called
connection.send.assert_called_once()
except Exception as e:
pytest.skip(f"Connection flow test failed in test environment: {e}")
class TestConnectionResourceInteraction:
"""Test interaction between connection and resources."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_connection = AsyncMock()
self.mock_connection.send = AsyncMock()
@pytest.mark.asyncio
async def test_session_and_response_interaction(self):
"""Test interaction between session and response resources."""
session_resource = SessionResource(self.mock_connection)
response_resource = ResponseResource(self.mock_connection)
# Update session
session = RequestSession(model="gpt-4o-realtime-preview", temperature=0.8)
await session_resource.update(session=session)
# Create response
await response_resource.create(additional_instructions="Be concise")
# Verify both operations called send
assert self.mock_connection.send.call_count == 2
@pytest.mark.asyncio
async def test_multiple_session_updates(self):
"""Test multiple session updates."""
session_resource = SessionResource(self.mock_connection)
# First update
session1 = RequestSession(model="gpt-4o-realtime-preview")
await session_resource.update(session=session1, event_id="update-1")
# Second update
session2 = RequestSession(model="gpt-4o-realtime-preview", temperature=0.5)
await session_resource.update(session=session2, event_id="update-2")
# Verify both updates were sent
assert self.mock_connection.send.call_count == 2
@pytest.mark.asyncio
async def test_response_create_and_cancel(self):
"""Test creating and then canceling a response."""
response_resource = ResponseResource(self.mock_connection)
# Create response
await response_resource.create(event_id="create-1")
# Cancel response
await response_resource.cancel(response_id="response-123", event_id="cancel-1")
# Verify both operations were sent
assert self.mock_connection.send.call_count == 2
class TestConnectionErrorScenarios:
"""Test various error scenarios."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_connection = AsyncMock()
@pytest.mark.asyncio
async def test_connection_send_failure(self):
"""Test handling of connection send failures."""
self.mock_connection.send.side_effect = ConnectionError("Send failed")
session_resource = SessionResource(self.mock_connection)
with pytest.raises(ConnectionError):
session = RequestSession(model="gpt-4o-realtime-preview")
await session_resource.update(session=session)
@pytest.mark.asyncio
async def test_connection_closed_during_operation(self):
"""Test handling of connection closure during operations."""
self.mock_connection.send.side_effect = ConnectionClosed(1000, "Normal closure")
response_resource = ResponseResource(self.mock_connection)
with pytest.raises(ConnectionClosed) as exc_info:
await response_resource.create()
assert exc_info.value.code == 1000
assert exc_info.value.reason == "Normal closure"
@pytest.mark.asyncio
async def test_invalid_session_parameters(self):
"""Test handling of invalid session parameters."""
session_resource = SessionResource(self.mock_connection)
# Test with None session (should raise TypeError or similar)
with pytest.raises((TypeError, AttributeError)):
await session_resource.update(session=None)
class TestAsyncContextBehavior:
"""Test async context manager behavior."""
@pytest.mark.asyncio
async def test_resource_lifecycle(self):
"""Test resource lifecycle management."""
mock_connection = AsyncMock()
session_resource = SessionResource(mock_connection)
response_resource = ResponseResource(mock_connection)
# Verify resources maintain connection reference
assert session_resource._connection is mock_connection
assert response_resource._connection is mock_connection
# Verify resources can be used independently
session = RequestSession(model="test-model")
await session_resource.update(session=session)
await response_resource.create()
assert mock_connection.send.call_count == 2
|