init home-assistant
This commit is contained in:
99
home-assistant/tests/components/cloudflare/__init__.py
Normal file
99
home-assistant/tests/components/cloudflare/__init__.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""Tests for the Cloudflare integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import pycfdns
|
||||
|
||||
from homeassistant.components.cloudflare.const import CONF_RECORDS, DOMAIN
|
||||
from homeassistant.const import CONF_API_TOKEN, CONF_ZONE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.typing import UNDEFINED, UndefinedType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
ENTRY_CONFIG = {
|
||||
CONF_API_TOKEN: "mock-api-token",
|
||||
CONF_ZONE: "mock.com",
|
||||
CONF_RECORDS: ["ha.mock.com", "homeassistant.mock.com"],
|
||||
}
|
||||
|
||||
ENTRY_OPTIONS = {}
|
||||
|
||||
USER_INPUT = {
|
||||
CONF_API_TOKEN: "mock-api-token",
|
||||
}
|
||||
|
||||
USER_INPUT_ZONE = {CONF_ZONE: "mock.com"}
|
||||
|
||||
USER_INPUT_RECORDS = {CONF_RECORDS: ["ha.mock.com", "homeassistant.mock.com"]}
|
||||
|
||||
MOCK_ZONE: pycfdns.ZoneModel = {"name": "mock.com", "id": "mock-zone-id"}
|
||||
MOCK_ZONE_RECORDS: list[pycfdns.RecordModel] = [
|
||||
{
|
||||
"id": "zone-record-id",
|
||||
"type": "A",
|
||||
"name": "ha.mock.com",
|
||||
"proxied": True,
|
||||
"content": "127.0.0.1",
|
||||
},
|
||||
{
|
||||
"id": "zone-record-id-2",
|
||||
"type": "A",
|
||||
"name": "homeassistant.mock.com",
|
||||
"proxied": True,
|
||||
"content": "127.0.0.1",
|
||||
},
|
||||
{
|
||||
"id": "zone-record-id-3",
|
||||
"type": "A",
|
||||
"name": "mock.com",
|
||||
"proxied": True,
|
||||
"content": "127.0.0.1",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
async def init_integration(
|
||||
hass: HomeAssistant,
|
||||
*,
|
||||
data: dict[str, Any] | UndefinedType = UNDEFINED,
|
||||
options: dict[str, Any] | UndefinedType = UNDEFINED,
|
||||
unique_id: str = MOCK_ZONE["name"],
|
||||
skip_setup: bool = False,
|
||||
) -> MockConfigEntry:
|
||||
"""Set up the Cloudflare integration in Home Assistant."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_CONFIG if data is UNDEFINED else data,
|
||||
options=ENTRY_OPTIONS if options is UNDEFINED else options,
|
||||
unique_id=unique_id,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
if not skip_setup:
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return entry
|
||||
|
||||
|
||||
def get_mock_client() -> Mock:
|
||||
"""Return of Mock of pycfdns.Client."""
|
||||
client = Mock()
|
||||
|
||||
client.list_zones = AsyncMock(return_value=[MOCK_ZONE])
|
||||
client.list_dns_records = AsyncMock(return_value=MOCK_ZONE_RECORDS)
|
||||
client.update_dns_record = AsyncMock(return_value=None)
|
||||
|
||||
return client
|
||||
|
||||
|
||||
def patch_async_setup_entry() -> AsyncMock:
|
||||
"""Patch the async_setup_entry method and return a mock."""
|
||||
return patch(
|
||||
"homeassistant.components.cloudflare.async_setup_entry",
|
||||
return_value=True,
|
||||
)
|
||||
30
home-assistant/tests/components/cloudflare/conftest.py
Normal file
30
home-assistant/tests/components/cloudflare/conftest.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""Define fixtures available for all tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from . import get_mock_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cfupdate() -> Generator[MagicMock]:
|
||||
"""Mock the CloudflareUpdater for easier testing."""
|
||||
mock_cfupdate = get_mock_client()
|
||||
with patch(
|
||||
"homeassistant.components.cloudflare.pycfdns.Client",
|
||||
return_value=mock_cfupdate,
|
||||
) as mock_api:
|
||||
yield mock_api
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cfupdate_flow() -> Generator[MagicMock]:
|
||||
"""Mock the CloudflareUpdater for easier config flow testing."""
|
||||
mock_cfupdate = get_mock_client()
|
||||
with patch(
|
||||
"homeassistant.components.cloudflare.config_flow.pycfdns.Client",
|
||||
return_value=mock_cfupdate,
|
||||
) as mock_api:
|
||||
yield mock_api
|
||||
172
home-assistant/tests/components/cloudflare/test_config_flow.py
Normal file
172
home-assistant/tests/components/cloudflare/test_config_flow.py
Normal file
@@ -0,0 +1,172 @@
|
||||
"""Test the Cloudflare config flow."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pycfdns
|
||||
|
||||
from homeassistant.components.cloudflare.const import CONF_RECORDS, DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.const import CONF_API_TOKEN, CONF_SOURCE, CONF_ZONE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from . import (
|
||||
ENTRY_CONFIG,
|
||||
USER_INPUT,
|
||||
USER_INPUT_RECORDS,
|
||||
USER_INPUT_ZONE,
|
||||
patch_async_setup_entry,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_user_form(hass: HomeAssistant, cfupdate_flow: MagicMock) -> None:
|
||||
"""Test we get the user initiated form."""
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={CONF_SOURCE: SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "zone"
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT_ZONE,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "records"
|
||||
assert result["errors"] is None
|
||||
|
||||
with patch_async_setup_entry() as mock_setup_entry:
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT_RECORDS,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == USER_INPUT_ZONE[CONF_ZONE]
|
||||
|
||||
assert result["data"]
|
||||
assert result["data"][CONF_API_TOKEN] == USER_INPUT[CONF_API_TOKEN]
|
||||
assert result["data"][CONF_ZONE] == USER_INPUT_ZONE[CONF_ZONE]
|
||||
assert result["data"][CONF_RECORDS] == USER_INPUT_RECORDS[CONF_RECORDS]
|
||||
|
||||
assert result["result"]
|
||||
assert result["result"].unique_id == USER_INPUT_ZONE[CONF_ZONE]
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_user_form_cannot_connect(
|
||||
hass: HomeAssistant, cfupdate_flow: MagicMock
|
||||
) -> None:
|
||||
"""Test we handle cannot connect error."""
|
||||
instance = cfupdate_flow.return_value
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={CONF_SOURCE: SOURCE_USER}
|
||||
)
|
||||
|
||||
instance.list_zones.side_effect = pycfdns.ComunicationException()
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT,
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
async def test_user_form_invalid_auth(
|
||||
hass: HomeAssistant, cfupdate_flow: MagicMock
|
||||
) -> None:
|
||||
"""Test we handle invalid auth error."""
|
||||
instance = cfupdate_flow.return_value
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={CONF_SOURCE: SOURCE_USER}
|
||||
)
|
||||
|
||||
instance.list_zones.side_effect = pycfdns.AuthenticationException()
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT,
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
|
||||
|
||||
async def test_user_form_unexpected_exception(
|
||||
hass: HomeAssistant, cfupdate_flow: MagicMock
|
||||
) -> None:
|
||||
"""Test we handle unexpected exception."""
|
||||
instance = cfupdate_flow.return_value
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={CONF_SOURCE: SOURCE_USER}
|
||||
)
|
||||
|
||||
instance.list_zones.side_effect = Exception()
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
USER_INPUT,
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "unknown"}
|
||||
|
||||
|
||||
async def test_user_form_single_instance_allowed(hass: HomeAssistant) -> None:
|
||||
"""Test that configuring more than one instance is rejected."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={CONF_SOURCE: SOURCE_USER},
|
||||
data=USER_INPUT,
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "single_instance_allowed"
|
||||
|
||||
|
||||
async def test_reauth_flow(hass: HomeAssistant, cfupdate_flow: MagicMock) -> None:
|
||||
"""Test the reauthentication configuration flow."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
with patch_async_setup_entry() as mock_setup_entry:
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_TOKEN: "other_token"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
assert entry.data[CONF_API_TOKEN] == "other_token"
|
||||
assert entry.data[CONF_ZONE] == ENTRY_CONFIG[CONF_ZONE]
|
||||
assert entry.data[CONF_RECORDS] == ENTRY_CONFIG[CONF_RECORDS]
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
14
home-assistant/tests/components/cloudflare/test_helpers.py
Normal file
14
home-assistant/tests/components/cloudflare/test_helpers.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""Test Cloudflare integration helpers."""
|
||||
|
||||
from homeassistant.components.cloudflare.helpers import get_zone_id
|
||||
|
||||
|
||||
def test_get_zone_id() -> None:
|
||||
"""Test get_zone_id."""
|
||||
zones = [
|
||||
{"id": "1", "name": "example.com"},
|
||||
{"id": "2", "name": "example.org"},
|
||||
]
|
||||
assert get_zone_id("example.com", zones) == "1"
|
||||
assert get_zone_id("example.org", zones) == "2"
|
||||
assert get_zone_id("example.net", zones) is None
|
||||
234
home-assistant/tests/components/cloudflare/test_init.py
Normal file
234
home-assistant/tests/components/cloudflare/test_init.py
Normal file
@@ -0,0 +1,234 @@
|
||||
"""Test the Cloudflare integration."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pycfdns
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.cloudflare.const import (
|
||||
CONF_RECORDS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
SERVICE_UPDATE_RECORDS,
|
||||
)
|
||||
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import homeassistant.util.dt as dt_util
|
||||
from homeassistant.util.location import LocationInfo
|
||||
|
||||
from . import ENTRY_CONFIG, init_integration
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
async def test_unload_entry(hass: HomeAssistant, cfupdate: MagicMock) -> None:
|
||||
"""Test successful unload of entry."""
|
||||
entry = await init_integration(hass)
|
||||
|
||||
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.NOT_LOADED
|
||||
assert not hass.data.get(DOMAIN)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"side_effect",
|
||||
[pycfdns.ComunicationException()],
|
||||
)
|
||||
async def test_async_setup_raises_entry_not_ready(
|
||||
hass: HomeAssistant, cfupdate: MagicMock, side_effect: Exception
|
||||
) -> None:
|
||||
"""Test that it throws ConfigEntryNotReady when exception occurs during setup."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
instance.list_zones.side_effect = side_effect
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
|
||||
assert entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
async def test_async_setup_raises_entry_auth_failed(
|
||||
hass: HomeAssistant, cfupdate: MagicMock
|
||||
) -> None:
|
||||
"""Test that it throws ConfigEntryAuthFailed when exception occurs during setup."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
instance.list_zones.side_effect = pycfdns.AuthenticationException()
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
|
||||
flow = flows[0]
|
||||
assert flow["step_id"] == "reauth_confirm"
|
||||
assert flow["handler"] == DOMAIN
|
||||
|
||||
assert "context" in flow
|
||||
assert flow["context"]["source"] == SOURCE_REAUTH
|
||||
assert flow["context"]["entry_id"] == entry.entry_id
|
||||
|
||||
|
||||
async def test_integration_services(
|
||||
hass: HomeAssistant, cfupdate: MagicMock, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test integration services."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = await init_integration(hass)
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.cloudflare.async_detect_location_info",
|
||||
return_value=LocationInfo(
|
||||
"0.0.0.0",
|
||||
"US",
|
||||
"USD",
|
||||
"CA",
|
||||
"California",
|
||||
"San Diego",
|
||||
"92122",
|
||||
"America/Los_Angeles",
|
||||
32.8594,
|
||||
-117.2073,
|
||||
True,
|
||||
),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_UPDATE_RECORDS,
|
||||
{},
|
||||
blocking=True,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(instance.update_dns_record.mock_calls) == 2
|
||||
assert "All target records are up to date" not in caplog.text
|
||||
|
||||
|
||||
async def test_integration_services_with_issue(
|
||||
hass: HomeAssistant, cfupdate: MagicMock
|
||||
) -> None:
|
||||
"""Test integration services with issue."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = await init_integration(hass)
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.cloudflare.async_detect_location_info",
|
||||
return_value=None,
|
||||
),
|
||||
pytest.raises(HomeAssistantError, match="Could not get external IPv4 address"),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_UPDATE_RECORDS,
|
||||
{},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
instance.update_dns_record.assert_not_called()
|
||||
|
||||
|
||||
async def test_integration_services_with_nonexisting_record(
|
||||
hass: HomeAssistant, cfupdate: MagicMock, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test integration services."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = await init_integration(
|
||||
hass, data={**ENTRY_CONFIG, CONF_RECORDS: ["nonexisting.example.com"]}
|
||||
)
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.cloudflare.async_detect_location_info",
|
||||
return_value=LocationInfo(
|
||||
"0.0.0.0",
|
||||
"US",
|
||||
"USD",
|
||||
"CA",
|
||||
"California",
|
||||
"San Diego",
|
||||
"92122",
|
||||
"America/Los_Angeles",
|
||||
32.8594,
|
||||
-117.2073,
|
||||
True,
|
||||
),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_UPDATE_RECORDS,
|
||||
{},
|
||||
blocking=True,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
instance.update_dns_record.assert_not_called()
|
||||
assert "All target records are up to date" in caplog.text
|
||||
|
||||
|
||||
async def test_integration_update_interval(
|
||||
hass: HomeAssistant,
|
||||
cfupdate: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test integration update interval."""
|
||||
instance = cfupdate.return_value
|
||||
|
||||
entry = await init_integration(hass)
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.cloudflare.async_detect_location_info",
|
||||
return_value=LocationInfo(
|
||||
"0.0.0.0",
|
||||
"US",
|
||||
"USD",
|
||||
"CA",
|
||||
"California",
|
||||
"San Diego",
|
||||
"92122",
|
||||
"America/Los_Angeles",
|
||||
32.8594,
|
||||
-117.2073,
|
||||
True,
|
||||
),
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(minutes=DEFAULT_UPDATE_INTERVAL)
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert len(instance.update_dns_record.mock_calls) == 2
|
||||
assert "All target records are up to date" not in caplog.text
|
||||
|
||||
instance.list_dns_records.side_effect = pycfdns.AuthenticationException()
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(minutes=DEFAULT_UPDATE_INTERVAL)
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert len(instance.update_dns_record.mock_calls) == 2
|
||||
|
||||
instance.list_dns_records.side_effect = pycfdns.ComunicationException()
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(minutes=DEFAULT_UPDATE_INTERVAL)
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert len(instance.update_dns_record.mock_calls) == 2
|
||||
Reference in New Issue
Block a user