@@ -1,12 +1,12 @@
|
||||
"""Test API functionality."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from custom_components.adguard_hub.api import AdGuardHomeAPI
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_session():
|
||||
"""Mock aiohttp session."""
|
||||
"""Mock aiohttp session with proper async context manager."""
|
||||
session = MagicMock()
|
||||
response = MagicMock()
|
||||
response.raise_for_status = MagicMock()
|
||||
@@ -14,13 +14,12 @@ def mock_session():
|
||||
response.status = 200
|
||||
response.content_length = 100
|
||||
|
||||
# Create async context manager for session.request
|
||||
async def mock_request(*args, **kwargs):
|
||||
return response
|
||||
# Properly mock the async context manager
|
||||
context_manager = MagicMock()
|
||||
context_manager.__aenter__ = AsyncMock(return_value=response)
|
||||
context_manager.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
session.request = MagicMock()
|
||||
session.request.return_value.__aenter__ = AsyncMock(return_value=response)
|
||||
session.request.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
session.request = MagicMock(return_value=context_manager)
|
||||
|
||||
return session
|
||||
|
||||
@@ -38,6 +37,7 @@ async def test_api_connection(mock_session):
|
||||
|
||||
result = await api.test_connection()
|
||||
assert result is True
|
||||
mock_session.request.assert_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -51,6 +51,7 @@ async def test_api_get_status(mock_session):
|
||||
|
||||
status = await api.get_status()
|
||||
assert status == {"status": "ok"}
|
||||
mock_session.request.assert_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -65,13 +66,12 @@ async def test_api_context_manager():
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_error_handling():
|
||||
"""Test API error handling."""
|
||||
from custom_components.adguard_hub.api import AdGuardConnectionError
|
||||
|
||||
# Test with a session that raises an exception
|
||||
session = MagicMock()
|
||||
session.request = MagicMock()
|
||||
session.request.return_value.__aenter__ = AsyncMock(side_effect=Exception("Connection error"))
|
||||
session.request.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
context_manager = MagicMock()
|
||||
context_manager.__aenter__ = AsyncMock(side_effect=Exception("Connection error"))
|
||||
context_manager.__aexit__ = AsyncMock(return_value=None)
|
||||
session.request = MagicMock(return_value=context_manager)
|
||||
|
||||
api = AdGuardHomeAPI(
|
||||
host="test-host",
|
||||
@@ -79,5 +79,5 @@ async def test_api_error_handling():
|
||||
session=session
|
||||
)
|
||||
|
||||
with pytest.raises(Exception): # Should raise AdGuardHomeError
|
||||
with pytest.raises(Exception):
|
||||
await api.get_status()
|
||||
|
Reference in New Issue
Block a user