init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""The tests for Device tracker platforms."""

View File

@@ -0,0 +1,154 @@
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.device_tracker import (
ATTR_ATTRIBUTES,
ATTR_BATTERY,
ATTR_DEV_ID,
ATTR_GPS,
ATTR_GPS_ACCURACY,
ATTR_HOST_NAME,
ATTR_LOCATION_NAME,
ATTR_MAC,
DOMAIN,
SERVICE_SEE,
DeviceScanner,
ScannerEntity,
SourceType,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.typing import ConfigType, GPSType
from homeassistant.loader import bind_hass
from tests.common import MockPlatform, mock_platform
@callback
@bind_hass
def async_see(
hass: HomeAssistant,
mac: str | None = None,
dev_id: str | None = None,
host_name: str | None = None,
location_name: str | None = None,
gps: GPSType | None = None,
gps_accuracy=None,
battery: int | None = None,
attributes: dict | None = None,
):
"""Call service to notify you see device."""
data = {
key: value
for key, value in (
(ATTR_MAC, mac),
(ATTR_DEV_ID, dev_id),
(ATTR_HOST_NAME, host_name),
(ATTR_LOCATION_NAME, location_name),
(ATTR_GPS, gps),
(ATTR_GPS_ACCURACY, gps_accuracy),
(ATTR_BATTERY, battery),
)
if value is not None
}
if attributes:
data[ATTR_ATTRIBUTES] = attributes
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_SEE, data))
class MockScannerEntity(ScannerEntity):
"""Test implementation of a ScannerEntity."""
def __init__(self) -> None:
"""Init."""
self.connected = False
self._hostname = "test.hostname.org"
self._ip_address = "0.0.0.0"
self._mac_address = "ad:de:ef:be:ed:fe"
@property
def source_type(self) -> SourceType:
"""Return the source type, eg gps or router, of the device."""
return SourceType.ROUTER
@property
def battery_level(self):
"""Return the battery level of the device.
Percentage from 0-100.
"""
return 100
@property
def ip_address(self) -> str:
"""Return the primary ip address of the device."""
return self._ip_address
@property
def mac_address(self) -> str:
"""Return the mac address of the device."""
return self._mac_address
@property
def hostname(self) -> str:
"""Return hostname of the device."""
return self._hostname
@property
def is_connected(self):
"""Return true if the device is connected to the network."""
return self.connected
def set_connected(self):
"""Set connected to True."""
self.connected = True
self.async_write_ha_state()
class MockScanner(DeviceScanner):
"""Mock device scanner."""
def __init__(self) -> None:
"""Initialize the MockScanner."""
self.devices_home = []
def come_home(self, device):
"""Make a device come home."""
self.devices_home.append(device)
def leave_home(self, device):
"""Make a device leave the house."""
self.devices_home.remove(device)
def reset(self):
"""Reset which devices are home."""
self.devices_home = []
def scan_devices(self):
"""Return a list of fake devices."""
return list(self.devices_home)
def get_device_name(self, device):
"""Return a name for a mock device.
Return None for dev1 for testing.
"""
return None if device == "DEV1" else device.lower()
def mock_legacy_device_tracker_setup(
hass: HomeAssistant, legacy_device_scanner: MockScanner
) -> None:
"""Mock legacy device tracker platform setup."""
async def _async_get_scanner(
hass: HomeAssistant, config: ConfigType
) -> MockScanner:
"""Return the test scanner."""
return legacy_device_scanner
mocked_platform = MockPlatform()
mocked_platform.async_get_scanner = _async_get_scanner
mock_platform(hass, "test.device_tracker", mocked_platform)

View File

@@ -0,0 +1,795 @@
"""Test Device Tracker config entry things."""
from collections.abc import Generator
from typing import Any
import pytest
from homeassistant.components.device_tracker import (
ATTR_HOST_NAME,
ATTR_IP,
ATTR_MAC,
ATTR_SOURCE_TYPE,
DOMAIN,
SourceType,
)
from homeassistant.components.device_tracker.config_entry import (
CONNECTED_DEVICE_REGISTERED,
BaseTrackerEntity,
ScannerEntity,
TrackerEntity,
)
from homeassistant.components.zone import ATTR_RADIUS
from homeassistant.config_entries import ConfigEntry, ConfigEntryState, ConfigFlow
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
STATE_HOME,
STATE_NOT_HOME,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
mock_config_flow,
mock_integration,
mock_platform,
)
TEST_DOMAIN = "test"
TEST_MAC_ADDRESS = "12:34:56:AB:CD:EF"
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture(autouse=True)
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield
@pytest.fixture(autouse=True)
def mock_setup_integration(hass: HomeAssistant) -> None:
"""Fixture to set up a mock integration."""
async def async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [Platform.DEVICE_TRACKER]
)
return True
async def async_unload_entry_init(
hass: HomeAssistant,
config_entry: ConfigEntry,
) -> bool:
await hass.config_entries.async_unload_platforms(
config_entry, [Platform.DEVICE_TRACKER]
)
return True
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
async_unload_entry=async_unload_entry_init,
),
)
@pytest.fixture(name="config_entry")
def config_entry_fixture(hass: HomeAssistant) -> MockConfigEntry:
"""Return the config entry used for the tests."""
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
return config_entry
async def create_mock_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entities: list[Entity],
) -> MockConfigEntry:
"""Create a device tracker platform with the specified entities."""
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up test event platform via config entry."""
async_add_entities(entities)
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
@pytest.fixture(name="entity_id")
def entity_id_fixture() -> str:
"""Return the entity_id of the entity for the test."""
return "device_tracker.entity1"
class MockTrackerEntity(TrackerEntity):
"""Test tracker entity."""
def __init__(
self,
battery_level: int | None = None,
location_name: str | None = None,
latitude: float | None = None,
longitude: float | None = None,
) -> None:
"""Initialize entity."""
self._battery_level = battery_level
self._location_name = location_name
self._latitude = latitude
self._longitude = longitude
@property
def battery_level(self) -> int | None:
"""Return the battery level of the device.
Percentage from 0-100.
"""
return self._battery_level
@property
def source_type(self) -> SourceType:
"""Return the source type, eg gps or router, of the device."""
return SourceType.GPS
@property
def location_name(self) -> str | None:
"""Return a location name for the current location of the device."""
return self._location_name
@property
def latitude(self) -> float | None:
"""Return latitude value of the device."""
return self._latitude
@property
def longitude(self) -> float | None:
"""Return longitude value of the device."""
return self._longitude
@pytest.fixture(name="battery_level")
def battery_level_fixture() -> int | None:
"""Return the battery level of the entity for the test."""
return None
@pytest.fixture(name="location_name")
def location_name_fixture() -> str | None:
"""Return the location_name of the entity for the test."""
return None
@pytest.fixture(name="latitude")
def latitude_fixture() -> float | None:
"""Return the latitude of the entity for the test."""
return None
@pytest.fixture(name="longitude")
def longitude_fixture() -> float | None:
"""Return the longitude of the entity for the test."""
return None
@pytest.fixture(name="tracker_entity")
def tracker_entity_fixture(
entity_id: str,
battery_level: int | None,
location_name: str | None,
latitude: float | None,
longitude: float | None,
) -> MockTrackerEntity:
"""Create a test tracker entity."""
entity = MockTrackerEntity(
battery_level=battery_level,
location_name=location_name,
latitude=latitude,
longitude=longitude,
)
entity.entity_id = entity_id
return entity
class MockScannerEntity(ScannerEntity):
"""Test scanner entity."""
def __init__(
self,
ip_address: str | None = None,
mac_address: str | None = None,
hostname: str | None = None,
connected: bool = False,
unique_id: str | None = None,
) -> None:
"""Initialize entity."""
self._ip_address = ip_address
self._mac_address = mac_address
self._hostname = hostname
self._connected = connected
self._unique_id = unique_id
@property
def should_poll(self) -> bool:
"""Return False for the test entity."""
return False
@property
def source_type(self) -> SourceType:
"""Return the source type, eg gps or router, of the device."""
return SourceType.ROUTER
@property
def ip_address(self) -> str | None:
"""Return the primary ip address of the device."""
return self._ip_address
@property
def mac_address(self) -> str | None:
"""Return the mac address of the device."""
return self._mac_address
@property
def hostname(self) -> str | None:
"""Return hostname of the device."""
return self._hostname
@property
def is_connected(self) -> bool:
"""Return true if the device is connected to the network."""
return self._connected
@property
def unique_id(self) -> str | None:
"""Return hostname of the device."""
return self._unique_id or self._mac_address
@callback
def set_connected(self, connected: bool) -> None:
"""Set connected state."""
self._connected = connected
self.async_write_ha_state()
@pytest.fixture(name="ip_address")
def ip_address_fixture() -> str | None:
"""Return the ip_address of the entity for the test."""
return None
@pytest.fixture(name="mac_address")
def mac_address_fixture() -> str | None:
"""Return the mac_address of the entity for the test."""
return None
@pytest.fixture(name="hostname")
def hostname_fixture() -> str | None:
"""Return the hostname of the entity for the test."""
return None
@pytest.fixture(name="unique_id")
def unique_id_fixture() -> str | None:
"""Return the unique_id of the entity for the test."""
return None
@pytest.fixture(name="scanner_entity")
def scanner_entity_fixture(
entity_id: str,
ip_address: str | None,
mac_address: str | None,
hostname: str | None,
unique_id: str | None,
) -> MockScannerEntity:
"""Create a test scanner entity."""
entity = MockScannerEntity(
ip_address=ip_address,
mac_address=mac_address,
hostname=hostname,
unique_id=unique_id,
)
entity.entity_id = entity_id
return entity
async def test_load_unload_entry(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_id: str,
tracker_entity: MockTrackerEntity,
) -> None:
"""Test loading and unloading a config entry with a device tracker entity."""
config_entry = await create_mock_platform(hass, config_entry, [tracker_entity])
assert config_entry.state is ConfigEntryState.LOADED
state = hass.states.get(entity_id)
assert state
assert await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.NOT_LOADED
state = hass.states.get(entity_id)
assert not state
@pytest.mark.parametrize(
(
"battery_level",
"location_name",
"latitude",
"longitude",
"expected_state",
"expected_attributes",
),
[
(
None,
None,
1.0,
2.0,
STATE_NOT_HOME,
{
ATTR_SOURCE_TYPE: SourceType.GPS,
ATTR_GPS_ACCURACY: 0,
ATTR_LATITUDE: 1.0,
ATTR_LONGITUDE: 2.0,
},
),
(
None,
None,
50.0,
60.0,
STATE_HOME,
{
ATTR_SOURCE_TYPE: SourceType.GPS,
ATTR_GPS_ACCURACY: 0,
ATTR_LATITUDE: 50.0,
ATTR_LONGITUDE: 60.0,
},
),
(
None,
None,
-50.0,
-60.0,
"other zone",
{
ATTR_SOURCE_TYPE: SourceType.GPS,
ATTR_GPS_ACCURACY: 0,
ATTR_LATITUDE: -50.0,
ATTR_LONGITUDE: -60.0,
},
),
(
None,
"zen_zone",
None,
None,
"zen_zone",
{
ATTR_SOURCE_TYPE: SourceType.GPS,
},
),
(
None,
None,
None,
None,
STATE_UNKNOWN,
{ATTR_SOURCE_TYPE: SourceType.GPS},
),
(
100,
None,
None,
None,
STATE_UNKNOWN,
{ATTR_BATTERY_LEVEL: 100, ATTR_SOURCE_TYPE: SourceType.GPS},
),
],
)
async def test_tracker_entity_state(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_id: str,
tracker_entity: MockTrackerEntity,
expected_state: str,
expected_attributes: dict[str, Any],
) -> None:
"""Test tracker entity state and state attributes."""
config_entry = await create_mock_platform(hass, config_entry, [tracker_entity])
assert config_entry.state is ConfigEntryState.LOADED
hass.states.async_set(
"zone.home",
"0",
{ATTR_LATITUDE: 50.0, ATTR_LONGITUDE: 60.0, ATTR_RADIUS: 200},
)
hass.states.async_set(
"zone.other_zone",
"0",
{ATTR_LATITUDE: -50.0, ATTR_LONGITUDE: -60.0, ATTR_RADIUS: 300},
)
await hass.async_block_till_done()
# Write state again to ensure the zone state is taken into account.
tracker_entity.async_write_ha_state()
state = hass.states.get(entity_id)
assert state
assert state.state == expected_state
assert state.attributes == expected_attributes
@pytest.mark.parametrize(
("ip_address", "mac_address", "hostname"),
[("0.0.0.0", "ad:de:ef:be:ed:fe", "test.hostname.org")],
)
async def test_scanner_entity_state(
hass: HomeAssistant,
config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_id: str,
ip_address: str,
mac_address: str,
hostname: str,
scanner_entity: MockScannerEntity,
) -> None:
"""Test ScannerEntity based device tracker."""
# Make device tied to other integration so device tracker entities get enabled
other_config_entry = MockConfigEntry(domain="not_fake_integration")
other_config_entry.add_to_hass(hass)
device_registry.async_get_or_create(
name="Device from other integration",
config_entry_id=other_config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, mac_address)},
)
config_entry = await create_mock_platform(hass, config_entry, [scanner_entity])
assert config_entry.state is ConfigEntryState.LOADED
entity_state = hass.states.get(entity_id)
assert entity_state
assert entity_state.attributes == {
ATTR_SOURCE_TYPE: SourceType.ROUTER,
ATTR_IP: ip_address,
ATTR_MAC: mac_address,
ATTR_HOST_NAME: hostname,
}
assert entity_state.state == STATE_NOT_HOME
scanner_entity.set_connected(True)
await hass.async_block_till_done()
entity_state = hass.states.get(entity_id)
assert entity_state
assert entity_state.state == STATE_HOME
def test_tracker_entity() -> None:
"""Test coverage for base TrackerEntity class."""
entity = TrackerEntity()
assert entity.source_type is SourceType.GPS
assert entity.latitude is None
assert entity.longitude is None
assert entity.location_name is None
assert entity.state is None
assert entity.battery_level is None
assert entity.should_poll is False
assert entity.force_update is True
class MockEntity(TrackerEntity):
"""Mock tracker class."""
def __init__(self) -> None:
"""Initialize."""
self.is_polling = False
@property
def should_poll(self) -> bool:
"""Return False for the test entity."""
return self.is_polling
test_entity = MockEntity()
assert test_entity.force_update
test_entity.is_polling = True
assert not test_entity.force_update
def test_scanner_entity() -> None:
"""Test coverage for base ScannerEntity entity class."""
entity = ScannerEntity()
assert entity.source_type is SourceType.ROUTER
with pytest.raises(NotImplementedError):
assert entity.is_connected is None
with pytest.raises(NotImplementedError):
assert entity.state == STATE_NOT_HOME
assert entity.battery_level is None
assert entity.ip_address is None
assert entity.mac_address is None
assert entity.hostname is None
class MockEntity(ScannerEntity):
"""Mock scanner class."""
def __init__(self) -> None:
"""Initialize."""
self.mock_mac_address: str | None = None
@property
def mac_address(self) -> str | None:
"""Return the mac address of the device."""
return self.mock_mac_address
test_entity = MockEntity()
assert test_entity.unique_id is None
test_entity.mock_mac_address = TEST_MAC_ADDRESS
assert test_entity.unique_id == TEST_MAC_ADDRESS
def test_base_tracker_entity() -> None:
"""Test coverage for base BaseTrackerEntity entity class."""
entity = BaseTrackerEntity()
with pytest.raises(NotImplementedError):
assert entity.source_type is None
assert entity.battery_level is None
with pytest.raises(NotImplementedError):
assert entity.state_attributes is None
@pytest.mark.parametrize(
("mac_address", "unique_id"), [(TEST_MAC_ADDRESS, f"{TEST_MAC_ADDRESS}_yo1")]
)
async def test_register_mac(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
scanner_entity: MockScannerEntity,
entity_id: str,
mac_address: str,
unique_id: str,
) -> None:
"""Test registering a mac."""
await create_mock_platform(hass, config_entry, [scanner_entity])
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.disabled_by == er.RegistryEntryDisabler.INTEGRATION
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, mac_address)},
)
await hass.async_block_till_done()
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.disabled_by is None
@pytest.mark.parametrize(
("connections", "mac_address", "unique_id"),
[
(
set(),
TEST_MAC_ADDRESS,
f"{TEST_MAC_ADDRESS}_yo1",
),
(
{(dr.CONNECTION_NETWORK_MAC, TEST_MAC_ADDRESS)},
"aa:bb:cc:dd:ee:ff",
"aa_bb_cc_dd_ee_ff",
),
],
)
async def test_register_mac_not_found(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
scanner_entity: MockScannerEntity,
entity_id: str,
connections: set[tuple[str, str]],
mac_address: str,
unique_id: str,
) -> None:
"""Test registering a mac when the mac or entity isn't found."""
registering_scanner_entity = MockScannerEntity(mac_address="aa:bb:cc:dd:ee:ff")
registering_scanner_entity.entity_id = f"{DOMAIN}.registering_scanner_entity"
await create_mock_platform(
hass, config_entry, [registering_scanner_entity, scanner_entity]
)
test_entity_entry = entity_registry.async_get(entity_id)
assert test_entity_entry is not None
assert test_entity_entry.disabled_by == er.RegistryEntryDisabler.INTEGRATION
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections=connections,
identifiers={(TEST_DOMAIN, "device1")},
)
await hass.async_block_till_done()
# The entity entry under test should still be disabled.
test_entity_entry = entity_registry.async_get(entity_id)
assert test_entity_entry is not None
assert test_entity_entry.disabled_by == er.RegistryEntryDisabler.INTEGRATION
@pytest.mark.parametrize(
("mac_address", "unique_id"), [(TEST_MAC_ADDRESS, f"{TEST_MAC_ADDRESS}_yo1")]
)
async def test_register_mac_ignored(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
scanner_entity: MockScannerEntity,
entity_id: str,
mac_address: str,
unique_id: str,
) -> None:
"""Test ignoring registering a mac."""
config_entry = MockConfigEntry(domain=TEST_DOMAIN, pref_disable_new_entities=True)
config_entry.add_to_hass(hass)
await create_mock_platform(hass, config_entry, [scanner_entity])
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.disabled_by == er.RegistryEntryDisabler.INTEGRATION
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, mac_address)},
)
await hass.async_block_till_done()
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.disabled_by == er.RegistryEntryDisabler.INTEGRATION
async def test_connected_device_registered(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test dispatch on connected device being registered."""
dispatches: list[dict[str, Any]] = []
@callback
def _save_dispatch(msg: dict[str, Any]) -> None:
"""Save dispatched message."""
dispatches.append(msg)
unsub = async_dispatcher_connect(hass, CONNECTED_DEVICE_REGISTERED, _save_dispatch)
connected_scanner_entity = MockScannerEntity(
ip_address="5.4.3.2",
mac_address="aa:bb:cc:dd:ee:ff",
hostname="connected",
connected=True,
)
disconnected_scanner_entity = MockScannerEntity(
ip_address="5.4.3.2",
mac_address="aa:bb:cc:dd:ee:00",
hostname="disconnected",
connected=False,
)
connected_scanner_entity_bad_ip = MockScannerEntity(
ip_address="",
mac_address="aa:bb:cc:dd:ee:01",
hostname="connected_bad_ip",
connected=True,
)
config_entry = await create_mock_platform(
hass,
config_entry,
[
connected_scanner_entity,
disconnected_scanner_entity,
connected_scanner_entity_bad_ip,
],
)
full_name = f"{config_entry.domain}.{DOMAIN}"
assert full_name in hass.config.components
assert (
len(hass.states.async_entity_ids(domain_filter=DOMAIN)) == 0
) # should be disabled
assert len(entity_registry.entities) == 3
assert (
entity_registry.entities[
"device_tracker.test_aa_bb_cc_dd_ee_ff"
].config_entry_id
== config_entry.entry_id
)
unsub()
assert dispatches == [
{"ip": "5.4.3.2", "mac": "aa:bb:cc:dd:ee:ff", "host_name": "connected"}
]
async def test_entity_has_device_info(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a scanner entity with device info."""
class DeviceInfoScannerEntity(MockScannerEntity):
"""Test scanner entity with device info."""
@property
def device_info(self) -> dr.DeviceInfo:
"""Return device info."""
return dr.DeviceInfo(
connections={(dr.CONNECTION_NETWORK_MAC, TEST_MAC_ADDRESS)},
identifiers={(TEST_DOMAIN, "device1")},
manufacturer="manufacturer",
model="model",
)
scanner_entity = DeviceInfoScannerEntity(
ip_address="5.4.3.2",
mac_address=TEST_MAC_ADDRESS,
)
config_entry = await create_mock_platform(hass, config_entry, [scanner_entity])
assert (
len(hass.states.async_entity_ids(domain_filter=DOMAIN)) == 1
) # should be enabled
assert len(entity_registry.entities) == 1
assert (
entity_registry.entities[
f"{DOMAIN}.{TEST_DOMAIN}_{TEST_MAC_ADDRESS.replace(':', '_').lower()}"
].config_entry_id
== config_entry.entry_id
)

View File

@@ -0,0 +1,241 @@
"""The tests for Device tracker device conditions."""
import pytest
from pytest_unordered import unordered
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.device_tracker import DOMAIN
from homeassistant.const import STATE_HOME, EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
async def test_get_conditions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a device_tracker."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for condition in ("is_not_home", "is_home")
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_conditions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for condition in ("is_not_home", "is_home")
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
async def test_if_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_HOME)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_home",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"is_home "
"- {{ trigger.platform }} "
"- {{ trigger.event.event_type }}"
)
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event2"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "is_not_home",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"is_not_home "
"- {{ trigger.platform }} "
"- {{ trigger.event.event_type }}"
)
},
},
},
]
},
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "is_home - event - test_event1"
hass.states.async_set(entry.entity_id, "school")
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 2
assert service_calls[1].data["some"] == "is_not_home - event - test_event2"
async def test_if_state_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for turn_on and turn_off conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(entry.entity_id, STATE_HOME)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "is_home",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": (
"is_home "
"- {{ trigger.platform }} "
"- {{ trigger.event.event_type }}"
)
},
},
},
]
},
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["some"] == "is_home - event - test_event1"

View File

@@ -0,0 +1,386 @@
"""The tests for Device Tracker device triggers."""
import pytest
from pytest_unordered import unordered
import voluptuous_serialize
from homeassistant.components import automation, zone
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.device_tracker import DOMAIN, device_trigger
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_get_device_automations
@pytest.fixture(autouse=True, name="stub_blueprint_populate")
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder."""
AWAY_LATITUDE = 32.881011
AWAY_LONGITUDE = -117.234758
HOME_LATITUDE = 32.880837
HOME_LONGITUDE = -117.237561
@pytest.fixture(autouse=True)
def setup_zone(hass: HomeAssistant) -> None:
"""Create test zone."""
hass.loop.run_until_complete(
async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": HOME_LATITUDE,
"longitude": HOME_LONGITUDE,
"radius": 250,
}
},
)
)
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a device_tracker."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for trigger in ("leaves", "enters")
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
[
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
],
)
async def test_get_triggers_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for trigger in ("leaves", "enters")
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert triggers == unordered(expected_triggers)
async def test_if_fires_on_zone_change(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for enter and leave triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(
entry.entity_id,
"state",
{"latitude": AWAY_LATITUDE, "longitude": AWAY_LONGITUDE},
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "enters",
"zone": "zone.test",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"enter "
"- {{ trigger.platform }} "
"- {{ trigger.entity_id }} "
"- {{ "
" trigger.from_state.attributes.longitude|round(3) "
" }} "
"- {{ trigger.to_state.attributes.longitude|round(3) }}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "leaves",
"zone": "zone.test",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"leave "
"- {{ trigger.platform }} "
"- {{ trigger.entity_id }} "
"- {{ "
" trigger.from_state.attributes.longitude|round(3) "
" }} "
"- {{ trigger.to_state.attributes.longitude|round(3)}}"
)
},
},
},
]
},
)
# Fake that the entity is entering.
hass.states.async_set(
entry.entity_id,
"state",
{"latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE},
)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"enter - device - {entry.entity_id} - -117.235 - -117.238"
)
# Fake that the entity is leaving.
hass.states.async_set(
entry.entity_id,
"state",
{"latitude": AWAY_LATITUDE, "longitude": AWAY_LONGITUDE},
)
await hass.async_block_till_done()
assert len(service_calls) == 2
assert (
service_calls[1].data["some"]
== f"leave - device - {entry.entity_id} - -117.238 - -117.235"
)
async def test_if_fires_on_zone_change_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
service_calls: list[ServiceCall],
) -> None:
"""Test for enter and leave triggers firing."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
hass.states.async_set(
entry.entity_id,
"state",
{"latitude": AWAY_LATITUDE, "longitude": AWAY_LONGITUDE},
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "enters",
"zone": "zone.test",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"enter "
"- {{ trigger.platform }} "
"- {{ trigger.entity_id }} "
"- {{ "
" trigger.from_state.attributes.longitude|round(3) "
" }} "
"- {{ trigger.to_state.attributes.longitude|round(3) }}"
)
},
},
},
]
},
)
# Fake that the entity is entering.
hass.states.async_set(
entry.entity_id,
"state",
{"latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE},
)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert (
service_calls[0].data["some"]
== f"enter - device - {entry.entity_id} - -117.235 - -117.238"
)
async def test_get_trigger_capabilities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a device_tracker trigger."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": DOMAIN,
"type": "enters",
"device_id": device_entry.id,
"entity_id": entity_entry.id,
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "zone",
"required": True,
"type": "select",
"options": [("zone.test", "test"), ("zone.home", "test home")],
}
]
async def test_get_trigger_capabilities_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from a device_tracker trigger."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": DOMAIN,
"type": "enters",
"device_id": device_entry.id,
"entity_id": entity_entry.entity_id,
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "zone",
"required": True,
"type": "select",
"options": [("zone.test", "test"), ("zone.home", "test home")],
}
]

View File

@@ -0,0 +1,738 @@
"""The tests for the device tracker component."""
from collections.abc import Generator
from datetime import datetime, timedelta
import json
import logging
import os
from unittest.mock import call, patch
import pytest
from homeassistant.components import device_tracker, zone
from homeassistant.components.device_tracker import SourceType, const, legacy
from homeassistant.const import (
ATTR_ENTITY_PICTURE,
ATTR_FRIENDLY_NAME,
ATTR_GPS_ACCURACY,
ATTR_ICON,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_PLATFORM,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import discovery
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.json import JSONEncoder
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from . import common
from .common import MockScanner, mock_legacy_device_tracker_setup
from tests.common import (
assert_setup_component,
async_fire_time_changed,
mock_registry,
mock_restore_cache,
patch_yaml_files,
)
TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: "test"}}
_LOGGER = logging.getLogger(__name__)
@pytest.fixture(name="yaml_devices")
def mock_yaml_devices(hass: HomeAssistant) -> Generator[str]:
"""Get a path for storing yaml devices."""
yaml_devices = hass.config.path(legacy.YAML_DEVICES)
if os.path.isfile(yaml_devices):
os.remove(yaml_devices)
yield yaml_devices
if os.path.isfile(yaml_devices):
os.remove(yaml_devices)
@pytest.fixture(autouse=True)
def _mock_legacy_device_tracker_setup(
hass: HomeAssistant, mock_legacy_device_scanner: MockScanner
) -> None:
"""Mock legacy device tracker setup."""
mock_legacy_device_tracker_setup(hass, mock_legacy_device_scanner)
async def test_is_on(hass: HomeAssistant) -> None:
"""Test is_on method."""
entity_id = f"{const.DOMAIN}.test"
hass.states.async_set(entity_id, STATE_HOME)
assert device_tracker.is_on(hass, entity_id)
hass.states.async_set(entity_id, STATE_NOT_HOME)
assert not device_tracker.is_on(hass, entity_id)
async def test_reading_broken_yaml_config(hass: HomeAssistant) -> None:
"""Test when known devices contains invalid data."""
files = {
"empty.yaml": "",
"nodict.yaml": "100",
"badkey.yaml": "@:\n name: Device",
"noname.yaml": "my_device:\n",
"allok.yaml": "My Device:\n name: Device",
"oneok.yaml": "My Device!:\n name: Device\nbad_device:\n nme: Device",
}
args = {"hass": hass, "consider_home": timedelta(seconds=60)}
with patch_yaml_files(files):
assert await legacy.async_load_config("empty.yaml", **args) == []
assert await legacy.async_load_config("nodict.yaml", **args) == []
assert await legacy.async_load_config("noname.yaml", **args) == []
assert await legacy.async_load_config("badkey.yaml", **args) == []
res = await legacy.async_load_config("allok.yaml", **args)
assert len(res) == 1
assert res[0].name == "Device"
assert res[0].dev_id == "my_device"
res = await legacy.async_load_config("oneok.yaml", **args)
assert len(res) == 1
assert res[0].name == "Device"
assert res[0].dev_id == "my_device"
async def test_reading_yaml_config(hass: HomeAssistant, yaml_devices: str) -> None:
"""Test the rendering of the YAML configuration."""
dev_id = "test"
device = legacy.Device(
hass,
timedelta(seconds=180),
True,
dev_id,
"AB:CD:EF:GH:IJ",
"Test name",
picture="http://test.picture",
icon="mdi:kettle",
)
await hass.async_add_executor_job(
legacy.update_config, yaml_devices, dev_id, device
)
loaded_config = None
original_async_load_config = legacy.async_load_config
async def capture_load_config(*args, **kwargs):
nonlocal loaded_config
loaded_config = await original_async_load_config(*args, **kwargs)
return loaded_config
with patch(
"homeassistant.components.device_tracker.legacy.async_load_config",
capture_load_config,
):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
config = loaded_config[0]
assert device.dev_id == config.dev_id
assert device.track == config.track
assert device.mac == config.mac
assert device.config_picture == config.config_picture
assert device.consider_home == config.consider_home
assert device.icon == config.icon
assert f"test.{device_tracker.DOMAIN}" in hass.config.components
@patch("homeassistant.components.device_tracker.const.LOGGER.warning")
async def test_duplicate_mac_dev_id(mock_warning, hass: HomeAssistant) -> None:
"""Test adding duplicate MACs or device IDs to DeviceTracker."""
devices = [
legacy.Device(
hass, True, True, "my_device", "AB:01", "My device", None, None, False
),
legacy.Device(
hass, True, True, "your_device", "AB:01", "Your device", None, None, False
),
]
legacy.DeviceTracker(hass, False, True, {}, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert (
mock_warning.call_count == 1
), "The only warning call should be duplicates (check DEBUG)"
args, _ = mock_warning.call_args
assert "Duplicate device MAC" in args[0], "Duplicate MAC warning expected"
mock_warning.reset_mock()
devices = [
legacy.Device(
hass, True, True, "my_device", "AB:01", "My device", None, None, False
),
legacy.Device(
hass, True, True, "my_device", None, "Your device", None, None, False
),
]
legacy.DeviceTracker(hass, False, True, {}, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert (
mock_warning.call_count == 1
), "The only warning call should be duplicates (check DEBUG)"
args, _ = mock_warning.call_args
assert "Duplicate device IDs" in args[0], "Duplicate device IDs warning expected"
async def test_setup_without_yaml_file(hass: HomeAssistant, yaml_devices: str) -> None:
"""Test with no YAML file."""
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
async def test_gravatar(hass: HomeAssistant) -> None:
"""Test the Gravatar generation."""
dev_id = "test"
device = legacy.Device(
hass,
timedelta(seconds=180),
True,
dev_id,
"AB:CD:EF:GH:IJ",
"Test name",
gravatar="test@example.com",
)
gravatar_url = (
"https://www.gravatar.com/avatar/"
"55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar"
)
assert device.config_picture == gravatar_url
async def test_gravatar_and_picture(hass: HomeAssistant) -> None:
"""Test that Gravatar overrides picture."""
dev_id = "test"
device = legacy.Device(
hass,
timedelta(seconds=180),
True,
dev_id,
"AB:CD:EF:GH:IJ",
"Test name",
picture="http://test.picture",
gravatar="test@example.com",
)
gravatar_url = (
"https://www.gravatar.com/avatar/"
"55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar"
)
assert device.config_picture == gravatar_url
@patch("homeassistant.components.device_tracker.legacy.DeviceTracker.see")
@patch("homeassistant.components.demo.device_tracker.setup_scanner", autospec=True)
async def test_discover_platform(
mock_demo_setup_scanner, mock_see, hass: HomeAssistant
) -> None:
"""Test discovery of device_tracker demo platform."""
await async_setup_component(hass, "homeassistant", {})
await async_setup_component(hass, device_tracker.DOMAIN, {})
# async_block_till_done is intentionally missing here so we
# can verify async_load_platform still works without it
with patch("homeassistant.components.device_tracker.legacy.update_config"):
await discovery.async_load_platform(
hass, device_tracker.DOMAIN, "demo", {"test_key": "test_val"}, {"bla": {}}
)
await hass.async_block_till_done()
assert device_tracker.DOMAIN in hass.config.components
assert mock_demo_setup_scanner.called
assert mock_demo_setup_scanner.call_args[0] == (
hass,
{},
mock_see,
{"test_key": "test_val"},
)
async def test_discover_platform_missing_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test discovery of device_tracker missing platform."""
await async_setup_component(hass, "homeassistant", {})
await async_setup_component(hass, device_tracker.DOMAIN, {})
# async_block_till_done is intentionally missing here so we
# can verify async_load_platform still works without it
with patch("homeassistant.components.device_tracker.legacy.update_config"):
await discovery.async_load_platform(
hass,
device_tracker.DOMAIN,
"its_not_there",
{"test_key": "test_val"},
{"bla": {}},
)
await hass.async_block_till_done()
assert device_tracker.DOMAIN in hass.config.components
assert (
"Unable to prepare setup for platform 'its_not_there.device_tracker'"
in caplog.text
)
# This test should not generate an unhandled exception
async def test_update_stale(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
mock_legacy_device_scanner: MockScanner,
) -> None:
"""Test stalled update."""
mock_legacy_device_scanner.reset()
mock_legacy_device_scanner.come_home("DEV1")
now = dt_util.utcnow()
register_time = datetime(now.year + 1, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(now.year + 1, 9, 15, 23, 1, tzinfo=dt_util.UTC)
with (
patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=register_time,
),
assert_setup_component(1, device_tracker.DOMAIN),
):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "test",
device_tracker.CONF_CONSIDER_HOME: 59,
}
},
)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.dev1").state == STATE_HOME
mock_legacy_device_scanner.leave_home("DEV1")
with patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=scan_time,
):
async_fire_time_changed(hass, scan_time)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.dev1").state == STATE_NOT_HOME
async def test_entity_attributes(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
) -> None:
"""Test the entity attributes."""
devices = mock_device_tracker_conf
dev_id = "test_entity"
entity_id = f"{const.DOMAIN}.{dev_id}"
friendly_name = "Paulus"
picture = "http://placehold.it/200x200"
icon = "mdi:kettle"
device = legacy.Device(
hass,
timedelta(seconds=180),
True,
dev_id,
None,
friendly_name,
picture,
icon=icon,
)
devices.append(device)
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
attrs = hass.states.get(entity_id).attributes
assert friendly_name == attrs.get(ATTR_FRIENDLY_NAME)
assert icon == attrs.get(ATTR_ICON)
assert picture == attrs.get(ATTR_ENTITY_PICTURE)
@patch("homeassistant.components.device_tracker.legacy.DeviceTracker.async_see")
async def test_see_service(mock_see, hass: HomeAssistant) -> None:
"""Test the see service with a unicode dev_id and NO MAC."""
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
params = {
"dev_id": "some_device",
"host_name": "example.com",
"location_name": "Work",
"gps": [0.3, 0.8],
"attributes": {"test": "test"},
}
common.async_see(hass, **params)
await hass.async_block_till_done()
assert mock_see.call_count == 1
assert mock_see.call_count == 1
assert mock_see.call_args == call(**params)
mock_see.reset_mock()
params["dev_id"] += chr(233) # e' acute accent from icloud
common.async_see(hass, **params)
await hass.async_block_till_done()
assert mock_see.call_count == 1
assert mock_see.call_count == 1
assert mock_see.call_args == call(**params)
async def test_see_service_guard_config_entry(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
) -> None:
"""Test the guard if the device is registered in the entity registry."""
dev_id = "test"
entity_id = f"{const.DOMAIN}.{dev_id}"
mock_registry(
hass,
{
entity_id: RegistryEntry(
entity_id=entity_id, unique_id=1, platform=const.DOMAIN
)
},
)
devices = mock_device_tracker_conf
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
params = {"dev_id": dev_id, "gps": [0.3, 0.8]}
common.async_see(hass, **params)
await hass.async_block_till_done()
assert not devices
async def test_new_device_event_fired(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
) -> None:
"""Test that the device tracker will fire an event."""
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
test_events = []
@callback
def listener(event):
"""Record that our event got called."""
test_events.append(event)
hass.bus.async_listen("device_tracker_new_device", listener)
common.async_see(hass, "mac_1", host_name="hello")
common.async_see(hass, "mac_1", host_name="hello")
await hass.async_block_till_done()
assert len(test_events) == 1
# Assert we can serialize the event
json.dumps(test_events[0].as_dict(), cls=JSONEncoder)
assert test_events[0].data == {
"entity_id": "device_tracker.hello",
"host_name": "hello",
"mac": "MAC_1",
}
async def test_duplicate_yaml_keys(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
) -> None:
"""Test that the device tracker will not generate invalid YAML."""
devices = mock_device_tracker_conf
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
common.async_see(hass, "mac_1", host_name="hello")
common.async_see(hass, "mac_2", host_name="hello")
await hass.async_block_till_done()
assert len(devices) == 2
assert devices[0].dev_id != devices[1].dev_id
async def test_invalid_dev_id(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
) -> None:
"""Test that the device tracker will not allow invalid dev ids."""
devices = mock_device_tracker_conf
with assert_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
common.async_see(hass, dev_id="hello-world")
await hass.async_block_till_done()
assert not devices
async def test_see_state(hass: HomeAssistant, yaml_devices: str) -> None:
"""Test device tracker see records state correctly."""
assert await async_setup_component(hass, device_tracker.DOMAIN, TEST_PLATFORM)
await hass.async_block_till_done()
params = {
"mac": "AA:BB:CC:DD:EE:FF",
"dev_id": "some_device",
"host_name": "example.com",
"location_name": "Work",
"gps": [0.3, 0.8],
"gps_accuracy": 1,
"battery": 100,
"attributes": {"test": "test", "number": 1},
}
common.async_see(hass, **params)
await hass.async_block_till_done()
config = await legacy.async_load_config(yaml_devices, hass, timedelta(seconds=0))
assert len(config) == 1
state = hass.states.get("device_tracker.example_com")
attrs = state.attributes
assert state.state == "Work"
assert state.object_id == "example_com"
assert state.name == "example.com"
assert attrs["friendly_name"] == "example.com"
assert attrs["battery"] == 100
assert attrs["latitude"] == 0.3
assert attrs["longitude"] == 0.8
assert attrs["test"] == "test"
assert attrs["gps_accuracy"] == 1
assert attrs["source_type"] == "gps"
assert attrs["number"] == 1
async def test_see_passive_zone_state(
hass: HomeAssistant,
mock_device_tracker_conf: list[legacy.Device],
mock_legacy_device_scanner: MockScanner,
) -> None:
"""Test that the device tracker sets gps for passive trackers."""
now = dt_util.utcnow()
register_time = datetime(now.year + 1, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(now.year + 1, 9, 15, 23, 1, tzinfo=dt_util.UTC)
with assert_setup_component(1, zone.DOMAIN):
zone_info = {
"name": "Home",
"latitude": 1,
"longitude": 2,
"radius": 250,
"passive": False,
}
await async_setup_component(hass, zone.DOMAIN, {"zone": zone_info})
await hass.async_block_till_done()
mock_legacy_device_scanner.reset()
mock_legacy_device_scanner.come_home("dev1")
with (
patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=register_time,
),
assert_setup_component(1, device_tracker.DOMAIN),
):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "test",
device_tracker.CONF_CONSIDER_HOME: 59,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("device_tracker.dev1")
attrs = state.attributes
assert state.state == STATE_HOME
assert state.object_id == "dev1"
assert state.name == "dev1"
assert attrs.get("friendly_name") == "dev1"
assert attrs.get("latitude") == 1
assert attrs.get("longitude") == 2
assert attrs.get("gps_accuracy") == 0
assert attrs.get("source_type") == SourceType.ROUTER
mock_legacy_device_scanner.leave_home("dev1")
with patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=scan_time,
):
async_fire_time_changed(hass, scan_time)
await hass.async_block_till_done()
state = hass.states.get("device_tracker.dev1")
attrs = state.attributes
assert state.state == STATE_NOT_HOME
assert state.object_id == "dev1"
assert state.name == "dev1"
assert attrs.get("friendly_name") == "dev1"
assert attrs.get("latitude") is None
assert attrs.get("longitude") is None
assert attrs.get("gps_accuracy") is None
assert attrs.get("source_type") == SourceType.ROUTER
@patch("homeassistant.components.device_tracker.const.LOGGER.warning")
async def test_see_failures(
mock_warning, hass: HomeAssistant, mock_device_tracker_conf: list[legacy.Device]
) -> None:
"""Test that the device tracker see failures."""
devices = mock_device_tracker_conf
tracker = legacy.DeviceTracker(hass, timedelta(seconds=60), 0, {}, [])
# MAC is not a string (but added)
await tracker.async_see(mac=567, host_name="Number MAC")
# No device id or MAC(not added)
with pytest.raises(HomeAssistantError):
await tracker.async_see()
assert mock_warning.call_count == 0
# Ignore gps on invalid GPS (both added & warnings)
await tracker.async_see(mac="mac_1_bad_gps", gps=1)
await tracker.async_see(mac="mac_2_bad_gps", gps=[1])
await tracker.async_see(mac="mac_3_bad_gps", gps="gps")
await hass.async_block_till_done()
assert mock_warning.call_count == 3
assert len(devices) == 4
async def test_async_added_to_hass(hass: HomeAssistant) -> None:
"""Test restoring state."""
attr = {
ATTR_LONGITUDE: 18,
ATTR_LATITUDE: -33,
const.ATTR_SOURCE_TYPE: "gps",
ATTR_GPS_ACCURACY: 2,
const.ATTR_BATTERY: 100,
}
mock_restore_cache(hass, [State("device_tracker.jk", "home", attr)])
path = hass.config.path(legacy.YAML_DEVICES)
files = {path: "jk:\n name: JK Phone\n track: True"}
with patch_yaml_files(files):
assert await async_setup_component(hass, device_tracker.DOMAIN, {})
await hass.async_block_till_done()
state = hass.states.get("device_tracker.jk")
assert state
assert state.state == "home"
for key, val in attr.items():
atr = state.attributes.get(key)
assert atr == val, f"{key}={atr} expected: {val}"
async def test_bad_platform(hass: HomeAssistant) -> None:
"""Test bad platform."""
config = {"device_tracker": [{"platform": "bad_platform"}]}
with assert_setup_component(0, device_tracker.DOMAIN):
assert await async_setup_component(hass, device_tracker.DOMAIN, config)
await hass.async_block_till_done()
assert f"bad_platform.{device_tracker.DOMAIN}" not in hass.config.components
async def test_adding_unknown_device_to_config(
mock_device_tracker_conf: list[legacy.Device],
hass: HomeAssistant,
mock_legacy_device_scanner: MockScanner,
) -> None:
"""Test the adding of unknown devices to configuration file."""
mock_legacy_device_scanner.reset()
mock_legacy_device_scanner.come_home("DEV1")
await async_setup_component(
hass, device_tracker.DOMAIN, {device_tracker.DOMAIN: {CONF_PLATFORM: "test"}}
)
await hass.async_block_till_done()
assert len(mock_device_tracker_conf) == 1
device = mock_device_tracker_conf[0]
assert device.dev_id == "dev1"
assert device.track
async def test_picture_and_icon_on_see_discovery(
mock_device_tracker_conf: list[legacy.Device], hass: HomeAssistant
) -> None:
"""Test that picture and icon are set in initial see."""
tracker = legacy.DeviceTracker(hass, timedelta(seconds=60), False, {}, [])
await tracker.async_see(dev_id=11, picture="pic_url", icon="mdi:icon")
await hass.async_block_till_done()
assert len(mock_device_tracker_conf) == 1
assert mock_device_tracker_conf[0].icon == "mdi:icon"
assert mock_device_tracker_conf[0].entity_picture == "pic_url"
async def test_backward_compatibility_for_track_new(
mock_device_tracker_conf: list[legacy.Device], hass: HomeAssistant
) -> None:
"""Test backward compatibility for track new."""
tracker = legacy.DeviceTracker(
hass, timedelta(seconds=60), False, {device_tracker.CONF_TRACK_NEW: True}, []
)
await tracker.async_see(dev_id=13)
await hass.async_block_till_done()
assert len(mock_device_tracker_conf) == 1
assert mock_device_tracker_conf[0].track is False
async def test_old_style_track_new_is_skipped(
mock_device_tracker_conf: list[legacy.Device], hass: HomeAssistant
) -> None:
"""Test old style config is skipped."""
tracker = legacy.DeviceTracker(
hass, timedelta(seconds=60), None, {device_tracker.CONF_TRACK_NEW: False}, []
)
await tracker.async_see(dev_id=14)
await hass.async_block_till_done()
assert len(mock_device_tracker_conf) == 1
assert mock_device_tracker_conf[0].track is False
def test_see_schema_allowing_ios_calls() -> None:
"""Test SEE service schema allows extra keys.
Temp work around because the iOS app sends incorrect data.
"""
device_tracker.SERVICE_SEE_PAYLOAD_SCHEMA(
{
"dev_id": "Test",
"battery": 35,
"battery_status": "Not Charging",
"gps": [10.0, 10.0],
"gps_accuracy": 300,
"hostname": "beer",
}
)

View File

@@ -0,0 +1,46 @@
"""Tests for the legacy device tracker component."""
from unittest.mock import mock_open, patch
from homeassistant.components.device_tracker import legacy
from homeassistant.core import HomeAssistant
from homeassistant.util.yaml import dump
from tests.common import patch_yaml_files
def test_remove_device_from_config(hass: HomeAssistant) -> None:
"""Test the removal of a device from a config."""
yaml_devices = {
"test": {
"hide_if_away": True,
"mac": "00:11:22:33:44:55",
"name": "Test name",
"picture": "/local/test.png",
"track": True,
},
"test2": {
"hide_if_away": True,
"mac": "00:ab:cd:33:44:55",
"name": "Test2",
"picture": "/local/test2.png",
"track": True,
},
}
mopen = mock_open()
files = {legacy.YAML_DEVICES: dump(yaml_devices)}
with (
patch_yaml_files(files, True),
patch("homeassistant.components.device_tracker.legacy.open", mopen),
):
legacy.remove_device_from_config(hass, "test")
mopen().write.assert_called_once_with(
"test2:\n"
" hide_if_away: true\n"
" mac: 00:ab:cd:33:44:55\n"
" name: Test2\n"
" picture: /local/test2.png\n"
" track: true\n"
)