84 lines
2.3 KiB
Python
84 lines
2.3 KiB
Python
"""Test API functionality."""
|
|
import pytest
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
from custom_components.adguard_hub.api import AdGuardHomeAPI
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_session():
|
|
"""Mock aiohttp session with proper async context manager."""
|
|
session = MagicMock()
|
|
response = MagicMock()
|
|
response.raise_for_status = MagicMock()
|
|
response.json = AsyncMock(return_value={"status": "ok"})
|
|
response.status = 200
|
|
response.content_length = 100
|
|
|
|
# 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(return_value=context_manager)
|
|
|
|
return session
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_connection(mock_session):
|
|
"""Test API connection."""
|
|
api = AdGuardHomeAPI(
|
|
host="test-host",
|
|
port=3000,
|
|
username="admin",
|
|
password="password",
|
|
session=mock_session
|
|
)
|
|
|
|
result = await api.test_connection()
|
|
assert result is True
|
|
mock_session.request.assert_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_get_status(mock_session):
|
|
"""Test getting status."""
|
|
api = AdGuardHomeAPI(
|
|
host="test-host",
|
|
port=3000,
|
|
session=mock_session
|
|
)
|
|
|
|
status = await api.get_status()
|
|
assert status == {"status": "ok"}
|
|
mock_session.request.assert_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_context_manager():
|
|
"""Test API as async context manager."""
|
|
async with AdGuardHomeAPI(host="test-host", port=3000) as api:
|
|
assert api is not None
|
|
assert api.host == "test-host"
|
|
assert api.port == 3000
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_error_handling():
|
|
"""Test API error handling."""
|
|
# Test with a session that raises an exception
|
|
session = MagicMock()
|
|
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",
|
|
port=3000,
|
|
session=session
|
|
)
|
|
|
|
with pytest.raises(Exception):
|
|
await api.get_status()
|