Clean up unnecessary registry mocks from integration tests (#87763)

This commit is contained in:
Franck Nijhof 2023-02-09 10:43:45 +01:00 committed by GitHub
parent 59890cca68
commit 330e1c6cbb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
45 changed files with 544 additions and 628 deletions

View file

@ -14,12 +14,7 @@ from homeassistant.util.dt import utcnow
from . import API_POINT_URL, init_integration from . import API_POINT_URL, init_integration
from tests.common import ( from tests.common import MockConfigEntry, async_fire_time_changed, load_fixture
MockConfigEntry,
async_fire_time_changed,
load_fixture,
mock_device_registry,
)
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
@ -202,7 +197,9 @@ async def test_unload_entry(
@pytest.mark.parametrize("old_identifier", ((DOMAIN, 123, 456), (DOMAIN, "123", "456"))) @pytest.mark.parametrize("old_identifier", ((DOMAIN, 123, 456), (DOMAIN, "123", "456")))
async def test_migrate_device_entry(hass, aioclient_mock, old_identifier): async def test_migrate_device_entry(
hass, aioclient_mock, old_identifier, device_registry
):
"""Test device_info identifiers migration.""" """Test device_info identifiers migration."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -219,15 +216,14 @@ async def test_migrate_device_entry(hass, aioclient_mock, old_identifier):
aioclient_mock.get(API_POINT_URL, text=load_fixture("valid_station.json", "airly")) aioclient_mock.get(API_POINT_URL, text=load_fixture("valid_station.json", "airly"))
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_reg = mock_device_registry(hass) device_entry = device_registry.async_get_or_create(
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id, identifiers={old_identifier} config_entry_id=config_entry.entry_id, identifiers={old_identifier}
) )
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
migrated_device_entry = device_reg.async_get_or_create( migrated_device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, "123-456")} config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, "123-456")}
) )
assert device_entry.id == migrated_device_entry.id assert device_entry.id == migrated_device_entry.id

View file

@ -10,39 +10,25 @@ from tests.common import (
MockConfigEntry, MockConfigEntry,
async_get_device_automations, async_get_device_automations,
async_mock_service, async_mock_service,
mock_device_registry,
mock_registry,
) )
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture @pytest.fixture
def calls(hass): def calls(hass):
"""Track calls to a mock service.""" """Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") return async_mock_service(hass, "test", "automation")
async def test_get_triggers(hass, device_reg, entity_reg): async def test_get_triggers(hass, device_registry, entity_registry):
"""Test we get the expected triggers from a arcam_fmj.""" """Test we get the expected triggers from a arcam_fmj."""
config_entry = MockConfigEntry(domain=DOMAIN, data={}) config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, "host", 1234)}, identifiers={(DOMAIN, "host", 1234)},
) )
entity_reg.async_get_or_create( entity_registry.async_get_or_create(
"media_player", DOMAIN, "5678", device_id=device_entry.id "media_player", DOMAIN, "5678", device_id=device_entry.id
) )
expected_triggers = [ expected_triggers = [

View file

@ -8,12 +8,10 @@ from homeassistant.components.broadlink.device import get_domains
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import async_entries_for_device from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import get_device from . import get_device
from tests.common import mock_device_registry, mock_registry
DEVICE_FACTORY = "homeassistant.components.broadlink.device.blk.gendevice" DEVICE_FACTORY = "homeassistant.components.broadlink.device.blk.gendevice"
@ -248,13 +246,14 @@ async def test_device_setup_get_fwversion_os_error(hass: HomeAssistant) -> None:
assert forward_entries == domains assert forward_entries == domains
async def test_device_setup_registry(hass: HomeAssistant) -> None: async def test_device_setup_registry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we register the device and the entries correctly.""" """Test we register the device and the entries correctly."""
device = get_device("Office") device = get_device("Office")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -269,7 +268,7 @@ async def test_device_setup_registry(hass: HomeAssistant) -> None:
assert device_entry.manufacturer == device.manufacturer assert device_entry.manufacturer == device.manufacturer
assert device_entry.sw_version == device.fwversion assert device_entry.sw_version == device.fwversion
for entry in async_entries_for_device(entity_registry, device_entry.id): for entry in er.async_entries_for_device(entity_registry, device_entry.id):
assert ( assert (
hass.states.get(entry.entity_id) hass.states.get(entry.entity_id)
.attributes[ATTR_FRIENDLY_NAME] .attributes[ATTR_FRIENDLY_NAME]
@ -334,13 +333,14 @@ async def test_device_unload_update_failed(hass: HomeAssistant) -> None:
assert mock_forward.call_count == 0 assert mock_forward.call_count == 0
async def test_device_update_listener(hass: HomeAssistant) -> None: async def test_device_update_listener(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we update device and entity registry when the entry is renamed.""" """Test we update device and entity registry when the entry is renamed."""
device = get_device("Office") device = get_device("Office")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -352,7 +352,7 @@ async def test_device_update_listener(hass: HomeAssistant) -> None:
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
assert device_entry.name == "New Name" assert device_entry.name == "New Name"
for entry in async_entries_for_device(entity_registry, device_entry.id): for entry in er.async_entries_for_device(entity_registry, device_entry.id):
assert ( assert (
hass.states.get(entry.entity_id) hass.states.get(entry.entity_id)
.attributes[ATTR_FRIENDLY_NAME] .attributes[ATTR_FRIENDLY_NAME]

View file

@ -11,12 +11,10 @@ from homeassistant.components.remote import (
) )
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON, Platform from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import async_entries_for_device from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import get_device from . import get_device
from tests.common import mock_device_registry, mock_registry
REMOTE_DEVICES = ["Entrance", "Living Room", "Office", "Garage"] REMOTE_DEVICES = ["Entrance", "Living Room", "Office", "Garage"]
IR_PACKET = ( IR_PACKET = (
@ -25,17 +23,19 @@ IR_PACKET = (
) )
async def test_remote_setup_works(hass: HomeAssistant) -> None: async def test_remote_setup_works(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful setup with all remotes.""" """Test a successful setup with all remotes."""
for device in map(get_device, REMOTE_DEVICES): for device in map(get_device, REMOTE_DEVICES):
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
remotes = [entry for entry in entries if entry.domain == Platform.REMOTE] remotes = [entry for entry in entries if entry.domain == Platform.REMOTE]
assert len(remotes) == 1 assert len(remotes) == 1
@ -48,17 +48,19 @@ async def test_remote_setup_works(hass: HomeAssistant) -> None:
assert mock_setup.api.auth.call_count == 1 assert mock_setup.api.auth.call_count == 1
async def test_remote_send_command(hass: HomeAssistant) -> None: async def test_remote_send_command(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sending a command with all remotes.""" """Test sending a command with all remotes."""
for device in map(get_device, REMOTE_DEVICES): for device in map(get_device, REMOTE_DEVICES):
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
remotes = [entry for entry in entries if entry.domain == Platform.REMOTE] remotes = [entry for entry in entries if entry.domain == Platform.REMOTE]
assert len(remotes) == 1 assert len(remotes) == 1
@ -75,17 +77,19 @@ async def test_remote_send_command(hass: HomeAssistant) -> None:
assert mock_setup.api.auth.call_count == 1 assert mock_setup.api.auth.call_count == 1
async def test_remote_turn_off_turn_on(hass: HomeAssistant) -> None: async def test_remote_turn_off_turn_on(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we do not send commands if the remotes are off.""" """Test we do not send commands if the remotes are off."""
for device in map(get_device, REMOTE_DEVICES): for device in map(get_device, REMOTE_DEVICES):
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
remotes = [entry for entry in entries if entry.domain == Platform.REMOTE] remotes = [entry for entry in entries if entry.domain == Platform.REMOTE]
assert len(remotes) == 1 assert len(remotes) == 1

View file

@ -5,16 +5,20 @@ from homeassistant.components.broadlink.const import DOMAIN
from homeassistant.components.broadlink.updater import BroadlinkSP4UpdateManager from homeassistant.components.broadlink.updater import BroadlinkSP4UpdateManager
from homeassistant.const import ATTR_FRIENDLY_NAME, Platform from homeassistant.const import ATTR_FRIENDLY_NAME, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_component import async_update_entity from homeassistant.helpers.entity_component import async_update_entity
from homeassistant.helpers.entity_registry import async_entries_for_device
from homeassistant.util import dt from homeassistant.util import dt
from . import get_device from . import get_device
from tests.common import async_fire_time_changed, mock_device_registry, mock_registry from tests.common import async_fire_time_changed
async def test_a1_sensor_setup(hass: HomeAssistant) -> None: async def test_a1_sensor_setup(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful e-Sensor setup.""" """Test a successful e-Sensor setup."""
device = get_device("Bedroom") device = get_device("Bedroom")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
@ -26,16 +30,13 @@ async def test_a1_sensor_setup(hass: HomeAssistant) -> None:
"noise": 1, "noise": 1,
} }
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors_raw.call_count == 1 assert mock_api.check_sensors_raw.call_count == 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 5 assert len(sensors) == 5
@ -55,7 +56,11 @@ async def test_a1_sensor_setup(hass: HomeAssistant) -> None:
} }
async def test_a1_sensor_update(hass: HomeAssistant) -> None: async def test_a1_sensor_update(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful e-Sensor update.""" """Test a successful e-Sensor update."""
device = get_device("Bedroom") device = get_device("Bedroom")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
@ -67,15 +72,12 @@ async def test_a1_sensor_update(hass: HomeAssistant) -> None:
"noise": 1, "noise": 1,
} }
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 5 assert len(sensors) == 5
@ -105,22 +107,23 @@ async def test_a1_sensor_update(hass: HomeAssistant) -> None:
} }
async def test_rm_pro_sensor_setup(hass: HomeAssistant) -> None: async def test_rm_pro_sensor_setup(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful RM pro sensor setup.""" """Test a successful RM pro sensor setup."""
device = get_device("Office") device = get_device("Office")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 18.2} mock_api.check_sensors.return_value = {"temperature": 18.2}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count == 1 assert mock_api.check_sensors.call_count == 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 1 assert len(sensors) == 1
@ -134,21 +137,22 @@ async def test_rm_pro_sensor_setup(hass: HomeAssistant) -> None:
assert sensors_and_states == {(f"{device.name} Temperature", "18.2")} assert sensors_and_states == {(f"{device.name} Temperature", "18.2")}
async def test_rm_pro_sensor_update(hass: HomeAssistant) -> None: async def test_rm_pro_sensor_update(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful RM pro sensor update.""" """Test a successful RM pro sensor update."""
device = get_device("Office") device = get_device("Office")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 25.7} mock_api.check_sensors.return_value = {"temperature": 25.7}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 1 assert len(sensors) == 1
@ -166,7 +170,11 @@ async def test_rm_pro_sensor_update(hass: HomeAssistant) -> None:
assert sensors_and_states == {(f"{device.name} Temperature", "25.8")} assert sensors_and_states == {(f"{device.name} Temperature", "25.8")}
async def test_rm_pro_filter_crazy_temperature(hass: HomeAssistant) -> None: async def test_rm_pro_filter_crazy_temperature(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we filter a crazy temperature variation. """Test we filter a crazy temperature variation.
Firmware issue. See https://github.com/home-assistant/core/issues/42100. Firmware issue. See https://github.com/home-assistant/core/issues/42100.
@ -175,15 +183,12 @@ async def test_rm_pro_filter_crazy_temperature(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 22.9} mock_api.check_sensors.return_value = {"temperature": 22.9}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 1 assert len(sensors) == 1
@ -201,42 +206,44 @@ async def test_rm_pro_filter_crazy_temperature(hass: HomeAssistant) -> None:
assert sensors_and_states == {(f"{device.name} Temperature", "22.9")} assert sensors_and_states == {(f"{device.name} Temperature", "22.9")}
async def test_rm_mini3_no_sensor(hass: HomeAssistant) -> None: async def test_rm_mini3_no_sensor(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we do not set up sensors for RM mini 3.""" """Test we do not set up sensors for RM mini 3."""
device = get_device("Entrance") device = get_device("Entrance")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 0} mock_api.check_sensors.return_value = {"temperature": 0}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count <= 1 assert mock_api.check_sensors.call_count <= 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 0 assert len(sensors) == 0
async def test_rm4_pro_hts2_sensor_setup(hass: HomeAssistant) -> None: async def test_rm4_pro_hts2_sensor_setup(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful RM4 pro sensor setup with HTS2 cable.""" """Test a successful RM4 pro sensor setup with HTS2 cable."""
device = get_device("Garage") device = get_device("Garage")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 22.5, "humidity": 43.7} mock_api.check_sensors.return_value = {"temperature": 22.5, "humidity": 43.7}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count == 1 assert mock_api.check_sensors.call_count == 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 2 assert len(sensors) == 2
@ -253,21 +260,22 @@ async def test_rm4_pro_hts2_sensor_setup(hass: HomeAssistant) -> None:
} }
async def test_rm4_pro_hts2_sensor_update(hass: HomeAssistant) -> None: async def test_rm4_pro_hts2_sensor_update(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful RM4 pro sensor update with HTS2 cable.""" """Test a successful RM4 pro sensor update with HTS2 cable."""
device = get_device("Garage") device = get_device("Garage")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 16.7, "humidity": 34.1} mock_api.check_sensors.return_value = {"temperature": 16.7, "humidity": 34.1}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 2 assert len(sensors) == 2
@ -288,27 +296,32 @@ async def test_rm4_pro_hts2_sensor_update(hass: HomeAssistant) -> None:
} }
async def test_rm4_pro_no_sensor(hass: HomeAssistant) -> None: async def test_rm4_pro_no_sensor(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we do not set up sensors for RM4 pro without HTS2 cable.""" """Test we do not set up sensors for RM4 pro without HTS2 cable."""
device = get_device("Garage") device = get_device("Garage")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 0, "humidity": 0} mock_api.check_sensors.return_value = {"temperature": 0, "humidity": 0}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count <= 1 assert mock_api.check_sensors.call_count <= 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = {entry for entry in entries if entry.domain == Platform.SENSOR} sensors = {entry for entry in entries if entry.domain == Platform.SENSOR}
assert len(sensors) == 0 assert len(sensors) == 0
async def test_scb1e_sensor_setup(hass: HomeAssistant) -> None: async def test_scb1e_sensor_setup(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful SCB1E sensor setup.""" """Test a successful SCB1E sensor setup."""
device = get_device("Dining room") device = get_device("Dining room")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
@ -324,16 +337,13 @@ async def test_scb1e_sensor_setup(hass: HomeAssistant) -> None:
"childlock": 0, "childlock": 0,
} }
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api) mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.get_state.call_count == 1 assert mock_api.get_state.call_count == 1
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 5 assert len(sensors) == 5
@ -353,7 +363,11 @@ async def test_scb1e_sensor_setup(hass: HomeAssistant) -> None:
} }
async def test_scb1e_sensor_update(hass: HomeAssistant) -> None: async def test_scb1e_sensor_update(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful SCB1E sensor update.""" """Test a successful SCB1E sensor update."""
device = get_device("Dining room") device = get_device("Dining room")
mock_api = device.get_mock_api() mock_api = device.get_mock_api()
@ -369,9 +383,6 @@ async def test_scb1e_sensor_update(hass: HomeAssistant) -> None:
"childlock": 0, "childlock": 0,
} }
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
target_time = ( target_time = (
dt.utcnow() + BroadlinkSP4UpdateManager.SCAN_INTERVAL * 3 + timedelta(seconds=1) dt.utcnow() + BroadlinkSP4UpdateManager.SCAN_INTERVAL * 3 + timedelta(seconds=1)
) )
@ -381,7 +392,7 @@ async def test_scb1e_sensor_update(hass: HomeAssistant) -> None:
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == Platform.SENSOR] sensors = [entry for entry in entries if entry.domain == Platform.SENSOR]
assert len(sensors) == 5 assert len(sensors) == 5

View file

@ -7,24 +7,24 @@ from homeassistant.components.switch import (
) )
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON, Platform from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import async_entries_for_device from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import get_device from . import get_device
from tests.common import mock_device_registry, mock_registry
async def test_switch_setup_works(
async def test_switch_setup_works(hass: HomeAssistant) -> None: hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful setup with a switch.""" """Test a successful setup with a switch."""
device = get_device("Dining room") device = get_device("Dining room")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
switches = [entry for entry in entries if entry.domain == Platform.SWITCH] switches = [entry for entry in entries if entry.domain == Platform.SWITCH]
assert len(switches) == 1 assert len(switches) == 1
@ -36,17 +36,19 @@ async def test_switch_setup_works(hass: HomeAssistant) -> None:
assert mock_setup.api.auth.call_count == 1 assert mock_setup.api.auth.call_count == 1
async def test_switch_turn_off_turn_on(hass: HomeAssistant) -> None: async def test_switch_turn_off_turn_on(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test send turn on and off for a switch.""" """Test send turn on and off for a switch."""
device = get_device("Dining room") device = get_device("Dining room")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
switches = [entry for entry in entries if entry.domain == Platform.SWITCH] switches = [entry for entry in entries if entry.domain == Platform.SWITCH]
assert len(switches) == 1 assert len(switches) == 1
@ -70,17 +72,19 @@ async def test_switch_turn_off_turn_on(hass: HomeAssistant) -> None:
assert mock_setup.api.auth.call_count == 1 assert mock_setup.api.auth.call_count == 1
async def test_slots_switch_setup_works(hass: HomeAssistant) -> None: async def test_slots_switch_setup_works(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test a successful setup with a switch with slots.""" """Test a successful setup with a switch with slots."""
device = get_device("Gaming room") device = get_device("Gaming room")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
switches = [entry for entry in entries if entry.domain == Platform.SWITCH] switches = [entry for entry in entries if entry.domain == Platform.SWITCH]
assert len(switches) == 4 assert len(switches) == 4
@ -93,17 +97,19 @@ async def test_slots_switch_setup_works(hass: HomeAssistant) -> None:
assert mock_setup.api.auth.call_count == 1 assert mock_setup.api.auth.call_count == 1
async def test_slots_switch_turn_off_turn_on(hass: HomeAssistant) -> None: async def test_slots_switch_turn_off_turn_on(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test send turn on and off for a switch with slots.""" """Test send turn on and off for a switch with slots."""
device = get_device("Gaming room") device = get_device("Gaming room")
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass) mock_setup = await device.setup_entry(hass)
device_entry = device_registry.async_get_device( device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)} {(DOMAIN, mock_setup.entry.unique_id)}
) )
entries = async_entries_for_device(entity_registry, device_entry.id) entries = er.async_entries_for_device(entity_registry, device_entry.id)
switches = [entry for entry in entries if entry.domain == Platform.SWITCH] switches = [entry for entry in entries if entry.domain == Platform.SWITCH]
assert len(switches) == 4 assert len(switches) == 4

View file

@ -21,13 +21,10 @@ from homeassistant.setup import async_setup_component
from . import mock_device, mock_location, mock_mode from . import mock_device, mock_location, mock_mode
from tests.common import mock_registry
async def test_alarm_control_panel(hass, canary, entity_registry) -> None:
async def test_alarm_control_panel(hass, canary) -> None:
"""Test the creation and values of the alarm_control_panel for Canary.""" """Test the creation and values of the alarm_control_panel for Canary."""
registry = mock_registry(hass)
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")
mocked_location = mock_location( mocked_location = mock_location(
@ -48,7 +45,7 @@ async def test_alarm_control_panel(hass, canary) -> None:
await hass.async_block_till_done() await hass.async_block_till_done()
entity_id = "alarm_control_panel.home" entity_id = "alarm_control_panel.home"
entity_entry = registry.async_get(entity_id) entity_entry = entity_registry.async_get(entity_id)
assert entity_entry assert entity_entry
assert entity_entry.unique_id == "100" assert entity_entry.unique_id == "100"

View file

@ -22,15 +22,11 @@ from homeassistant.util.dt import utcnow
from . import mock_device, mock_location, mock_reading from . import mock_device, mock_location, mock_reading
from tests.common import async_fire_time_changed, mock_device_registry, mock_registry from tests.common import async_fire_time_changed
async def test_sensors_pro(hass, canary) -> None: async def test_sensors_pro(hass, canary, device_registry, entity_registry) -> None:
"""Test the creation and values of the sensors for Canary Pro.""" """Test the creation and values of the sensors for Canary Pro."""
registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")
instance = canary.return_value instance = canary.return_value
@ -74,7 +70,7 @@ async def test_sensors_pro(hass, canary) -> None:
} }
for sensor_id, data in sensors.items(): for sensor_id, data in sensors.items():
entity_entry = registry.async_get(f"sensor.{sensor_id}") entity_entry = entity_registry.async_get(f"sensor.{sensor_id}")
assert entity_entry assert entity_entry
assert entity_entry.original_device_class == data[3] assert entity_entry.original_device_class == data[3]
assert entity_entry.unique_id == data[0] assert entity_entry.unique_id == data[0]
@ -152,12 +148,8 @@ async def test_sensors_attributes_pro(hass, canary) -> None:
assert state3.attributes[ATTR_AIR_QUALITY] == STATE_AIR_QUALITY_NORMAL assert state3.attributes[ATTR_AIR_QUALITY] == STATE_AIR_QUALITY_NORMAL
async def test_sensors_flex(hass, canary) -> None: async def test_sensors_flex(hass, canary, device_registry, entity_registry) -> None:
"""Test the creation and values of the sensors for Canary Flex.""" """Test the creation and values of the sensors for Canary Flex."""
registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Flex") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Flex")
instance = canary.return_value instance = canary.return_value
@ -193,7 +185,7 @@ async def test_sensors_flex(hass, canary) -> None:
} }
for sensor_id, data in sensors.items(): for sensor_id, data in sensors.items():
entity_entry = registry.async_get(f"sensor.{sensor_id}") entity_entry = entity_registry.async_get(f"sensor.{sensor_id}")
assert entity_entry assert entity_entry
assert entity_entry.original_device_class == data[3] assert entity_entry.original_device_class == data[3]
assert entity_entry.unique_id == data[0] assert entity_entry.unique_id == data[0]

View file

@ -10,7 +10,7 @@ from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import EntityCategory
from tests.common import async_fire_time_changed, mock_registry from tests.common import async_fire_time_changed
@pytest.fixture @pytest.fixture
@ -19,10 +19,10 @@ def cloud_stub():
return Mock(is_logged_in=True, subscription_expired=False) return Mock(is_logged_in=True, subscription_expired=False)
async def test_alexa_config_expose_entity_prefs(hass, cloud_prefs, cloud_stub): async def test_alexa_config_expose_entity_prefs(
hass, cloud_prefs, cloud_stub, entity_registry
):
"""Test Alexa config should expose using prefs.""" """Test Alexa config should expose using prefs."""
entity_registry = mock_registry(hass)
entity_entry1 = entity_registry.async_get_or_create( entity_entry1 = entity_registry.async_get_or_create(
"light", "light",
"test", "test",

View file

@ -14,7 +14,7 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import EntityCategory
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from tests.common import async_fire_time_changed, mock_registry from tests.common import async_fire_time_changed
@pytest.fixture @pytest.fixture
@ -278,10 +278,10 @@ async def test_sync_google_on_home_assistant_start(hass, mock_cloud_login, cloud
assert len(mock_sync.mock_calls) == 1 assert len(mock_sync.mock_calls) == 1
async def test_google_config_expose_entity_prefs(hass, mock_conf, cloud_prefs): async def test_google_config_expose_entity_prefs(
hass, mock_conf, cloud_prefs, entity_registry
):
"""Test Google config should expose using prefs.""" """Test Google config should expose using prefs."""
entity_registry = mock_registry(hass)
entity_entry1 = entity_registry.async_get_or_create( entity_entry1 = entity_registry.async_get_or_create(
"light", "light",
"test", "test",

View file

@ -4,7 +4,7 @@ from pytest_unordered import unordered
from homeassistant.components.config import area_registry from homeassistant.components.config import area_registry
from tests.common import ANY, mock_area_registry from tests.common import ANY
@pytest.fixture @pytest.fixture
@ -14,16 +14,10 @@ def client(hass, hass_ws_client):
return hass.loop.run_until_complete(hass_ws_client(hass)) return hass.loop.run_until_complete(hass_ws_client(hass))
@pytest.fixture async def test_list_areas(hass, client, area_registry):
def registry(hass):
"""Return an empty, loaded, registry."""
return mock_area_registry(hass)
async def test_list_areas(hass, client, registry):
"""Test list entries.""" """Test list entries."""
area1 = registry.async_create("mock 1") area1 = area_registry.async_create("mock 1")
area2 = registry.async_create( area2 = area_registry.async_create(
"mock 2", aliases={"alias_1", "alias_2"}, picture="/image/example.png" "mock 2", aliases={"alias_1", "alias_2"}, picture="/image/example.png"
) )
@ -46,7 +40,7 @@ async def test_list_areas(hass, client, registry):
] ]
async def test_create_area(hass, client, registry): async def test_create_area(hass, client, area_registry):
"""Test create entry.""" """Test create entry."""
# Create area with only mandatory parameters # Create area with only mandatory parameters
await client.send_json( await client.send_json(
@ -61,7 +55,7 @@ async def test_create_area(hass, client, registry):
"name": "mock", "name": "mock",
"picture": None, "picture": None,
} }
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
# Create area with all parameters # Create area with all parameters
await client.send_json( await client.send_json(
@ -82,12 +76,12 @@ async def test_create_area(hass, client, registry):
"name": "mock 2", "name": "mock 2",
"picture": "/image/example.png", "picture": "/image/example.png",
} }
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2
async def test_create_area_with_name_already_in_use(hass, client, registry): async def test_create_area_with_name_already_in_use(hass, client, area_registry):
"""Test create entry that should fail.""" """Test create entry that should fail."""
registry.async_create("mock") area_registry.async_create("mock")
await client.send_json( await client.send_json(
{"id": 1, "name": "mock", "type": "config/area_registry/create"} {"id": 1, "name": "mock", "type": "config/area_registry/create"}
@ -98,12 +92,12 @@ async def test_create_area_with_name_already_in_use(hass, client, registry):
assert not msg["success"] assert not msg["success"]
assert msg["error"]["code"] == "invalid_info" assert msg["error"]["code"] == "invalid_info"
assert msg["error"]["message"] == "The name mock (mock) is already in use" assert msg["error"]["message"] == "The name mock (mock) is already in use"
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_delete_area(hass, client, registry): async def test_delete_area(hass, client, area_registry):
"""Test delete entry.""" """Test delete entry."""
area = registry.async_create("mock") area = area_registry.async_create("mock")
await client.send_json( await client.send_json(
{"id": 1, "area_id": area.id, "type": "config/area_registry/delete"} {"id": 1, "area_id": area.id, "type": "config/area_registry/delete"}
@ -112,12 +106,12 @@ async def test_delete_area(hass, client, registry):
msg = await client.receive_json() msg = await client.receive_json()
assert msg["success"] assert msg["success"]
assert not registry.areas assert not area_registry.areas
async def test_delete_non_existing_area(hass, client, registry): async def test_delete_non_existing_area(hass, client, area_registry):
"""Test delete entry that should fail.""" """Test delete entry that should fail."""
registry.async_create("mock") area_registry.async_create("mock")
await client.send_json( await client.send_json(
{"id": 1, "area_id": "", "type": "config/area_registry/delete"} {"id": 1, "area_id": "", "type": "config/area_registry/delete"}
@ -128,12 +122,12 @@ async def test_delete_non_existing_area(hass, client, registry):
assert not msg["success"] assert not msg["success"]
assert msg["error"]["code"] == "invalid_info" assert msg["error"]["code"] == "invalid_info"
assert msg["error"]["message"] == "Area ID doesn't exist" assert msg["error"]["message"] == "Area ID doesn't exist"
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area(hass, client, registry): async def test_update_area(hass, client, area_registry):
"""Test update entry.""" """Test update entry."""
area = registry.async_create("mock 1") area = area_registry.async_create("mock 1")
await client.send_json( await client.send_json(
{ {
@ -154,7 +148,7 @@ async def test_update_area(hass, client, registry):
"name": "mock 2", "name": "mock 2",
"picture": "/image/example.png", "picture": "/image/example.png",
} }
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
await client.send_json( await client.send_json(
{ {
@ -174,12 +168,12 @@ async def test_update_area(hass, client, registry):
"name": "mock 2", "name": "mock 2",
"picture": None, "picture": None,
} }
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area_with_same_name(hass, client, registry): async def test_update_area_with_same_name(hass, client, area_registry):
"""Test update entry.""" """Test update entry."""
area = registry.async_create("mock 1") area = area_registry.async_create("mock 1")
await client.send_json( await client.send_json(
{ {
@ -194,13 +188,13 @@ async def test_update_area_with_same_name(hass, client, registry):
assert msg["result"]["area_id"] == area.id assert msg["result"]["area_id"] == area.id
assert msg["result"]["name"] == "mock 1" assert msg["result"]["name"] == "mock 1"
assert len(registry.areas) == 1 assert len(area_registry.areas) == 1
async def test_update_area_with_name_already_in_use(hass, client, registry): async def test_update_area_with_name_already_in_use(hass, client, area_registry):
"""Test update entry.""" """Test update entry."""
area = registry.async_create("mock 1") area = area_registry.async_create("mock 1")
registry.async_create("mock 2") area_registry.async_create("mock 2")
await client.send_json( await client.send_json(
{ {
@ -216,4 +210,4 @@ async def test_update_area_with_name_already_in_use(hass, client, registry):
assert not msg["success"] assert not msg["success"]
assert msg["error"]["code"] == "invalid_info" assert msg["error"]["code"] == "invalid_info"
assert msg["error"]["message"] == "The name mock 2 (mock2) is already in use" assert msg["error"]["message"] == "The name mock 2 (mock2) is already in use"
assert len(registry.areas) == 2 assert len(area_registry.areas) == 2

View file

@ -3,15 +3,10 @@ import pytest
from homeassistant.components.config import device_registry from homeassistant.components.config import device_registry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as helpers_dr from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import ( from tests.common import MockConfigEntry, MockModule, mock_integration
MockConfigEntry,
MockModule,
mock_device_registry,
mock_integration,
)
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
from tests.typing import WebSocketGenerator from tests.typing import WebSocketGenerator
@ -23,28 +18,22 @@ def client(hass, hass_ws_client):
return hass.loop.run_until_complete(hass_ws_client(hass)) return hass.loop.run_until_complete(hass_ws_client(hass))
@pytest.fixture async def test_list_devices(hass, client, device_registry):
def registry(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
async def test_list_devices(hass, client, registry):
"""Test list entries.""" """Test list entries."""
device1 = registry.async_get_or_create( device1 = device_registry.async_get_or_create(
config_entry_id="1234", config_entry_id="1234",
connections={("ethernet", "12:34:56:78:90:AB:CD:EF")}, connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
identifiers={("bridgeid", "0123")}, identifiers={("bridgeid", "0123")},
manufacturer="manufacturer", manufacturer="manufacturer",
model="model", model="model",
) )
device2 = registry.async_get_or_create( device2 = device_registry.async_get_or_create(
config_entry_id="1234", config_entry_id="1234",
identifiers={("bridgeid", "1234")}, identifiers={("bridgeid", "1234")},
manufacturer="manufacturer", manufacturer="manufacturer",
model="model", model="model",
via_device=("bridgeid", "0123"), via_device=("bridgeid", "0123"),
entry_type=helpers_dr.DeviceEntryType.SERVICE, entry_type=dr.DeviceEntryType.SERVICE,
) )
await client.send_json({"id": 5, "type": "config/device_registry/list"}) await client.send_json({"id": 5, "type": "config/device_registry/list"})
@ -75,7 +64,7 @@ async def test_list_devices(hass, client, registry):
"configuration_url": None, "configuration_url": None,
"connections": [], "connections": [],
"disabled_by": None, "disabled_by": None,
"entry_type": helpers_dr.DeviceEntryType.SERVICE, "entry_type": dr.DeviceEntryType.SERVICE,
"hw_version": None, "hw_version": None,
"identifiers": [["bridgeid", "1234"]], "identifiers": [["bridgeid", "1234"]],
"manufacturer": "manufacturer", "manufacturer": "manufacturer",
@ -90,7 +79,7 @@ async def test_list_devices(hass, client, registry):
class Unserializable: class Unserializable:
"""Good luck serializing me.""" """Good luck serializing me."""
registry.async_update_device(device2.id, name=Unserializable()) device_registry.async_update_device(device2.id, name=Unserializable())
await hass.async_block_till_done() await hass.async_block_till_done()
await client.send_json({"id": 6, "type": "config/device_registry/list"}) await client.send_json({"id": 6, "type": "config/device_registry/list"})
@ -117,7 +106,7 @@ async def test_list_devices(hass, client, registry):
] ]
# Remove the bad device to avoid errors when test is being torn down # Remove the bad device to avoid errors when test is being torn down
registry.async_remove_device(device2.id) device_registry.async_remove_device(device2.id)
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -125,16 +114,16 @@ async def test_list_devices(hass, client, registry):
[ [
["area_id", "12345A"], ["area_id", "12345A"],
["area_id", None], ["area_id", None],
["disabled_by", helpers_dr.DeviceEntryDisabler.USER], ["disabled_by", dr.DeviceEntryDisabler.USER],
["disabled_by", "user"], ["disabled_by", "user"],
["disabled_by", None], ["disabled_by", None],
["name_by_user", "Test Friendly Name"], ["name_by_user", "Test Friendly Name"],
["name_by_user", None], ["name_by_user", None],
], ],
) )
async def test_update_device(hass, client, registry, payload_key, payload_value): async def test_update_device(hass, client, device_registry, payload_key, payload_value):
"""Test update entry.""" """Test update entry."""
device = registry.async_get_or_create( device = device_registry.async_get_or_create(
config_entry_id="1234", config_entry_id="1234",
connections={("ethernet", "12:34:56:78:90:AB:CD:EF")}, connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
identifiers={("bridgeid", "0123")}, identifiers={("bridgeid", "0123")},
@ -155,9 +144,9 @@ async def test_update_device(hass, client, registry, payload_key, payload_value)
msg = await client.receive_json() msg = await client.receive_json()
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(registry.devices) == 1 assert len(device_registry.devices) == 1
device = registry.async_get_device( device = device_registry.async_get_device(
identifiers={("bridgeid", "0123")}, identifiers={("bridgeid", "0123")},
connections={("ethernet", "12:34:56:78:90:AB:CD:EF")}, connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
) )
@ -165,16 +154,17 @@ async def test_update_device(hass, client, registry, payload_key, payload_value)
assert msg["result"][payload_key] == payload_value assert msg["result"][payload_key] == payload_value
assert getattr(device, payload_key) == payload_value assert getattr(device, payload_key) == payload_value
assert isinstance(device.disabled_by, (helpers_dr.DeviceEntryDisabler, type(None))) assert isinstance(device.disabled_by, (dr.DeviceEntryDisabler, type(None)))
async def test_remove_config_entry_from_device( async def test_remove_config_entry_from_device(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
device_registry: dr.DeviceRegistry,
) -> None: ) -> None:
"""Test removing config entry from device.""" """Test removing config entry from device."""
assert await async_setup_component(hass, "config", {}) assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass) ws_client = await hass_ws_client(hass)
device_registry = mock_device_registry(hass)
can_remove = False can_remove = False
@ -212,11 +202,11 @@ async def test_remove_config_entry_from_device(
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=entry_1.entry_id, config_entry_id=entry_1.entry_id,
connections={(helpers_dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
device_entry = device_registry.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=entry_2.entry_id, config_entry_id=entry_2.entry_id,
connections={(helpers_dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
assert device_entry.config_entries == {entry_1.entry_id, entry_2.entry_id} assert device_entry.config_entries == {entry_1.entry_id, entry_2.entry_id}
@ -276,12 +266,13 @@ async def test_remove_config_entry_from_device(
async def test_remove_config_entry_from_device_fails( async def test_remove_config_entry_from_device_fails(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
device_registry: dr.DeviceRegistry,
) -> None: ) -> None:
"""Test removing config entry from device failing cases.""" """Test removing config entry from device failing cases."""
assert await async_setup_component(hass, "config", {}) assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass) ws_client = await hass_ws_client(hass)
device_registry = mock_device_registry(hass)
async def async_remove_config_entry_device(hass, config_entry, device_entry): async def async_remove_config_entry_device(hass, config_entry, device_entry):
return True return True
@ -322,15 +313,15 @@ async def test_remove_config_entry_from_device_fails(
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=entry_1.entry_id, config_entry_id=entry_1.entry_id,
connections={(helpers_dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=entry_2.entry_id, config_entry_id=entry_2.entry_id,
connections={(helpers_dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
device_entry = device_registry.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=entry_3.entry_id, config_entry_id=entry_3.entry_id,
connections={(helpers_dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
assert device_entry.config_entries == { assert device_entry.config_entries == {
entry_1.entry_id, entry_1.entry_id,

View file

@ -4,12 +4,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from tests.common import ( from tests.common import MockConfigEntry, MockEntityPlatform, MockPlatform
MockConfigEntry,
MockEntityPlatform,
MockPlatform,
mock_registry,
)
def test_tracker_entity() -> None: def test_tracker_entity() -> None:
@ -170,10 +165,10 @@ async def test_register_mac_ignored(hass: HomeAssistant) -> None:
assert entity_entry_1.disabled_by == er.RegistryEntryDisabler.INTEGRATION assert entity_entry_1.disabled_by == er.RegistryEntryDisabler.INTEGRATION
async def test_connected_device_registered(hass: HomeAssistant) -> None: async def test_connected_device_registered(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test dispatch on connected device being registered.""" """Test dispatch on connected device being registered."""
registry = mock_registry(hass)
dispatches = [] dispatches = []
@callback @callback
@ -243,9 +238,9 @@ async def test_connected_device_registered(hass: HomeAssistant) -> None:
full_name = f"{entity_platform.domain}.{config_entry.domain}" full_name = f"{entity_platform.domain}.{config_entry.domain}"
assert full_name in hass.config.components assert full_name in hass.config.components
assert len(hass.states.async_entity_ids()) == 0 # should be disabled assert len(hass.states.async_entity_ids()) == 0 # should be disabled
assert len(registry.entities) == 2 assert len(entity_registry.entities) == 2
assert ( assert (
registry.entities["test_domain.test_aa_bb_cc_dd_ee_ff"].config_entry_id entity_registry.entities["test_domain.test_aa_bb_cc_dd_ee_ff"].config_entry_id
== "super-mock-id" == "super-mock-id"
) )
unsub() unsub()

View file

@ -25,9 +25,8 @@ def mock_path():
@pytest.fixture @pytest.fixture
def mock_device_registry_devices(hass): def mock_device_registry_devices(device_registry):
"""Create device registry devices so the device tracker entities are enabled.""" """Create device registry devices so the device tracker entities are enabled."""
dev_reg = dr.async_get(hass)
config_entry = MockConfigEntry(domain="something_else") config_entry = MockConfigEntry(domain="something_else")
for idx, device in enumerate( for idx, device in enumerate(
@ -39,7 +38,7 @@ def mock_device_registry_devices(hass):
"5E:65:55:00:00:00", "5E:65:55:00:00:00",
) )
): ):
dev_reg.async_get_or_create( device_registry.async_get_or_create(
name=f"Device {idx}", name=f"Device {idx}",
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, device)}, connections={(dr.CONNECTION_NETWORK_MAC, device)},

View file

@ -7,11 +7,11 @@ from homeassistant.components.gios.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import STATIONS, init_integration from . import STATIONS, init_integration
from tests.common import MockConfigEntry, load_fixture, mock_device_registry from tests.common import MockConfigEntry, load_fixture
async def test_async_setup_entry(hass: HomeAssistant) -> None: async def test_async_setup_entry(hass: HomeAssistant) -> None:
@ -56,7 +56,9 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
assert not hass.data.get(DOMAIN) assert not hass.data.get(DOMAIN)
async def test_migrate_device_and_config_entry(hass: HomeAssistant) -> None: async def test_migrate_device_and_config_entry(
hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test device_info identifiers and config entry migration.""" """Test device_info identifiers and config entry migration."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -85,15 +87,14 @@ async def test_migrate_device_and_config_entry(hass: HomeAssistant) -> None:
): ):
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_reg = mock_device_registry(hass) device_entry = device_registry.async_get_or_create(
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, 123)} config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, 123)}
) )
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
migrated_device_entry = device_reg.async_get_or_create( migrated_device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, "123")} config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, "123")}
) )
assert device_entry.id == migrated_device_entry.id assert device_entry.id == migrated_device_entry.id

View file

@ -41,6 +41,7 @@ from homeassistant.const import (
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from . import ( from . import (
@ -48,7 +49,7 @@ from . import (
_mocked_ismartgate_closed_door_response, _mocked_ismartgate_closed_door_response,
) )
from tests.common import MockConfigEntry, async_fire_time_changed, mock_device_registry from tests.common import MockConfigEntry, async_fire_time_changed
@patch("homeassistant.components.gogogate2.common.GogoGate2Api") @patch("homeassistant.components.gogogate2.common.GogoGate2Api")
@ -306,9 +307,10 @@ async def test_availability(ismartgateapi_mock, hass: HomeAssistant) -> None:
@patch("homeassistant.components.gogogate2.common.ISmartGateApi") @patch("homeassistant.components.gogogate2.common.ISmartGateApi")
async def test_device_info_ismartgate(ismartgateapi_mock, hass: HomeAssistant) -> None: async def test_device_info_ismartgate(
ismartgateapi_mock, hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test device info.""" """Test device info."""
device_registry = mock_device_registry(hass)
closed_door_response = _mocked_ismartgate_closed_door_response() closed_door_response = _mocked_ismartgate_closed_door_response()
@ -341,10 +343,10 @@ async def test_device_info_ismartgate(ismartgateapi_mock, hass: HomeAssistant) -
@patch("homeassistant.components.gogogate2.common.GogoGate2Api") @patch("homeassistant.components.gogogate2.common.GogoGate2Api")
async def test_device_info_gogogate2(gogogate2api_mock, hass: HomeAssistant) -> None: async def test_device_info_gogogate2(
gogogate2api_mock, hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test device info.""" """Test device info."""
device_registry = mock_device_registry(hass)
closed_door_response = _mocked_gogogate_open_door_response() closed_door_response = _mocked_gogogate_open_door_response()
api = MagicMock(GogoGate2Api) api = MagicMock(GogoGate2Api)

View file

@ -24,8 +24,6 @@ from homeassistant.helpers.entity import EntityCategory
from . import DEMO_DEVICES from . import DEMO_DEVICES
from tests.common import mock_registry
API_PASSWORD = "test1234" API_PASSWORD = "test1234"
PROJECT_ID = "hasstest-1234" PROJECT_ID = "hasstest-1234"
@ -125,11 +123,10 @@ def hass_fixture(event_loop, hass):
return hass return hass
async def test_sync_request(hass_fixture, assistant_client, auth_header): async def test_sync_request(
hass_fixture, assistant_client, auth_header, entity_registry
):
"""Test a sync request.""" """Test a sync request."""
entity_registry = mock_registry(hass_fixture)
entity_entry1 = entity_registry.async_get_or_create( entity_entry1 = entity_registry.async_get_or_create(
"switch", "switch",
"test", "test",

View file

@ -17,10 +17,10 @@ from homeassistant.components.homekit_controller import config_flow
from homeassistant.components.homekit_controller.const import KNOWN_DEVICES from homeassistant.components.homekit_controller.const import KNOWN_DEVICES
from homeassistant.components.homekit_controller.storage import async_get_entity_storage from homeassistant.components.homekit_controller.storage import async_get_entity_storage
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import device_registry from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
from tests.common import MockConfigEntry, mock_device_registry from tests.common import MockConfigEntry
PAIRING_START_FORM_ERRORS = [ PAIRING_START_FORM_ERRORS = [
(KeyError, "pairing_failed"), (KeyError, "pairing_failed"),
@ -351,19 +351,18 @@ async def test_discovery_ignored_model(hass, controller):
assert result["reason"] == "ignored_model" assert result["reason"] == "ignored_model"
async def test_discovery_ignored_hk_bridge(hass, controller): async def test_discovery_ignored_hk_bridge(hass, controller, device_registry):
"""Ensure we ignore homekit bridges and accessories created by the homekit integration.""" """Ensure we ignore homekit bridges and accessories created by the homekit integration."""
device = setup_mock_accessory(controller) device = setup_mock_accessory(controller)
discovery_info = get_device_discovery_info(device) discovery_info = get_device_discovery_info(device)
config_entry = MockConfigEntry(domain=config_flow.HOMEKIT_BRIDGE_DOMAIN, data={}) config_entry = MockConfigEntry(domain=config_flow.HOMEKIT_BRIDGE_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
formatted_mac = device_registry.format_mac("AA:BB:CC:DD:EE:FF") formatted_mac = dr.format_mac("AA:BB:CC:DD:EE:FF")
dev_reg = mock_device_registry(hass) device_registry.async_get_or_create(
dev_reg.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, formatted_mac)}, connections={(dr.CONNECTION_NETWORK_MAC, formatted_mac)},
) )
discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID] = "AA:BB:CC:DD:EE:FF" discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID] = "AA:BB:CC:DD:EE:FF"
@ -378,19 +377,18 @@ async def test_discovery_ignored_hk_bridge(hass, controller):
assert result["reason"] == "ignored_model" assert result["reason"] == "ignored_model"
async def test_discovery_does_not_ignore_non_homekit(hass, controller): async def test_discovery_does_not_ignore_non_homekit(hass, controller, device_registry):
"""Do not ignore devices that are not from the homekit integration.""" """Do not ignore devices that are not from the homekit integration."""
device = setup_mock_accessory(controller) device = setup_mock_accessory(controller)
discovery_info = get_device_discovery_info(device) discovery_info = get_device_discovery_info(device)
config_entry = MockConfigEntry(domain="not_homekit", data={}) config_entry = MockConfigEntry(domain="not_homekit", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
formatted_mac = device_registry.format_mac("AA:BB:CC:DD:EE:FF") formatted_mac = dr.format_mac("AA:BB:CC:DD:EE:FF")
dev_reg = mock_device_registry(hass) device_registry.async_get_or_create(
dev_reg.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, formatted_mac)}, connections={(dr.CONNECTION_NETWORK_MAC, formatted_mac)},
) )
discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID] = "AA:BB:CC:DD:EE:FF" discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID] = "AA:BB:CC:DD:EE:FF"

View file

@ -13,24 +13,10 @@ from tests.common import (
MockConfigEntry, MockConfigEntry,
async_get_device_automations, async_get_device_automations,
async_mock_service, async_mock_service,
mock_device_registry,
mock_registry,
) )
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture @pytest.fixture
def calls(hass): def calls(hass):
"""Track calls to a mock service.""" """Track calls to a mock service."""
@ -44,15 +30,17 @@ async def kodi_media_player(hass):
return f"{MP_DOMAIN}.name" return f"{MP_DOMAIN}.name"
async def test_get_triggers(hass, device_reg, entity_reg): async def test_get_triggers(hass, device_registry, entity_registry):
"""Test we get the expected triggers from a kodi.""" """Test we get the expected triggers from a kodi."""
config_entry = MockConfigEntry(domain=DOMAIN, data={}) config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, "host", 1234)}, identifiers={(DOMAIN, "host", 1234)},
) )
entity_reg.async_get_or_create(MP_DOMAIN, DOMAIN, "5678", device_id=device_entry.id) entity_registry.async_get_or_create(
MP_DOMAIN, DOMAIN, "5678", device_id=device_entry.id
)
expected_triggers = [ expected_triggers = [
{ {
"platform": "device", "platform": "device",

View file

@ -8,7 +8,6 @@ from homeassistant.components.local_file.const import DOMAIN, SERVICE_UPDATE_FIL
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_registry
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
@ -16,8 +15,6 @@ async def test_loading_file(
hass: HomeAssistant, hass_client: ClientSessionGenerator hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None: ) -> None:
"""Test that it loads image from disk.""" """Test that it loads image from disk."""
mock_registry(hass)
with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch( with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
"os.access", mock.Mock(return_value=True) "os.access", mock.Mock(return_value=True)
), mock.patch( ), mock.patch(
@ -54,8 +51,6 @@ async def test_file_not_readable(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""Test a warning is shown setup when file is not readable.""" """Test a warning is shown setup when file is not readable."""
mock_registry(hass)
with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch( with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
"os.access", mock.Mock(return_value=False) "os.access", mock.Mock(return_value=False)
): ):
@ -146,9 +141,6 @@ async def test_camera_content_type(
async def test_update_file_path(hass: HomeAssistant) -> None: async def test_update_file_path(hass: HomeAssistant) -> None:
"""Test update_file_path service.""" """Test update_file_path service."""
# Setup platform # Setup platform
mock_registry(hass)
with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch( with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
"os.access", mock.Mock(return_value=True) "os.access", mock.Mock(return_value=True)
), mock.patch( ), mock.patch(

View file

@ -31,7 +31,7 @@ from homeassistant.const import (
CONF_PLATFORM, CONF_PLATFORM,
CONF_TYPE, CONF_TYPE,
) )
from homeassistant.helpers import device_registry from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import MockBridge from . import MockBridge
@ -41,7 +41,6 @@ from tests.common import (
assert_lists_same, assert_lists_same,
async_get_device_automations, async_get_device_automations,
async_mock_service, async_mock_service,
mock_device_registry,
) )
MOCK_BUTTON_DEVICES = [ MOCK_BUTTON_DEVICES = [
@ -107,12 +106,6 @@ def calls(hass):
return async_mock_service(hass, "test", "automation") return async_mock_service(hass, "test", "automation")
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
async def _async_setup_lutron_with_picos(hass): async def _async_setup_lutron_with_picos(hass):
"""Setups a lutron bridge with picos.""" """Setups a lutron bridge with picos."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
@ -137,7 +130,7 @@ async def _async_setup_lutron_with_picos(hass):
return config_entry.entry_id return config_entry.entry_id
async def test_get_triggers(hass, device_reg): async def test_get_triggers(hass):
"""Test we get the expected triggers from a lutron pico.""" """Test we get the expected triggers from a lutron pico."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
data: LutronCasetaData = hass.data[DOMAIN][config_entry_id] data: LutronCasetaData = hass.data[DOMAIN][config_entry_id]
@ -174,13 +167,13 @@ async def test_get_triggers(hass, device_reg):
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_get_triggers_for_invalid_device_id(hass, device_reg): async def test_get_triggers_for_invalid_device_id(hass, device_registry):
"""Test error raised for invalid lutron device_id.""" """Test error raised for invalid lutron device_id."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
invalid_device = device_reg.async_get_or_create( invalid_device = device_registry.async_get_or_create(
config_entry_id=config_entry_id, config_entry_id=config_entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
) )
triggers = await async_get_device_automations( triggers = await async_get_device_automations(
@ -190,11 +183,11 @@ async def test_get_triggers_for_invalid_device_id(hass, device_reg):
assert triggers == [] assert triggers == []
async def test_get_triggers_for_non_button_device(hass, device_reg): async def test_get_triggers_for_non_button_device(hass, device_registry):
"""Test error raised for invalid lutron device_id.""" """Test error raised for invalid lutron device_id."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
invalid_device = device_reg.async_get_or_create( invalid_device = device_registry.async_get_or_create(
config_entry_id=config_entry_id, config_entry_id=config_entry_id,
identifiers={(DOMAIN, "invdevserial")}, identifiers={(DOMAIN, "invdevserial")},
) )
@ -206,11 +199,11 @@ async def test_get_triggers_for_non_button_device(hass, device_reg):
assert triggers == [] assert triggers == []
async def test_none_serial_keypad(hass, device_reg): async def test_none_serial_keypad(hass, device_registry):
"""Test serial assignment for keypads without serials.""" """Test serial assignment for keypads without serials."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
keypad_device = device_reg.async_get_or_create( keypad_device = device_registry.async_get_or_create(
config_entry_id=config_entry_id, config_entry_id=config_entry_id,
identifiers={(DOMAIN, "1234_786")}, identifiers={(DOMAIN, "1234_786")},
) )
@ -218,13 +211,14 @@ async def test_none_serial_keypad(hass, device_reg):
assert keypad_device is not None assert keypad_device is not None
async def test_if_fires_on_button_event(hass, calls, device_reg): async def test_if_fires_on_button_event(hass, calls, device_registry):
"""Test for press trigger firing.""" """Test for press trigger firing."""
await _async_setup_lutron_with_picos(hass) await _async_setup_lutron_with_picos(hass)
device = MOCK_BUTTON_DEVICES[0] device = MOCK_BUTTON_DEVICES[0]
dr = device_registry.async_get(hass) dr_device = device_registry.async_get_device(
dr_device = dr.async_get_device(identifiers={(DOMAIN, device["serial"])}) identifiers={(DOMAIN, device["serial"])}
)
device_id = dr_device.id device_id = dr_device.id
assert await async_setup_component( assert await async_setup_component(
@ -266,12 +260,13 @@ async def test_if_fires_on_button_event(hass, calls, device_reg):
assert calls[0].data["some"] == "test_trigger_button_press" assert calls[0].data["some"] == "test_trigger_button_press"
async def test_if_fires_on_button_event_without_lip(hass, calls, device_reg): async def test_if_fires_on_button_event_without_lip(hass, calls, device_registry):
"""Test for press trigger firing on a device that does not support lip.""" """Test for press trigger firing on a device that does not support lip."""
await _async_setup_lutron_with_picos(hass) await _async_setup_lutron_with_picos(hass)
device = MOCK_BUTTON_DEVICES[1] device = MOCK_BUTTON_DEVICES[1]
dr = device_registry.async_get(hass) dr_device = device_registry.async_get_device(
dr_device = dr.async_get_device(identifiers={(DOMAIN, device["serial"])}) identifiers={(DOMAIN, device["serial"])}
)
device_id = dr_device.id device_id = dr_device.id
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -312,7 +307,7 @@ async def test_if_fires_on_button_event_without_lip(hass, calls, device_reg):
assert calls[0].data["some"] == "test_trigger_button_press" assert calls[0].data["some"] == "test_trigger_button_press"
async def test_validate_trigger_config_no_device(hass, calls, device_reg): async def test_validate_trigger_config_no_device(hass, calls):
"""Test for no press with no device.""" """Test for no press with no device."""
assert await async_setup_component( assert await async_setup_component(
@ -350,7 +345,7 @@ async def test_validate_trigger_config_no_device(hass, calls, device_reg):
assert len(calls) == 0 assert len(calls) == 0
async def test_validate_trigger_config_unknown_device(hass, calls, device_reg): async def test_validate_trigger_config_unknown_device(hass, calls):
"""Test for no press with an unknown device.""" """Test for no press with an unknown device."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
@ -396,7 +391,7 @@ async def test_validate_trigger_config_unknown_device(hass, calls, device_reg):
assert len(calls) == 0 assert len(calls) == 0
async def test_validate_trigger_invalid_triggers(hass, device_reg, caplog): async def test_validate_trigger_invalid_triggers(hass, caplog):
"""Test for click_event with invalid triggers.""" """Test for click_event with invalid triggers."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
data: LutronCasetaData = hass.data[DOMAIN][config_entry_id] data: LutronCasetaData = hass.data[DOMAIN][config_entry_id]
@ -430,15 +425,16 @@ async def test_validate_trigger_invalid_triggers(hass, device_reg, caplog):
assert "value must be one of ['press', 'release']" in caplog.text assert "value must be one of ['press', 'release']" in caplog.text
async def test_if_fires_on_button_event_late_setup(hass, calls): async def test_if_fires_on_button_event_late_setup(hass, calls, device_registry):
"""Test for press trigger firing with integration getting setup late.""" """Test for press trigger firing with integration getting setup late."""
config_entry_id = await _async_setup_lutron_with_picos(hass) config_entry_id = await _async_setup_lutron_with_picos(hass)
await hass.config_entries.async_unload(config_entry_id) await hass.config_entries.async_unload(config_entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
device = MOCK_BUTTON_DEVICES[0] device = MOCK_BUTTON_DEVICES[0]
dr = device_registry.async_get(hass) dr_device = device_registry.async_get_device(
dr_device = dr.async_get_device(identifiers={(DOMAIN, device["serial"])}) identifiers={(DOMAIN, device["serial"])}
)
device_id = dr_device.id device_id = dr_device.id
assert await async_setup_component( assert await async_setup_component(

View file

@ -9,7 +9,7 @@ from homeassistant.components import mqtt
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import async_fire_mqtt_message, mock_device_registry from tests.common import async_fire_mqtt_message
from tests.components.diagnostics import ( from tests.components.diagnostics import (
get_diagnostics_for_config_entry, get_diagnostics_for_config_entry,
get_diagnostics_for_device, get_diagnostics_for_device,
@ -47,15 +47,9 @@ def device_tracker_sensor_only():
yield yield
@pytest.fixture
def device_reg(hass: HomeAssistant):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
async def test_entry_diagnostics( async def test_entry_diagnostics(
hass: HomeAssistant, hass: HomeAssistant,
device_reg, device_registry,
hass_client, hass_client,
mqtt_mock_entry_no_yaml_config: MqttMockHAClientGenerator, mqtt_mock_entry_no_yaml_config: MqttMockHAClientGenerator,
) -> None: ) -> None:
@ -95,7 +89,7 @@ async def test_entry_diagnostics(
) )
await hass.async_block_till_done() await hass.async_block_till_done()
device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}) device_entry = device_registry.async_get_device({("mqtt", "0AFFD2")})
expected_debug_info = { expected_debug_info = {
"entities": [ "entities": [
@ -178,7 +172,7 @@ async def test_entry_diagnostics(
) )
async def test_redact_diagnostics( async def test_redact_diagnostics(
hass: HomeAssistant, hass: HomeAssistant,
device_reg, device_registry,
hass_client, hass_client,
mqtt_mock_entry_no_yaml_config: MqttMockHAClientGenerator, mqtt_mock_entry_no_yaml_config: MqttMockHAClientGenerator,
) -> None: ) -> None:
@ -210,7 +204,7 @@ async def test_redact_diagnostics(
async_fire_mqtt_message(hass, "attributes-topic", location_data) async_fire_mqtt_message(hass, "attributes-topic", location_data)
await hass.async_block_till_done() await hass.async_block_till_done()
device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}) device_entry = device_registry.async_get_device({("mqtt", "0AFFD2")})
expected_debug_info = { expected_debug_info = {
"entities": [ "entities": [

View file

@ -12,7 +12,7 @@ from homeassistant.components.netatmo.const import (
) )
from homeassistant.components.netatmo.device_trigger import SUBTYPES from homeassistant.components.netatmo.device_trigger import SUBTYPES
from homeassistant.const import ATTR_DEVICE_ID from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.helpers import device_registry from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import ( from tests.common import (
@ -21,23 +21,9 @@ from tests.common import (
async_capture_events, async_capture_events,
async_get_device_automations, async_get_device_automations,
async_mock_service, async_mock_service,
mock_device_registry,
mock_registry,
) )
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture @pytest.fixture
def calls(hass): def calls(hass):
"""Track calls to a mock service.""" """Track calls to a mock service."""
@ -54,17 +40,17 @@ def calls(hass):
], ],
) )
async def test_get_triggers( async def test_get_triggers(
hass, device_reg, entity_reg, platform, device_type, event_types hass, device_registry, entity_registry, platform, device_type, event_types
): ):
"""Test we get the expected triggers from a netatmo devices.""" """Test we get the expected triggers from a netatmo devices."""
config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
model=device_type, model=device_type,
) )
entity_reg.async_get_or_create( entity_registry.async_get_or_create(
platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id
) )
expected_triggers = [] expected_triggers = []
@ -119,20 +105,20 @@ async def test_get_triggers(
], ],
) )
async def test_if_fires_on_event( async def test_if_fires_on_event(
hass, calls, device_reg, entity_reg, platform, camera_type, event_type hass, calls, device_registry, entity_registry, platform, camera_type, event_type
): ):
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (device_registry.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)
config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={connection}, connections={connection},
identifiers={(NETATMO_DOMAIN, mac_address)}, identifiers={(NETATMO_DOMAIN, mac_address)},
model=camera_type, model=camera_type,
) )
entity_reg.async_get_or_create( entity_registry.async_get_or_create(
platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id
) )
events = async_capture_events(hass, "netatmo_event") events = async_capture_events(hass, "netatmo_event")
@ -163,7 +149,7 @@ async def test_if_fires_on_event(
}, },
) )
device = device_reg.async_get_device(set(), {connection}) device = device_registry.async_get_device(set(), {connection})
assert device is not None assert device is not None
# Fake that the entity is turning on. # Fake that the entity is turning on.
@ -194,20 +180,27 @@ async def test_if_fires_on_event(
], ],
) )
async def test_if_fires_on_event_with_subtype( async def test_if_fires_on_event_with_subtype(
hass, calls, device_reg, entity_reg, platform, camera_type, event_type, sub_type hass,
calls,
device_registry,
entity_registry,
platform,
camera_type,
event_type,
sub_type,
): ):
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (device_registry.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)
config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={connection}, connections={connection},
identifiers={(NETATMO_DOMAIN, mac_address)}, identifiers={(NETATMO_DOMAIN, mac_address)},
model=camera_type, model=camera_type,
) )
entity_reg.async_get_or_create( entity_registry.async_get_or_create(
platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id
) )
events = async_capture_events(hass, "netatmo_event") events = async_capture_events(hass, "netatmo_event")
@ -240,7 +233,7 @@ async def test_if_fires_on_event_with_subtype(
}, },
) )
device = device_reg.async_get_device(set(), {connection}) device = device_registry.async_get_device(set(), {connection})
assert device is not None assert device is not None
# Fake that the entity is turning on. # Fake that the entity is turning on.
@ -265,20 +258,20 @@ async def test_if_fires_on_event_with_subtype(
[("climate", "NAPlug", trigger) for trigger in CLIMATE_TRIGGERS], [("climate", "NAPlug", trigger) for trigger in CLIMATE_TRIGGERS],
) )
async def test_if_invalid_device( async def test_if_invalid_device(
hass, device_reg, entity_reg, platform, device_type, event_type hass, device_registry, entity_registry, platform, device_type, event_type
): ):
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (device_registry.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)
config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create( device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={connection}, connections={connection},
identifiers={(NETATMO_DOMAIN, mac_address)}, identifiers={(NETATMO_DOMAIN, mac_address)},
model=device_type, model=device_type,
) )
entity_reg.async_get_or_create( entity_registry.async_get_or_create(
platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id
) )

View file

@ -8,6 +8,7 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.config_validation import ensure_list from homeassistant.helpers.config_validation import ensure_list
from . import ( from . import (
@ -18,8 +19,6 @@ from . import (
) )
from .const import ATTR_DEVICE_INFO, ATTR_UNKNOWN_DEVICE, MOCK_OWPROXY_DEVICES from .const import ATTR_DEVICE_INFO, ATTR_UNKNOWN_DEVICE, MOCK_OWPROXY_DEVICES
from tests.common import mock_device_registry, mock_registry
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def override_platforms() -> Generator[None, None, None]: def override_platforms() -> Generator[None, None, None]:
@ -34,14 +33,13 @@ async def test_binary_sensors(
owproxy: MagicMock, owproxy: MagicMock,
device_id: str, device_id: str,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for 1-Wire binary sensor. """Test for 1-Wire binary sensor.
This test forces all entities to be enabled. This test forces all entities to be enabled.
""" """
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_device = MOCK_OWPROXY_DEVICES[device_id] mock_device = MOCK_OWPROXY_DEVICES[device_id]
expected_entities = mock_device.get(Platform.BINARY_SENSOR, []) expected_entities = mock_device.get(Platform.BINARY_SENSOR, [])
expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO)) expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO))

View file

@ -10,6 +10,7 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.config_validation import ensure_list from homeassistant.helpers.config_validation import ensure_list
from . import ( from . import (
@ -25,8 +26,6 @@ from .const import (
MOCK_OWPROXY_DEVICES, MOCK_OWPROXY_DEVICES,
) )
from tests.common import mock_device_registry, mock_registry
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def override_platforms() -> Generator[None, None, None]: def override_platforms() -> Generator[None, None, None]:
@ -41,14 +40,13 @@ async def test_sensors(
owproxy: MagicMock, owproxy: MagicMock,
device_id: str, device_id: str,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for 1-Wire device. """Test for 1-Wire device.
As they would be on a clean setup: all binary-sensors and switches disabled. As they would be on a clean setup: all binary-sensors and switches disabled.
""" """
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_device = MOCK_OWPROXY_DEVICES[device_id] mock_device = MOCK_OWPROXY_DEVICES[device_id]
expected_entities = mock_device.get(Platform.SENSOR, []) expected_entities = mock_device.get(Platform.SENSOR, [])
if "branches" in mock_device: if "branches" in mock_device:
@ -79,13 +77,16 @@ async def test_sensors(
@pytest.mark.parametrize("device_id", ["12.111111111111"]) @pytest.mark.parametrize("device_id", ["12.111111111111"])
async def test_tai8570_sensors( async def test_tai8570_sensors(
hass: HomeAssistant, config_entry: ConfigEntry, owproxy: MagicMock, device_id: str hass: HomeAssistant,
config_entry: ConfigEntry,
owproxy: MagicMock,
device_id: str,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""The DS2602 is often used without TAI8570. """The DS2602 is often used without TAI8570.
The sensors should be ignored. The sensors should be ignored.
""" """
entity_registry = mock_registry(hass)
mock_devices = deepcopy(MOCK_OWPROXY_DEVICES) mock_devices = deepcopy(MOCK_OWPROXY_DEVICES)
mock_device = mock_devices[device_id] mock_device = mock_devices[device_id]

View file

@ -16,6 +16,7 @@ from homeassistant.const import (
Platform, Platform,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.config_validation import ensure_list from homeassistant.helpers.config_validation import ensure_list
from . import ( from . import (
@ -26,8 +27,6 @@ from . import (
) )
from .const import ATTR_DEVICE_INFO, ATTR_UNKNOWN_DEVICE, MOCK_OWPROXY_DEVICES from .const import ATTR_DEVICE_INFO, ATTR_UNKNOWN_DEVICE, MOCK_OWPROXY_DEVICES
from tests.common import mock_device_registry, mock_registry
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def override_platforms() -> Generator[None, None, None]: def override_platforms() -> Generator[None, None, None]:
@ -42,14 +41,13 @@ async def test_switches(
owproxy: MagicMock, owproxy: MagicMock,
device_id: str, device_id: str,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for 1-Wire switch. """Test for 1-Wire switch.
This test forces all entities to be enabled. This test forces all entities to be enabled.
""" """
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_device = MOCK_OWPROXY_DEVICES[device_id] mock_device = MOCK_OWPROXY_DEVICES[device_id]
expected_entities = mock_device.get(Platform.SWITCH, []) expected_entities = mock_device.get(Platform.SWITCH, [])
expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO)) expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO))

View file

@ -9,7 +9,7 @@ from homeassistant.const import CONF_DEVICE, CONF_ID, CONF_NAME
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry, mock_device_registry from tests.common import MockConfigEntry
VERSION_OLD = "4.2.5" VERSION_OLD = "4.2.5"
VERSION_NEW = "4.2.8.1" VERSION_NEW = "4.2.8.1"
@ -46,12 +46,13 @@ async def test_device_registry_insert(hass: HomeAssistant) -> None:
assert gw_dev.sw_version == VERSION_OLD assert gw_dev.sw_version == VERSION_OLD
async def test_device_registry_update(hass: HomeAssistant) -> None: async def test_device_registry_update(
hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test that the device registry is updated correctly.""" """Test that the device registry is updated correctly."""
MOCK_CONFIG_ENTRY.add_to_hass(hass) MOCK_CONFIG_ENTRY.add_to_hass(hass)
dev_reg = mock_device_registry(hass) device_registry.async_get_or_create(
dev_reg.async_get_or_create(
config_entry_id=MOCK_CONFIG_ENTRY.entry_id, config_entry_id=MOCK_CONFIG_ENTRY.entry_id,
identifiers={(DOMAIN, MOCK_GATEWAY_ID)}, identifiers={(DOMAIN, MOCK_GATEWAY_ID)},
name="Mock Gateway", name="Mock Gateway",
@ -67,5 +68,5 @@ async def test_device_registry_update(hass: HomeAssistant) -> None:
await setup.async_setup_component(hass, DOMAIN, {}) await setup.async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done() await hass.async_block_till_done()
gw_dev = dev_reg.async_get_device(identifiers={(DOMAIN, MOCK_GATEWAY_ID)}) gw_dev = device_registry.async_get_device(identifiers={(DOMAIN, MOCK_GATEWAY_ID)})
assert gw_dev.sw_version == VERSION_NEW assert gw_dev.sw_version == VERSION_NEW

View file

@ -27,10 +27,11 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import location from homeassistant.util import location
from tests.common import MockConfigEntry, mock_registry from tests.common import MockConfigEntry
MOCK_HOST = "192.168.0.1" MOCK_HOST = "192.168.0.1"
MOCK_NAME = "test_ps4" MOCK_NAME = "test_ps4"
@ -133,22 +134,23 @@ async def test_creating_entry_sets_up_media_player(hass: HomeAssistant) -> None:
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_config_flow_entry_migrate(hass: HomeAssistant) -> None: async def test_config_flow_entry_migrate(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that config flow entry is migrated correctly.""" """Test that config flow entry is migrated correctly."""
# Start with the config entry at Version 1. # Start with the config entry at Version 1.
manager = hass.config_entries manager = hass.config_entries
mock_entry = MOCK_ENTRY_VERSION_1 mock_entry = MOCK_ENTRY_VERSION_1
mock_entry.add_to_manager(manager) mock_entry.add_to_manager(manager)
mock_e_registry = mock_registry(hass)
mock_entity_id = f"media_player.ps4_{MOCK_UNIQUE_ID}" mock_entity_id = f"media_player.ps4_{MOCK_UNIQUE_ID}"
mock_e_entry = mock_e_registry.async_get_or_create( mock_e_entry = entity_registry.async_get_or_create(
"media_player", "media_player",
"ps4", "ps4",
MOCK_UNIQUE_ID, MOCK_UNIQUE_ID,
config_entry=mock_entry, config_entry=mock_entry,
device_id=MOCK_DEVICE_ID, device_id=MOCK_DEVICE_ID,
) )
assert len(mock_e_registry.entities) == 1 assert len(entity_registry.entities) == 1
assert mock_e_entry.entity_id == mock_entity_id assert mock_e_entry.entity_id == mock_entity_id
assert mock_e_entry.unique_id == MOCK_UNIQUE_ID assert mock_e_entry.unique_id == MOCK_UNIQUE_ID
@ -157,14 +159,14 @@ async def test_config_flow_entry_migrate(hass: HomeAssistant) -> None:
return_value=MOCK_LOCATION, return_value=MOCK_LOCATION,
), patch( ), patch(
"homeassistant.helpers.entity_registry.async_get", "homeassistant.helpers.entity_registry.async_get",
return_value=mock_e_registry, return_value=entity_registry,
): ):
await ps4.async_migrate_entry(hass, mock_entry) await ps4.async_migrate_entry(hass, mock_entry)
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(mock_e_registry.entities) == 1 assert len(entity_registry.entities) == 1
for entity in mock_e_registry.entities.values(): for entity in entity_registry.entities.values():
mock_entity = entity mock_entity = entity
# Test that entity_id remains the same. # Test that entity_id remains the same.

View file

@ -36,9 +36,10 @@ from homeassistant.const import (
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, mock_device_registry, mock_registry from tests.common import MockConfigEntry
MOCK_CREDS = "123412341234abcd12341234abcd12341234abcd12341234abcd12341234abcd" MOCK_CREDS = "123412341234abcd12341234abcd12341234abcd12341234abcd12341234abcd"
MOCK_NAME = "ha_ps4_name" MOCK_NAME = "ha_ps4_name"
@ -288,9 +289,10 @@ async def test_media_attributes_are_loaded(hass, patch_load_json):
assert mock_attrs.get(ATTR_MEDIA_CONTENT_TYPE) == MOCK_TITLE_TYPE assert mock_attrs.get(ATTR_MEDIA_CONTENT_TYPE) == MOCK_TITLE_TYPE
async def test_device_info_is_set_from_status_correctly(hass, patch_get_status): async def test_device_info_is_set_from_status_correctly(
hass, patch_get_status, device_registry
):
"""Test that device info is set correctly from status update.""" """Test that device info is set correctly from status update."""
mock_d_registry = mock_device_registry(hass)
patch_get_status.return_value = MOCK_STATUS_STANDBY patch_get_status.return_value = MOCK_STATUS_STANDBY
mock_entity_id = await setup_mock_component(hass) mock_entity_id = await setup_mock_component(hass)
@ -303,8 +305,8 @@ async def test_device_info_is_set_from_status_correctly(hass, patch_get_status):
mock_state = hass.states.get(mock_entity_id).state mock_state = hass.states.get(mock_entity_id).state
mock_d_entries = mock_d_registry.devices mock_d_entries = device_registry.devices
mock_entry = mock_d_registry.async_get_device(identifiers={(DOMAIN, MOCK_HOST_ID)}) mock_entry = device_registry.async_get_device(identifiers={(DOMAIN, MOCK_HOST_ID)})
assert mock_state == STATE_STANDBY assert mock_state == STATE_STANDBY
assert len(mock_d_entries) == 1 assert len(mock_d_entries) == 1
@ -314,27 +316,29 @@ async def test_device_info_is_set_from_status_correctly(hass, patch_get_status):
assert mock_entry.identifiers == {(DOMAIN, MOCK_HOST_ID)} assert mock_entry.identifiers == {(DOMAIN, MOCK_HOST_ID)}
async def test_device_info_is_assummed(hass: HomeAssistant) -> None: async def test_device_info_is_assummed(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that device info is assumed if device is unavailable.""" """Test that device info is assumed if device is unavailable."""
# Create a device registry entry with device info. # Create a device registry entry with device info.
mock_d_registry = mock_device_registry(hass) device_registry.async_get_or_create(
mock_d_registry.async_get_or_create(
config_entry_id=MOCK_ENTRY_ID, config_entry_id=MOCK_ENTRY_ID,
name=MOCK_HOST_NAME, name=MOCK_HOST_NAME,
model=MOCK_DEVICE_MODEL, model=MOCK_DEVICE_MODEL,
identifiers={(DOMAIN, MOCK_HOST_ID)}, identifiers={(DOMAIN, MOCK_HOST_ID)},
sw_version=MOCK_HOST_VERSION, sw_version=MOCK_HOST_VERSION,
) )
mock_d_entries = mock_d_registry.devices mock_d_entries = device_registry.devices
assert len(mock_d_entries) == 1 assert len(mock_d_entries) == 1
# Create a entity_registry entry which is using identifiers from device. # Create a entity_registry entry which is using identifiers from device.
mock_unique_id = ps4.format_unique_id(MOCK_CREDS, MOCK_HOST_ID) mock_unique_id = ps4.format_unique_id(MOCK_CREDS, MOCK_HOST_ID)
mock_e_registry = mock_registry(hass) entity_registry.async_get_or_create(
mock_e_registry.async_get_or_create(
"media_player", DOMAIN, mock_unique_id, config_entry=MOCK_CONFIG "media_player", DOMAIN, mock_unique_id, config_entry=MOCK_CONFIG
) )
mock_entity_id = mock_e_registry.async_get_entity_id( mock_entity_id = entity_registry.async_get_entity_id(
"media_player", DOMAIN, mock_unique_id "media_player", DOMAIN, mock_unique_id
) )
@ -350,12 +354,13 @@ async def test_device_info_is_assummed(hass: HomeAssistant) -> None:
assert mock_entities[0] == mock_entity_id assert mock_entities[0] == mock_entity_id
async def test_device_info_assummed_works(hass: HomeAssistant) -> None: async def test_device_info_assummed_works(
hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Reverse test that device info assumption works.""" """Reverse test that device info assumption works."""
mock_d_registry = mock_device_registry(hass)
mock_entity_id = await setup_mock_component(hass) mock_entity_id = await setup_mock_component(hass)
mock_state = hass.states.get(mock_entity_id).state mock_state = hass.states.get(mock_entity_id).state
mock_d_entries = mock_d_registry.devices mock_d_entries = device_registry.devices
# Ensure that state is not set. # Ensure that state is not set.
assert mock_state == STATE_UNKNOWN assert mock_state == STATE_UNKNOWN

View file

@ -7,6 +7,7 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import ( from . import (
check_device_registry, check_device_registry,
@ -16,8 +17,6 @@ from . import (
) )
from .const import MOCK_VEHICLES from .const import MOCK_VEHICLES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
@ -30,12 +29,13 @@ def override_platforms() -> Generator[None, None, None]:
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
async def test_binary_sensors( async def test_binary_sensors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault binary sensors.""" """Test for Renault binary sensors."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -50,12 +50,13 @@ async def test_binary_sensors(
@pytest.mark.usefixtures("fixtures_with_no_data") @pytest.mark.usefixtures("fixtures_with_no_data")
async def test_binary_sensor_empty( async def test_binary_sensor_empty(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault binary sensors with empty data from Renault.""" """Test for Renault binary sensors with empty data from Renault."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -69,12 +70,13 @@ async def test_binary_sensor_empty(
@pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception") @pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception")
async def test_binary_sensor_errors( async def test_binary_sensor_errors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault binary sensors with temporary failure.""" """Test for Renault binary sensors with temporary failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -90,12 +92,13 @@ async def test_binary_sensor_errors(
@pytest.mark.usefixtures("fixtures_with_access_denied_exception") @pytest.mark.usefixtures("fixtures_with_access_denied_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_binary_sensor_access_denied( async def test_binary_sensor_access_denied(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault binary sensors with access denied failure.""" """Test for Renault binary sensors with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -108,12 +111,13 @@ async def test_binary_sensor_access_denied(
@pytest.mark.usefixtures("fixtures_with_not_supported_exception") @pytest.mark.usefixtures("fixtures_with_not_supported_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_binary_sensor_not_supported( async def test_binary_sensor_not_supported(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault binary sensors with not supported failure.""" """Test for Renault binary sensors with not supported failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -9,11 +9,12 @@ from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRE
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import check_device_registry, check_entities_no_data from . import check_device_registry, check_entities_no_data
from .const import ATTR_ENTITY_ID, MOCK_VEHICLES from .const import ATTR_ENTITY_ID, MOCK_VEHICLES
from tests.common import load_fixture, mock_device_registry, mock_registry from tests.common import load_fixture
pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
@ -27,13 +28,13 @@ def override_platforms() -> Generator[None, None, None]:
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
async def test_buttons( async def test_buttons(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers.""" """Test for Renault device trackers."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -48,13 +49,13 @@ async def test_buttons(
@pytest.mark.usefixtures("fixtures_with_no_data") @pytest.mark.usefixtures("fixtures_with_no_data")
async def test_button_empty( async def test_button_empty(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with empty data from Renault.""" """Test for Renault device trackers with empty data from Renault."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -68,13 +69,13 @@ async def test_button_empty(
@pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception") @pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception")
async def test_button_errors( async def test_button_errors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with temporary failure.""" """Test for Renault device trackers with temporary failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -90,13 +91,13 @@ async def test_button_errors(
@pytest.mark.usefixtures("fixtures_with_access_denied_exception") @pytest.mark.usefixtures("fixtures_with_access_denied_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_button_access_denied( async def test_button_access_denied(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with access denied failure.""" """Test for Renault device trackers with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -112,13 +113,13 @@ async def test_button_access_denied(
@pytest.mark.usefixtures("fixtures_with_not_supported_exception") @pytest.mark.usefixtures("fixtures_with_not_supported_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_button_not_supported( async def test_button_not_supported(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with not supported failure.""" """Test for Renault device trackers with not supported failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -7,6 +7,7 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import ( from . import (
check_device_registry, check_device_registry,
@ -16,8 +17,6 @@ from . import (
) )
from .const import MOCK_VEHICLES from .const import MOCK_VEHICLES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
@ -30,13 +29,13 @@ def override_platforms() -> Generator[None, None, None]:
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
async def test_device_trackers( async def test_device_trackers(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers.""" """Test for Renault device trackers."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -51,13 +50,13 @@ async def test_device_trackers(
@pytest.mark.usefixtures("fixtures_with_no_data") @pytest.mark.usefixtures("fixtures_with_no_data")
async def test_device_tracker_empty( async def test_device_tracker_empty(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with empty data from Renault.""" """Test for Renault device trackers with empty data from Renault."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -71,13 +70,13 @@ async def test_device_tracker_empty(
@pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception") @pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception")
async def test_device_tracker_errors( async def test_device_tracker_errors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with temporary failure.""" """Test for Renault device trackers with temporary failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -93,13 +92,13 @@ async def test_device_tracker_errors(
@pytest.mark.usefixtures("fixtures_with_access_denied_exception") @pytest.mark.usefixtures("fixtures_with_access_denied_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_device_tracker_access_denied( async def test_device_tracker_access_denied(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with access denied failure.""" """Test for Renault device trackers with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -112,13 +111,13 @@ async def test_device_tracker_access_denied(
@pytest.mark.usefixtures("fixtures_with_not_supported_exception") @pytest.mark.usefixtures("fixtures_with_not_supported_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_device_tracker_not_supported( async def test_device_tracker_not_supported(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault device trackers with not supported failure.""" """Test for Renault device trackers with not supported failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -5,8 +5,8 @@ from homeassistant.components.diagnostics import REDACTED
from homeassistant.components.renault import DOMAIN from homeassistant.components.renault import DOMAIN
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import mock_device_registry
from tests.components.diagnostics import ( from tests.components.diagnostics import (
get_diagnostics_for_config_entry, get_diagnostics_for_config_entry,
get_diagnostics_for_device, get_diagnostics_for_device,
@ -187,11 +187,12 @@ async def test_entry_diagnostics(
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_device_diagnostics( async def test_device_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry, hass_client hass: HomeAssistant,
config_entry: ConfigEntry,
device_registry: dr.DeviceRegistry,
hass_client,
): ):
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -13,6 +13,7 @@ from homeassistant.components.select import (
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import ( from . import (
check_device_registry, check_device_registry,
@ -22,7 +23,7 @@ from . import (
) )
from .const import MOCK_VEHICLES from .const import MOCK_VEHICLES
from tests.common import load_fixture, mock_device_registry, mock_registry from tests.common import load_fixture
pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
@ -36,12 +37,13 @@ def override_platforms() -> Generator[None, None, None]:
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
async def test_selects( async def test_selects(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault selects.""" """Test for Renault selects."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -56,12 +58,13 @@ async def test_selects(
@pytest.mark.usefixtures("fixtures_with_no_data") @pytest.mark.usefixtures("fixtures_with_no_data")
async def test_select_empty( async def test_select_empty(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault selects with empty data from Renault.""" """Test for Renault selects with empty data from Renault."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -75,12 +78,13 @@ async def test_select_empty(
@pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception") @pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception")
async def test_select_errors( async def test_select_errors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault selects with temporary failure.""" """Test for Renault selects with temporary failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -96,12 +100,13 @@ async def test_select_errors(
@pytest.mark.usefixtures("fixtures_with_access_denied_exception") @pytest.mark.usefixtures("fixtures_with_access_denied_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_select_access_denied( async def test_select_access_denied(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault selects with access denied failure.""" """Test for Renault selects with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -114,12 +119,13 @@ async def test_select_access_denied(
@pytest.mark.usefixtures("fixtures_with_not_supported_exception") @pytest.mark.usefixtures("fixtures_with_not_supported_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_select_not_supported( async def test_select_not_supported(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault selects with access denied failure.""" """Test for Renault selects with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -8,7 +8,7 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry, RegistryEntryDisabler from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import ( from . import (
check_device_registry, check_device_registry,
@ -18,8 +18,6 @@ from . import (
) )
from .const import ATTR_DEFAULT_DISABLED, MOCK_VEHICLES from .const import ATTR_DEFAULT_DISABLED, MOCK_VEHICLES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") pytestmark = pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
@ -31,7 +29,7 @@ def override_platforms() -> Generator[None, None, None]:
def _check_and_enable_disabled_entities( def _check_and_enable_disabled_entities(
entity_registry: EntityRegistry, expected_entities: MappingProxyType entity_registry: er.EntityRegistry, expected_entities: MappingProxyType
) -> None: ) -> None:
"""Ensure that the expected_entities are correctly disabled.""" """Ensure that the expected_entities are correctly disabled."""
for expected_entity in expected_entities: for expected_entity in expected_entities:
@ -39,18 +37,19 @@ def _check_and_enable_disabled_entities(
entity_id = expected_entity[ATTR_ENTITY_ID] entity_id = expected_entity[ATTR_ENTITY_ID]
registry_entry = entity_registry.entities.get(entity_id) registry_entry = entity_registry.entities.get(entity_id)
assert registry_entry.disabled assert registry_entry.disabled
assert registry_entry.disabled_by is RegistryEntryDisabler.INTEGRATION assert registry_entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
entity_registry.async_update_entity(entity_id, **{"disabled_by": None}) entity_registry.async_update_entity(entity_id, **{"disabled_by": None})
@pytest.mark.usefixtures("fixtures_with_data") @pytest.mark.usefixtures("fixtures_with_data")
async def test_sensors( async def test_sensors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault sensors.""" """Test for Renault sensors."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -69,12 +68,13 @@ async def test_sensors(
@pytest.mark.usefixtures("fixtures_with_no_data") @pytest.mark.usefixtures("fixtures_with_no_data")
async def test_sensor_empty( async def test_sensor_empty(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault sensors with empty data from Renault.""" """Test for Renault sensors with empty data from Renault."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -93,12 +93,13 @@ async def test_sensor_empty(
@pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception") @pytest.mark.usefixtures("fixtures_with_invalid_upstream_exception")
async def test_sensor_errors( async def test_sensor_errors(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault sensors with temporary failure.""" """Test for Renault sensors with temporary failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -118,12 +119,13 @@ async def test_sensor_errors(
@pytest.mark.usefixtures("fixtures_with_access_denied_exception") @pytest.mark.usefixtures("fixtures_with_access_denied_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_sensor_access_denied( async def test_sensor_access_denied(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault sensors with access denied failure.""" """Test for Renault sensors with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -136,12 +138,13 @@ async def test_sensor_access_denied(
@pytest.mark.usefixtures("fixtures_with_not_supported_exception") @pytest.mark.usefixtures("fixtures_with_not_supported_exception")
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) @pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
async def test_sensor_not_supported( async def test_sensor_not_supported(
hass: HomeAssistant, config_entry: ConfigEntry, vehicle_type: str hass: HomeAssistant,
config_entry: ConfigEntry,
vehicle_type: str,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for Renault sensors with access denied failure.""" """Test for Renault sensors with access denied failure."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -9,7 +9,7 @@ import pytest
import homeassistant.components.automation as automation import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.rfxtrx import DOMAIN from homeassistant.components.rfxtrx import DOMAIN
from homeassistant.helpers.device_registry import DeviceRegistry from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .conftest import create_rfx_test_cfg from .conftest import create_rfx_test_cfg
@ -18,23 +18,9 @@ from tests.common import (
MockConfigEntry, MockConfigEntry,
assert_lists_same, assert_lists_same,
async_get_device_automations, async_get_device_automations,
mock_device_registry,
mock_registry,
) )
@pytest.fixture(name="device_reg")
def device_reg_fixture(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture(name="entity_reg")
def entity_reg_fixture(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
class DeviceTestData(NamedTuple): class DeviceTestData(NamedTuple):
"""Test data linked to a device.""" """Test data linked to a device."""
@ -93,11 +79,11 @@ def _get_expected_actions(data):
[DEVICE_TEMPHUM_1, []], [DEVICE_TEMPHUM_1, []],
], ],
) )
async def test_get_actions(hass, device_reg: DeviceRegistry, device, expected): async def test_get_actions(hass, device_registry: dr.DeviceRegistry, device, expected):
"""Test we get the expected actions from a rfxtrx.""" """Test we get the expected actions from a rfxtrx."""
await setup_entry(hass, {device.code: {}}) await setup_entry(hass, {device.code: {}})
device_entry = device_reg.async_get_device(device.device_identifiers, set()) device_entry = device_registry.async_get_device(device.device_identifiers, set())
assert device_entry assert device_entry
actions = await async_get_device_automations( actions = await async_get_device_automations(
@ -134,13 +120,18 @@ async def test_get_actions(hass, device_reg: DeviceRegistry, device, expected):
], ],
) )
async def test_action( async def test_action(
hass, device_reg: DeviceRegistry, rfxtrx: RFXtrx.Connect, device, config, expected hass,
device_registry: dr.DeviceRegistry,
rfxtrx: RFXtrx.Connect,
device,
config,
expected,
): ):
"""Test for actions.""" """Test for actions."""
await setup_entry(hass, {device.code: {}}) await setup_entry(hass, {device.code: {}})
device_entry = device_reg.async_get_device(device.device_identifiers, set()) device_entry = device_registry.async_get_device(device.device_identifiers, set())
assert device_entry assert device_entry
assert await async_setup_component( assert await async_setup_component(
@ -169,14 +160,14 @@ async def test_action(
rfxtrx.transport.send.assert_called_once_with(bytearray.fromhex(expected)) rfxtrx.transport.send.assert_called_once_with(bytearray.fromhex(expected))
async def test_invalid_action(hass, device_reg: DeviceRegistry, caplog): async def test_invalid_action(hass, device_registry: dr.DeviceRegistry, caplog):
"""Test for invalid actions.""" """Test for invalid actions."""
device = DEVICE_LIGHTING_1 device = DEVICE_LIGHTING_1
await setup_entry(hass, {device.code: {}}) await setup_entry(hass, {device.code: {}})
device_identifers: Any = device.device_identifiers device_identifers: Any = device.device_identifiers
device_entry = device_reg.async_get_device(device_identifers, set()) device_entry = device_registry.async_get_device(device_identifers, set())
assert device_entry assert device_entry
assert await async_setup_component( assert await async_setup_component(

View file

@ -8,7 +8,7 @@ import pytest
import homeassistant.components.automation as automation import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.rfxtrx import DOMAIN from homeassistant.components.rfxtrx import DOMAIN
from homeassistant.helpers.device_registry import DeviceRegistry from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .conftest import create_rfx_test_cfg from .conftest import create_rfx_test_cfg
@ -18,7 +18,6 @@ from tests.common import (
assert_lists_same, assert_lists_same,
async_get_device_automations, async_get_device_automations,
async_mock_service, async_mock_service,
mock_device_registry,
) )
@ -45,12 +44,6 @@ EVENT_FIREALARM_1 = EventTestData(
) )
@pytest.fixture(name="device_reg")
def device_reg_fixture(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
async def setup_entry(hass, devices): async def setup_entry(hass, devices):
"""Construct a config setup.""" """Construct a config setup."""
entry_data = create_rfx_test_cfg(devices=devices) entry_data = create_rfx_test_cfg(devices=devices)
@ -84,11 +77,11 @@ async def setup_entry(hass, devices):
] ]
], ],
) )
async def test_get_triggers(hass, device_reg, event: EventTestData, expected): async def test_get_triggers(hass, device_registry, event: EventTestData, expected):
"""Test we get the expected triggers from a rfxtrx.""" """Test we get the expected triggers from a rfxtrx."""
await setup_entry(hass, {event.code: {}}) await setup_entry(hass, {event.code: {}})
device_entry = device_reg.async_get_device(event.device_identifiers, set()) device_entry = device_registry.async_get_device(event.device_identifiers, set())
expected_triggers = [ expected_triggers = [
{ {
@ -116,12 +109,12 @@ async def test_get_triggers(hass, device_reg, event: EventTestData, expected):
EVENT_FIREALARM_1, EVENT_FIREALARM_1,
], ],
) )
async def test_firing_event(hass, device_reg: DeviceRegistry, rfxtrx, event): async def test_firing_event(hass, device_registry: dr.DeviceRegistry, rfxtrx, event):
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
await setup_entry(hass, {event.code: {"fire_event": True}}) await setup_entry(hass, {event.code: {"fire_event": True}})
device_entry = device_reg.async_get_device(event.device_identifiers, set()) device_entry = device_registry.async_get_device(event.device_identifiers, set())
assert device_entry assert device_entry
calls = async_mock_service(hass, "test", "automation") calls = async_mock_service(hass, "test", "automation")
@ -155,14 +148,14 @@ async def test_firing_event(hass, device_reg: DeviceRegistry, rfxtrx, event):
assert calls[0].data["some"] == "device" assert calls[0].data["some"] == "device"
async def test_invalid_trigger(hass, device_reg: DeviceRegistry, caplog): async def test_invalid_trigger(hass, device_registry: dr.DeviceRegistry, caplog):
"""Test for invalid actions.""" """Test for invalid actions."""
event = EVENT_LIGHTING_1 event = EVENT_LIGHTING_1
await setup_entry(hass, {event.code: {"fire_event": True}}) await setup_entry(hass, {event.code: {"fire_event": True}})
device_identifers: Any = event.device_identifiers device_identifers: Any = event.device_identifiers
device_entry = device_reg.async_get_device(device_identifers, set()) device_entry = device_registry.async_get_device(device_identifers, set())
assert device_entry assert device_entry
assert await async_setup_component( assert await async_setup_component(

View file

@ -1,14 +1,12 @@
"""Tests for the SABnzbd Integration.""" """Tests for the SABnzbd Integration."""
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components.sabnzbd import DEFAULT_NAME, DOMAIN, OLD_SENSOR_KEYS from homeassistant.components.sabnzbd import DEFAULT_NAME, DOMAIN, OLD_SENSOR_KEYS
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_URL from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_URL
from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry, mock_device_registry, mock_registry from tests.common import MockConfigEntry
MOCK_ENTRY_ID = "mock_entry_id" MOCK_ENTRY_ID = "mock_entry_id"
@ -27,18 +25,6 @@ MOCK_ENTRY_VERSION_1 = MockConfigEntry(
) )
@pytest.fixture
def device_registry(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_registry(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
async def test_unique_id_migrate(hass, device_registry, entity_registry): async def test_unique_id_migrate(hass, device_registry, entity_registry):
"""Test that config flow entry is migrated correctly.""" """Test that config flow entry is migrated correctly."""
# Start with the config entry at Version 1. # Start with the config entry at Version 1.
@ -49,7 +35,7 @@ async def test_unique_id_migrate(hass, device_registry, entity_registry):
config_entry_id=mock_entry.entry_id, config_entry_id=mock_entry.entry_id,
identifiers={(DOMAIN, DOMAIN)}, identifiers={(DOMAIN, DOMAIN)},
name=DEFAULT_NAME, name=DEFAULT_NAME,
entry_type=DeviceEntryType.SERVICE, entry_type=dr.DeviceEntryType.SERVICE,
) )
entity_id_sensor_key = [] entity_id_sensor_key = []

View file

@ -7,12 +7,11 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import check_device_registry, check_entities from . import check_device_registry, check_entities
from .const import EXPECTED_ENTITIES from .const import EXPECTED_ENTITIES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info") pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info")
@ -23,11 +22,13 @@ def override_platforms() -> Generator[None, None, None]:
yield yield
async def test_binary_sensors(hass: HomeAssistant, config_entry: ConfigEntry) -> None: async def test_binary_sensors(
hass: HomeAssistant,
config_entry: ConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for SFR Box binary sensors.""" """Test for SFR Box binary sensors."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -10,12 +10,11 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import check_device_registry, check_entities from . import check_device_registry, check_entities
from .const import EXPECTED_ENTITIES from .const import EXPECTED_ENTITIES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info") pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info")
@ -29,12 +28,12 @@ def override_platforms() -> Generator[None, None, None]:
async def test_buttons( async def test_buttons(
hass: HomeAssistant, config_entry_with_auth: ConfigEntry hass: HomeAssistant,
config_entry_with_auth: ConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test for SFR Box buttons.""" """Test for SFR Box buttons."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry_with_auth.entry_id) await hass.config_entries.async_setup(config_entry_with_auth.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -8,13 +8,11 @@ import pytest
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry, RegistryEntryDisabler from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import check_device_registry, check_entities from . import check_device_registry, check_entities
from .const import ATTR_DEFAULT_DISABLED, EXPECTED_ENTITIES from .const import ATTR_DEFAULT_DISABLED, EXPECTED_ENTITIES
from tests.common import mock_device_registry, mock_registry
pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info") pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info")
@ -26,7 +24,7 @@ def override_platforms() -> Generator[None, None, None]:
def _check_and_enable_disabled_entities( def _check_and_enable_disabled_entities(
entity_registry: EntityRegistry, expected_entities: MappingProxyType entity_registry: er.EntityRegistry, expected_entities: MappingProxyType
) -> None: ) -> None:
"""Ensure that the expected_entities are correctly disabled.""" """Ensure that the expected_entities are correctly disabled."""
for expected_entity in expected_entities: for expected_entity in expected_entities:
@ -35,15 +33,17 @@ def _check_and_enable_disabled_entities(
registry_entry = entity_registry.entities.get(entity_id) registry_entry = entity_registry.entities.get(entity_id)
assert registry_entry, f"Registry entry not found for {entity_id}" assert registry_entry, f"Registry entry not found for {entity_id}"
assert registry_entry.disabled assert registry_entry.disabled
assert registry_entry.disabled_by is RegistryEntryDisabler.INTEGRATION assert registry_entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
entity_registry.async_update_entity(entity_id, **{"disabled_by": None}) entity_registry.async_update_entity(entity_id, **{"disabled_by": None})
async def test_sensors(hass: HomeAssistant, config_entry: ConfigEntry) -> None: async def test_sensors(
hass: HomeAssistant,
config_entry: ConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for SFR Box sensors.""" """Test for SFR Box sensors."""
entity_registry = mock_registry(hass)
device_registry = mock_device_registry(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -7,8 +7,9 @@ from homeassistant.components.velbus.const import DOMAIN
from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.config_entries import ConfigEntry, ConfigEntryState
from homeassistant.const import CONF_NAME, CONF_PORT from homeassistant.const import CONF_NAME, CONF_PORT
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry, mock_device_registry from tests.common import MockConfigEntry
@pytest.mark.usefixtures("controller") @pytest.mark.usefixtures("controller")
@ -29,13 +30,12 @@ async def test_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry):
@pytest.mark.usefixtures("controller") @pytest.mark.usefixtures("controller")
async def test_device_identifier_migration( async def test_device_identifier_migration(
hass: HomeAssistant, config_entry: ConfigEntry hass: HomeAssistant, config_entry: ConfigEntry, device_registry: dr.DeviceRegistry
): ):
"""Test being able to unload an entry.""" """Test being able to unload an entry."""
original_identifiers = {(DOMAIN, "module_address", "module_serial")} original_identifiers = {(DOMAIN, "module_address", "module_serial")}
target_identifiers = {(DOMAIN, "module_address")} target_identifiers = {(DOMAIN, "module_address")}
device_registry = mock_device_registry(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
identifiers=original_identifiers, # type: ignore[arg-type] identifiers=original_identifiers, # type: ignore[arg-type]

View file

@ -8,8 +8,9 @@ from homeassistant.components.vera import CONF_CONTROLLER, CONF_LEGACY_UNIQUE_ID
from homeassistant.const import CONF_EXCLUDE, CONF_LIGHTS, CONF_SOURCE from homeassistant.const import CONF_EXCLUDE, CONF_LIGHTS, CONF_SOURCE
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, mock_registry from tests.common import MockConfigEntry
async def test_async_step_user_success(hass: HomeAssistant) -> None: async def test_async_step_user_success(hass: HomeAssistant) -> None:
@ -74,10 +75,9 @@ async def test_async_step_import_success(hass: HomeAssistant) -> None:
async def test_async_step_import_success_with_legacy_unique_id( async def test_async_step_import_success_with_legacy_unique_id(
hass: HomeAssistant, hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None: ) -> None:
"""Test import step success with legacy unique id.""" """Test import step success with legacy unique id."""
entity_registry = mock_registry(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
domain="switch", platform=DOMAIN, unique_id="12" domain="switch", platform=DOMAIN, unique_id="12"
) )

View file

@ -17,7 +17,7 @@ from homeassistant.helpers import entity_registry as er
from .common import ComponentFactory, ConfigSource, new_simple_controller_config from .common import ComponentFactory, ConfigSource, new_simple_controller_config
from tests.common import MockConfigEntry, mock_registry from tests.common import MockConfigEntry
async def test_init( async def test_init(
@ -75,7 +75,9 @@ async def test_init_from_file(
async def test_multiple_controllers_with_legacy_one( async def test_multiple_controllers_with_legacy_one(
hass: HomeAssistant, vera_component_factory: ComponentFactory hass: HomeAssistant,
vera_component_factory: ComponentFactory,
entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test multiple controllers with one legacy controller.""" """Test multiple controllers with one legacy controller."""
vera_device1: pv.VeraBinarySensor = MagicMock(spec=pv.VeraBinarySensor) vera_device1: pv.VeraBinarySensor = MagicMock(spec=pv.VeraBinarySensor)
@ -93,7 +95,6 @@ async def test_multiple_controllers_with_legacy_one(
entity2_id = "binary_sensor.second_dev_2" entity2_id = "binary_sensor.second_dev_2"
# Add existing entity registry entry from previous setup. # Add existing entity registry entry from previous setup.
entity_registry = mock_registry(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
domain="switch", platform=DOMAIN, unique_id="12" domain="switch", platform=DOMAIN, unique_id="12"
) )

View file

@ -9,7 +9,7 @@ from homeassistant.components.zwave_me import ZWaveMePlatform
from homeassistant.const import CONF_TOKEN, CONF_URL from homeassistant.const import CONF_TOKEN, CONF_URL
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, mock_device_registry from tests.common import MockConfigEntry
DEFAULT_DEVICE_INFO = ZWaveMeData( DEFAULT_DEVICE_INFO = ZWaveMeData(
id="DummyDevice", id="DummyDevice",
@ -20,12 +20,6 @@ DEFAULT_DEVICE_INFO = ZWaveMeData(
) )
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
async def mock_connection(controller): async def mock_connection(controller):
"""Mock established connection and setting identifiers.""" """Mock established connection and setting identifiers."""
controller.on_new_device(DEFAULT_DEVICE_INFO) controller.on_new_device(DEFAULT_DEVICE_INFO)
@ -40,7 +34,7 @@ async def mock_connection(controller):
], ],
) )
async def test_remove_stale_devices( async def test_remove_stale_devices(
hass: HomeAssistant, device_reg, identifier, should_exist hass: HomeAssistant, device_registry, identifier, should_exist
): ):
"""Test removing devices with old-format ids.""" """Test removing devices with old-format ids."""
@ -50,7 +44,7 @@ async def test_remove_stale_devices(
data={CONF_TOKEN: "test_token", CONF_URL: "http://test_test"}, data={CONF_TOKEN: "test_token", CONF_URL: "http://test_test"},
) )
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
device_reg.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=config_entry.entry_id,
connections={("mac", "12:34:56:AB:CD:EF")}, connections={("mac", "12:34:56:AB:CD:EF")},
identifiers={("zwave_me", f"{config_entry.unique_id}-{identifier}")}, identifiers={("zwave_me", f"{config_entry.unique_id}-{identifier}")},
@ -64,7 +58,7 @@ async def test_remove_stale_devices(
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
assert ( assert (
bool( bool(
device_reg.async_get_device( device_registry.async_get_device(
{ {
( (
"zwave_me", "zwave_me",