refactor: another refactor
Some checks failed
Integration Testing / Integration Tests (2024.12.0, 3.11) (push) Failing after 27s
Integration Testing / Integration Tests (2024.12.0, 3.12) (push) Failing after 56s
Integration Testing / Integration Tests (2024.12.0, 3.13) (push) Failing after 1m38s
Integration Testing / Integration Tests (2025.9.4, 3.11) (push) Failing after 19s
Integration Testing / Integration Tests (2025.9.4, 3.12) (push) Failing after 20s
Integration Testing / Integration Tests (2025.9.4, 3.13) (push) Failing after 25s
Code Quality Check / Code Quality Analysis (push) Failing after 20s
Code Quality Check / Security Analysis (push) Failing after 21s

Signed-off-by: Rafal Zielinski <sq4ind@gmail.com>
This commit is contained in:
2025-09-28 17:01:21 +01:00
parent 1aad59c582
commit 554b8ac16b
25 changed files with 464 additions and 543 deletions

View File

@@ -1 +1 @@
"""Tests for AdGuard Control Hub integration."""
"""Tests for AdGuard Control Hub."""

View File

@@ -1,5 +1,12 @@
"""Test configuration and fixtures."""
import pytest
from unittest.mock import AsyncMock, MagicMock
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
from custom_components.adguard_hub.api import AdGuardHomeAPI
from custom_components.adguard_hub.const import DOMAIN
@pytest.fixture(autouse=True)
@@ -8,9 +15,76 @@ def auto_enable_custom_integrations(enable_custom_integrations):
yield
@pytest.fixture(autouse=True)
def mock_platform_setup():
"""Mock platform setup to avoid actual platform loading."""
from unittest.mock import patch
with patch("homeassistant.config_entries.ConfigEntry.async_forward_entry_setups"):
yield
@pytest.fixture
def mock_config_entry():
"""Mock config entry for testing."""
return ConfigEntry(
version=1,
minor_version=1,
domain=DOMAIN,
title="Test AdGuard Control Hub",
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 3000,
CONF_USERNAME: "admin",
CONF_PASSWORD: "password",
},
options={},
source=SOURCE_USER,
entry_id="test_entry_id",
unique_id="192.168.1.100:3000",
)
@pytest.fixture
def mock_api():
"""Mock AdGuard Home API."""
api = MagicMock(spec=AdGuardHomeAPI)
api.host = "192.168.1.100"
api.port = 3000
api.test_connection = AsyncMock(return_value=True)
api.get_status = AsyncMock(return_value={
"protection_enabled": True,
"version": "v0.107.0",
"dns_port": 53,
"running": True,
})
api.get_clients = AsyncMock(return_value={
"clients": [
{
"name": "test_client",
"ids": ["192.168.1.50"],
"filtering_enabled": True,
"blocked_services": {"ids": ["youtube"]},
}
]
})
api.get_statistics = AsyncMock(return_value={
"num_dns_queries": 10000,
"num_blocked_filtering": 1500,
"avg_processing_time": 2.5,
"filtering_rules_count": 75000,
})
api.get_client_by_name = AsyncMock(return_value={
"name": "test_client",
"ids": ["192.168.1.50"],
"filtering_enabled": True,
"blocked_services": {"ids": ["youtube"]},
})
api.set_protection = AsyncMock(return_value={"success": True})
return api
@pytest.fixture
def mock_hass():
"""Mock Home Assistant instance."""
hass = MagicMock(spec=HomeAssistant)
hass.data = {}
hass.services = MagicMock()
hass.services.has_service = MagicMock(return_value=False)
hass.services.register = MagicMock()
hass.services.remove = MagicMock()
hass.config_entries = MagicMock()
hass.config_entries.async_forward_entry_setups = AsyncMock(return_value=True)
hass.config_entries.async_unload_platforms = AsyncMock(return_value=True)
return hass

View File

@@ -4,80 +4,50 @@ 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
class TestAdGuardHomeAPI:
"""Test the AdGuard Home API wrapper."""
# Properly mock the async context manager
context_manager = MagicMock()
context_manager.__aenter__ = AsyncMock(return_value=response)
context_manager.__aexit__ = AsyncMock(return_value=None)
def test_api_initialization(self):
"""Test API initialization."""
api = AdGuardHomeAPI(
host="192.168.1.100",
port=3000,
username="admin",
password="password",
ssl=True,
)
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.host == "192.168.1.100"
assert api.port == 3000
assert api.username == "admin"
assert api.password == "password"
assert api.ssl is True
assert api.base_url == "https://192.168.1.100:3000"
@pytest.mark.asyncio
async def test_api_context_manager(self):
"""Test API as async context manager."""
async with AdGuardHomeAPI(host="192.168.1.100", port=3000) as api:
assert api is not None
assert api.host == "192.168.1.100"
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)
@pytest.mark.asyncio
async def test_test_connection_success(self):
"""Test successful connection test."""
session = MagicMock()
response = MagicMock()
response.status = 200
response.json = AsyncMock(return_value={"protection_enabled": True})
response.raise_for_status = MagicMock()
response.content_length = 100
api = AdGuardHomeAPI(
host="test-host",
port=3000,
session=session
)
context_manager = MagicMock()
context_manager.__aenter__ = AsyncMock(return_value=response)
context_manager.__aexit__ = AsyncMock(return_value=None)
session.request = MagicMock(return_value=context_manager)
with pytest.raises(Exception):
await api.get_status()
api = AdGuardHomeAPI(host="192.168.1.100", session=session)
result = await api.test_connection()
assert result is True

View File

@@ -1,71 +0,0 @@
"""Test config flow for AdGuard Control Hub."""
import pytest
from unittest.mock import AsyncMock, patch
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from custom_components.adguard_hub.const import DOMAIN
@pytest.mark.asyncio
async def test_config_flow_success(hass: HomeAssistant):
"""Test successful config flow."""
with patch("custom_components.adguard_hub.config_flow.validate_input") as mock_validate:
mock_validate.return_value = {
"title": "AdGuard Control Hub (192.168.1.100)",
"host": "192.168.1.100",
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
@pytest.mark.asyncio
async def test_config_flow_cannot_connect(hass: HomeAssistant):
"""Test config flow with connection error."""
from custom_components.adguard_hub.config_flow import CannotConnect
with patch("custom_components.adguard_hub.config_flow.validate_input") as mock_validate:
mock_validate.side_effect = CannotConnect("Connection failed")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={
"host": "invalid-host",
"port": 3000,
"username": "admin",
"password": "password",
},
)
assert result["type"] == FlowResultType.FORM
assert result["errors"]["base"] == "cannot_connect"
@pytest.mark.asyncio
async def test_config_flow_invalid_auth(hass: HomeAssistant):
"""Test config flow with authentication error."""
from custom_components.adguard_hub.config_flow import InvalidAuth
with patch("custom_components.adguard_hub.config_flow.validate_input") as mock_validate:
mock_validate.side_effect = InvalidAuth("Auth failed")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={
"host": "192.168.1.100",
"port": 3000,
"username": "wrong",
"password": "wrong",
},
)
assert result["type"] == FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"

View File

@@ -1,228 +1,48 @@
"""Test the complete AdGuard Control Hub integration."""
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
from unittest.mock import MagicMock, patch
from homeassistant.exceptions import ConfigEntryNotReady
from custom_components.adguard_hub import async_setup_entry, async_unload_entry
from custom_components.adguard_hub.api import AdGuardHomeAPI
from custom_components.adguard_hub.const import DOMAIN
@pytest.fixture
def mock_config_entry():
"""Mock config entry compatible with HA 2025.9.4."""
return ConfigEntry(
version=1,
minor_version=1,
domain=DOMAIN,
title="Test AdGuard",
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 3000,
CONF_USERNAME: "admin",
CONF_PASSWORD: "password",
},
options={},
source=SOURCE_USER,
entry_id="test_entry_id",
unique_id="192.168.1.100:3000",
discovery_keys=set(),
subentries_data={},
)
class TestIntegrationSetup:
"""Test integration setup and unload."""
@pytest.mark.asyncio
async def test_setup_entry_success(self, mock_hass, mock_config_entry, mock_api):
"""Test successful setup of config entry."""
with patch("custom_components.adguard_hub.AdGuardHomeAPI", return_value=mock_api), patch("custom_components.adguard_hub.async_get_clientsession"):
@pytest.fixture
def mock_api():
"""Mock API instance."""
api = MagicMock(spec=AdGuardHomeAPI)
api.host = "192.168.1.100"
api.port = 3000
api.test_connection = AsyncMock(return_value=True)
api.get_status = AsyncMock(return_value={
"protection_enabled": True,
"version": "v0.107.0",
"dns_port": 53,
"running": True,
})
api.get_clients = AsyncMock(return_value={
"clients": [
{
"name": "test_client",
"ids": ["192.168.1.50"],
"filtering_enabled": True,
"blocked_services": {"ids": ["youtube"]},
result = await async_setup_entry(mock_hass, mock_config_entry)
assert result is True
assert DOMAIN in mock_hass.data
assert mock_config_entry.entry_id in mock_hass.data[DOMAIN]
@pytest.mark.asyncio
async def test_setup_entry_connection_failure(self, mock_hass, mock_config_entry):
"""Test setup failure due to connection error."""
mock_api = MagicMock()
mock_api.test_connection = pytest.AsyncMock(return_value=False)
with patch("custom_components.adguard_hub.AdGuardHomeAPI", return_value=mock_api), patch("custom_components.adguard_hub.async_get_clientsession"):
with pytest.raises(ConfigEntryNotReady):
await async_setup_entry(mock_hass, mock_config_entry)
@pytest.mark.asyncio
async def test_unload_entry_success(self, mock_hass, mock_config_entry):
"""Test successful unloading of config entry."""
mock_hass.data[DOMAIN] = {
mock_config_entry.entry_id: {
"coordinator": MagicMock(),
"api": MagicMock(),
}
]
})
api.get_statistics = AsyncMock(return_value={
"num_dns_queries": 1000,
"num_blocked_filtering": 100,
"num_dns_queries_today": 500,
"num_blocked_filtering_today": 50,
"filtering_rules_count": 50000,
"avg_processing_time": 2.5,
})
return api
@pytest.mark.asyncio
async def test_setup_entry_success(hass: HomeAssistant, mock_config_entry, mock_api):
"""Test successful setup of config entry."""
with patch("custom_components.adguard_hub.AdGuardHomeAPI", return_value=mock_api), \
patch("custom_components.adguard_hub.async_get_clientsession"), \
patch.object(hass.config_entries, "async_forward_entry_setups", return_value=True):
result = await async_setup_entry(hass, mock_config_entry)
assert result is True
assert DOMAIN in hass.data
assert mock_config_entry.entry_id in hass.data[DOMAIN]
assert "coordinator" in hass.data[DOMAIN][mock_config_entry.entry_id]
assert "api" in hass.data[DOMAIN][mock_config_entry.entry_id]
@pytest.mark.asyncio
async def test_setup_entry_connection_failure(hass: HomeAssistant, mock_config_entry):
"""Test setup failure due to connection error."""
mock_api = MagicMock(spec=AdGuardHomeAPI)
mock_api.test_connection = AsyncMock(return_value=False)
with patch("custom_components.adguard_hub.AdGuardHomeAPI", return_value=mock_api), \
patch("custom_components.adguard_hub.async_get_clientsession"):
with pytest.raises(Exception): # Should raise ConfigEntryNotReady
await async_setup_entry(hass, mock_config_entry)
@pytest.mark.asyncio
async def test_unload_entry(hass: HomeAssistant, mock_config_entry):
"""Test unloading of config entry."""
# Set up initial data
hass.data[DOMAIN] = {
mock_config_entry.entry_id: {
"coordinator": MagicMock(),
"api": MagicMock(),
}
}
with patch.object(hass.config_entries, "async_unload_platforms", return_value=True):
result = await async_unload_entry(hass, mock_config_entry)
result = await async_unload_entry(mock_hass, mock_config_entry)
assert result is True
assert mock_config_entry.entry_id not in hass.data[DOMAIN]
@pytest.mark.asyncio
async def test_coordinator_data_update(hass: HomeAssistant, mock_api):
"""Test coordinator data update functionality."""
from custom_components.adguard_hub import AdGuardControlHubCoordinator
coordinator = AdGuardControlHubCoordinator(hass, mock_api)
# Test successful data update
data = await coordinator._async_update_data()
assert "clients" in data
assert "statistics" in data
assert "status" in data
assert "test_client" in data["clients"]
assert data["statistics"]["num_dns_queries"] == 1000
assert data["status"]["protection_enabled"] is True
@pytest.mark.asyncio
async def test_api_error_handling(mock_api):
"""Test API error handling."""
from custom_components.adguard_hub.api import AdGuardConnectionError, AdGuardAuthError
# Test connection error
mock_api.get_status = AsyncMock(side_effect=AdGuardConnectionError("Connection failed"))
with pytest.raises(AdGuardConnectionError):
await mock_api.get_status()
# Test auth error
mock_api.get_clients = AsyncMock(side_effect=AdGuardAuthError("Auth failed"))
with pytest.raises(AdGuardAuthError):
await mock_api.get_clients()
def test_services_registration(hass: HomeAssistant):
"""Test that services are properly registered."""
from custom_components.adguard_hub.services import AdGuardControlHubServices
# Create services without async context
services = AdGuardControlHubServices(hass)
services.register_services()
# Check that services are registered
assert hass.services.has_service(DOMAIN, "block_services")
assert hass.services.has_service(DOMAIN, "unblock_services")
assert hass.services.has_service(DOMAIN, "emergency_unblock")
assert hass.services.has_service(DOMAIN, "add_client")
assert hass.services.has_service(DOMAIN, "remove_client")
assert hass.services.has_service(DOMAIN, "bulk_update_clients")
# Clean up
services.unregister_services()
def test_blocked_services_constants():
"""Test that blocked services are properly defined."""
from custom_components.adguard_hub.const import BLOCKED_SERVICES
assert "youtube" in BLOCKED_SERVICES
assert "netflix" in BLOCKED_SERVICES
assert "gaming" in BLOCKED_SERVICES
assert "facebook" in BLOCKED_SERVICES
# Check friendly names are defined
assert BLOCKED_SERVICES["youtube"] == "YouTube"
assert BLOCKED_SERVICES["netflix"] == "Netflix"
def test_api_endpoints():
"""Test that API endpoints are properly defined."""
from custom_components.adguard_hub.const import API_ENDPOINTS
required_endpoints = [
"status", "clients", "stats", "protection",
"clients_add", "clients_update", "clients_delete"
]
for endpoint in required_endpoints:
assert endpoint in API_ENDPOINTS
assert API_ENDPOINTS[endpoint].startswith("/")
@pytest.mark.asyncio
async def test_client_operations(mock_api):
"""Test client add/update/delete operations."""
# Test add client
client_data = {
"name": "new_client",
"ids": ["192.168.1.200"],
"filtering_enabled": True,
}
mock_api.add_client = AsyncMock(return_value={"success": True})
result = await mock_api.add_client(client_data)
assert result["success"] is True
# Test update client
update_data = {
"name": "new_client",
"data": {"filtering_enabled": False}
}
mock_api.update_client = AsyncMock(return_value={"success": True})
result = await mock_api.update_client(update_data)
assert result["success"] is True
# Test delete client
mock_api.delete_client = AsyncMock(return_value={"success": True})
result = await mock_api.delete_client("new_client")
assert result["success"] is True
assert mock_config_entry.entry_id not in mock_hass.data[DOMAIN]