def test_async_remove_with_platform(hass):
    """Remove an entity from a platform."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    entity1 = MockEntity(name='test_1')
    yield from component.async_add_entities([entity1])
    assert len(hass.states.async_entity_ids()) == 1
    yield from entity1.async_remove()
    assert len(hass.states.async_entity_ids()) == 0
    def test_update_state_adds_entities_with_update_before_add_false(self):
        """Test if not call update before add to state machine."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        ent = MockEntity()
        ent.update = Mock(spec_set=True)

        component.add_entities([ent], False)
        self.hass.block_till_done()

        assert 1 == len(self.hass.states.entity_ids())
        assert not ent.update.called
async def test_update_entity(hass):
    """Test that we can update an entity with the helper."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    entity = MockEntity()
    entity.async_update_ha_state = Mock(return_value=mock_coro())
    await component.async_add_entities([entity])

    # Called as part of async_add_entities
    assert len(entity.async_update_ha_state.mock_calls) == 1

    await hass.helpers.entity_component.async_update_entity(entity.entity_id)

    assert len(entity.async_update_ha_state.mock_calls) == 2
    assert entity.async_update_ha_state.mock_calls[-1][1][0] is True
    def test_update_state_adds_entities(self):
        """Test if updating poll entities cause an entity to be added works."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        ent1 = MockEntity()
        ent2 = MockEntity(should_poll=True)

        component.add_entities([ent2])
        assert 1 == len(self.hass.states.entity_ids())
        ent2.update = lambda *_: component.add_entities([ent1])

        fire_time_changed(
            self.hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL
        )
        self.hass.block_till_done()

        assert 2 == len(self.hass.states.entity_ids())
def test_raise_error_on_update(hass):
    """Test the add entity if they raise an error on update."""
    updates = []
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    entity1 = MockEntity(name='test_1')
    entity2 = MockEntity(name='test_2')

    def _raise():
        """Helper to raise an exception."""
        raise AssertionError

    entity1.update = _raise
    entity2.update = lambda: updates.append(1)

    yield from component.async_add_entities([entity1, entity2], True)

    assert len(updates) == 1
    assert 1 in updates
    def test_polling_only_updates_entities_it_should_poll(self):
        """Test the polling of only updated entities."""
        component = EntityComponent(
            _LOGGER, DOMAIN, self.hass, timedelta(seconds=20))

        no_poll_ent = MockEntity(should_poll=False)
        no_poll_ent.async_update = Mock()
        poll_ent = MockEntity(should_poll=True)
        poll_ent.async_update = Mock()

        component.add_entities([no_poll_ent, poll_ent])

        no_poll_ent.async_update.reset_mock()
        poll_ent.async_update.reset_mock()

        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=20))
        self.hass.block_till_done()

        assert not no_poll_ent.async_update.called
        assert poll_ent.async_update.called
Example #7
0
def test_using_prescribed_entity_id_which_is_registered(hass):
    """Test not allowing predefined entity ID that already registered."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    registry = mock_registry(hass)
    # Register test_domain.world
    registry.async_get_or_create(DOMAIN,
                                 'test',
                                 '1234',
                                 suggested_object_id='world')

    # This entity_id will be rewritten
    yield from component.async_add_entities(
        [MockEntity(entity_id='test_domain.world')])

    assert 'test_domain.world_2' in hass.states.async_entity_ids()
Example #8
0
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities([
         MockEntity(
             unique_id="qwer",
             device_info={
                 "identifiers": {("hue", "1234")},
                 "connections": {(dr.CONNECTION_NETWORK_MAC, "abcd")},
                 "name": "Device Bla",
             },
             has_entity_name=has_entity_name,
             name=entity_name,
         ),
     ])
     return True
Example #9
0
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities([
         # Invalid device info
         MockEntity(unique_id="abcd", device_info={}),
         # Valid device info
         MockEntity(
             unique_id="qwer",
             device_info={
                 "identifiers": {("hue", "1234")},
                 "configuration_url": "http://192.168.0.100/config",
                 "connections": {(dr.CONNECTION_NETWORK_MAC, "abcd")},
                 "manufacturer": "test-manuf",
                 "model": "test-model",
                 "name": "test-name",
                 "sw_version": "test-sw",
                 "hw_version": "test-hw",
                 "suggested_area": "Heliport",
                 "entry_type": dr.DeviceEntryType.SERVICE,
                 "via_device": ("hue", "via-id"),
             },
         ),
     ])
     return True
Example #10
0
async def test_using_prescribed_entity_id_which_is_registered(hass):
    """Test not allowing predefined entity ID that already registered."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    registry = mock_registry(hass)
    # Register test_domain.world
    registry.async_get_or_create(DOMAIN,
                                 "test",
                                 "1234",
                                 suggested_object_id="world")

    # This entity_id will be rewritten
    await component.async_add_entities(
        [MockEntity(entity_id="test_domain.world")])

    assert "test_domain.world_2" in hass.states.async_entity_ids()
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities(
         [
             # Valid device info, but invalid url
             MockEntity(
                 unique_id="qwer",
                 device_info={
                     "identifiers": {("hue", "1234")},
                     "configuration_url": "foo://192.168.0.100/config",
                 },
             ),
         ]
     )
     return True
Example #12
0
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities(
         [
             # Invalid device info
             MockEntity(unique_id="abcd", device_info={}),
             # Valid device info
             MockEntity(
                 unique_id="qwer",
                 device_info={
                     "identifiers": {("hue", "1234")},
                     "connections": {("mac", "abcd")},
                     "manufacturer": "test-manuf",
                     "model": "test-model",
                     "name": "test-name",
                     "sw_version": "test-sw",
                     "suggested_area": "Heliport",
                     "entry_type": "service",
                     "via_device": ("hue", "via-id"),
                 },
             ),
         ]
     )
     return True
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities(
         [
             # Valid device info, with homeassistant url
             MockEntity(
                 unique_id="qwer",
                 device_info={
                     "identifiers": {("mqtt", "1234")},
                     "configuration_url": None,
                 },
             ),
         ]
     )
     return True
Example #14
0
async def test_update_entity_require_restart(hass, client):
    """Test updating entity."""
    entity_id = "test_domain.test_platform_1234"
    config_entry = MockConfigEntry(domain="test_platform")
    config_entry.add_to_hass(hass)
    platform = MockEntityPlatform(hass)
    platform.config_entry = config_entry
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get(entity_id)
    assert state is not None

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": entity_id,
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "area_id": None,
            "capabilities": None,
            "config_entry_id": config_entry.entry_id,
            "device_class": None,
            "device_id": None,
            "disabled_by": None,
            "entity_category": None,
            "entity_id": entity_id,
            "icon": None,
            "hidden_by": None,
            "has_entity_name": False,
            "name": None,
            "options": {},
            "original_device_class": None,
            "original_icon": None,
            "original_name": None,
            "platform": "test_platform",
            "unique_id": "1234",
        },
        "require_restart": True,
    }
async def test_update_entity_id(opp, client):
    """Test update entity id."""
    mock_registry(
        opp,
        {
            "test_domain.world":
            RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
            )
        },
    )
    platform = MockEntityPlatform(opp)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    assert opp.states.get("test_domain.world") is not None

    await client.send_json({
        "id": 6,
        "type": "config/entity_registry/update",
        "entity_id": "test_domain.world",
        "new_entity_id": "test_domain.planet",
    })

    msg = await client.receive_json()

    assert msg["result"] == {
        "entity_entry": {
            "config_entry_id": None,
            "device_id": None,
            "area_id": None,
            "disabled_by": None,
            "platform": "test_platform",
            "entity_id": "test_domain.planet",
            "name": None,
            "icon": None,
            "original_name": None,
            "original_icon": None,
            "capabilities": None,
            "unique_id": "1234",
        }
    }

    assert opp.states.get("test_domain.world") is None
    assert opp.states.get("test_domain.planet") is not None
async def test_update_entity_no_changes(hass, client):
    """Test update entity with no changes."""
    mock_registry(
        hass,
        {
            "test_domain.world":
            RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                name="name of entity",
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get("test_domain.world")
    assert state is not None
    assert state.name == "name of entity"

    await client.send_json({
        "id": 6,
        "type": "config/entity_registry/update",
        "entity_id": "test_domain.world",
        "name": "name of entity",
    })

    msg = await client.receive_json()

    assert msg["result"] == {
        "config_entry_id": None,
        "device_id": None,
        "disabled_by": None,
        "platform": "test_platform",
        "entity_id": "test_domain.world",
        "name": "name of entity",
        "icon": None,
        "original_name": None,
        "original_icon": None,
        "capabilities": None,
        "unique_id": "1234",
    }

    state = hass.states.get("test_domain.world")
    assert state.name == "name of entity"
Example #17
0
async def test_entity_registry_updates_invalid_entity_id(hass):
    """Test that we can't update to an invalid entity id."""
    registry = mock_registry(
        hass,
        {
            "test_domain.world": er.RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                name="Some name",
            ),
            "test_domain.existing": er.RegistryEntry(
                entity_id="test_domain.existing",
                unique_id="5678",
                platform="test_platform",
            ),
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get("test_domain.world")
    assert state is not None
    assert state.name == "Some name"

    with pytest.raises(ValueError):
        registry.async_update_entity(
            "test_domain.world", new_entity_id="test_domain.existing"
        )

    with pytest.raises(ValueError):
        registry.async_update_entity(
            "test_domain.world", new_entity_id="invalid_entity_id"
        )

    with pytest.raises(ValueError):
        registry.async_update_entity(
            "test_domain.world", new_entity_id="diff_domain.world"
        )

    await hass.async_block_till_done()
    await hass.async_block_till_done()

    assert hass.states.get("test_domain.world") is not None
    assert hass.states.get("invalid_entity_id") is None
    assert hass.states.get("diff_domain.world") is None
def test_registry_respect_entity_disabled(hass):
    """Test that the registry respects entity disabled."""
    mock_registry(hass, {
        'test_domain.world': entity_registry.RegistryEntry(
            entity_id='test_domain.world',
            unique_id='1234',
            # Using component.async_add_entities is equal to platform "domain"
            platform='test_platform',
            disabled_by=entity_registry.DISABLED_USER
        )
    })
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id='1234')
    yield from platform.async_add_entities([entity])
    assert entity.entity_id is None
    assert hass.states.async_entity_ids() == []
Example #19
0
 async def async_setup_entry(hass, config_entry, async_add_entities):
     """Mock setup entry method."""
     async_add_entities(
         [
             MockEntity(
                 unique_id="qwer",
                 device_info={
                     "connections": {("mac", "abcd")},
                     "default_name": "default name 1",
                     "default_model": "default model 1",
                     "default_manufacturer": "default manufacturer 1",
                 },
             )
         ]
     )
     return True
async def test_enable_entity_disabled_device(hass, client, device_registry):
    """Test enabling entity of disabled device."""
    config_entry = MockConfigEntry(domain="test_platform")
    config_entry.add_to_hass(hass)

    device = device_registry.async_get_or_create(
        config_entry_id="1234",
        connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
        identifiers={("bridgeid", "0123")},
        manufacturer="manufacturer",
        model="model",
        disabled_by=DISABLED_USER,
    )

    mock_registry(
        hass,
        {
            "test_domain.world": RegistryEntry(
                config_entry_id=config_entry.entry_id,
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                device_id=device.id,
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])

    state = hass.states.get("test_domain.world")
    assert state is not None

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": "test_domain.world",
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]
Example #21
0
async def test_override_restored_entities(hass):
    """Test that we allow overriding restored entities."""
    registry = mock_registry(hass)
    registry.async_get_or_create(
        "test_domain", "test_domain", "1234", suggested_object_id="world"
    )

    hass.states.async_set("test_domain.world", "unavailable", {"restored": True})

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    await component.async_add_entities(
        [MockEntity(unique_id="1234", state="on", entity_id="test_domain.world")], True
    )

    state = hass.states.get("test_domain.world")
    assert state.state == "on"
Example #22
0
async def test_parallel_updates_no_update_method(hass):
    """Test platform parallel_updates default set to 0."""
    platform = MockPlatform()

    mock_entity_platform(hass, "test_domain.platform", platform)

    component = EntityComponent(_LOGGER, DOMAIN, hass)
    component._platforms = {}

    await component.async_setup({DOMAIN: {"platform": "platform"}})
    await hass.async_block_till_done()

    handle = list(component._platforms.values())[-1]

    entity = MockEntity()
    await handle.async_add_entities([entity])
    assert entity.parallel_updates is None
Example #23
0
async def test_enable_entity_disabled_device(hass, client, device_registry):
    """Test enabling entity of disabled device."""
    entity_id = "test_domain.test_platform_1234"
    config_entry = MockConfigEntry(domain="test_platform")
    config_entry.add_to_hass(hass)

    device = device_registry.async_get_or_create(
        config_entry_id="1234",
        connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
        identifiers={("bridgeid", "0123")},
        manufacturer="manufacturer",
        model="model",
        disabled_by=DeviceEntryDisabler.USER,
    )
    device_info = {
        "connections": {("ethernet", "12:34:56:78:90:AB:CD:EF")},
    }

    platform = MockEntityPlatform(hass)
    platform.config_entry = config_entry
    entity = MockEntity(unique_id="1234", device_info=device_info)
    await platform.async_add_entities([entity])

    state = hass.states.get(entity_id)
    assert state is None

    entity_reg = async_get_entity_registry(hass)
    entity_entry = entity_reg.async_get(entity_id)
    assert entity_entry.config_entry_id == config_entry.entry_id
    assert entity_entry.device_id == device.id
    assert entity_entry.disabled_by == RegistryEntryDisabler.DEVICE

    # UPDATE DISABLED_BY TO NONE
    await client.send_json(
        {
            "id": 8,
            "type": "config/entity_registry/update",
            "entity_id": entity_id,
            "disabled_by": None,
        }
    )

    msg = await client.receive_json()

    assert not msg["success"]
Example #24
0
async def test_entity_registry_updates_invalid_entity_id(hass):
    """Test that we can't update to an invalid entity id."""
    registry = mock_registry(
        hass,
        {
            'test_domain.world':
            entity_registry.RegistryEntry(
                entity_id='test_domain.world',
                unique_id='1234',
                # Using component.async_add_entities is equal to platform "domain"
                platform='test_platform',
                name='Some name'),
            'test_domain.existing':
            entity_registry.RegistryEntry(
                entity_id='test_domain.existing',
                unique_id='5678',
                platform='test_platform',
            ),
        })
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id='1234')
    await platform.async_add_entities([entity])

    state = hass.states.get('test_domain.world')
    assert state is not None
    assert state.name == 'Some name'

    with pytest.raises(ValueError):
        registry.async_update_entity('test_domain.world',
                                     new_entity_id='test_domain.existing')

    with pytest.raises(ValueError):
        registry.async_update_entity('test_domain.world',
                                     new_entity_id='invalid_entity_id')

    with pytest.raises(ValueError):
        registry.async_update_entity('test_domain.world',
                                     new_entity_id='diff_domain.world')

    await hass.async_block_till_done()
    await hass.async_block_till_done()

    assert hass.states.get('test_domain.world') is not None
    assert hass.states.get('invalid_entity_id') is None
    assert hass.states.get('diff_domain.world') is None
Example #25
0
def test_overriding_name_from_registry(hass):
    """Test that we can override a name via the Entity Registry."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    mock_registry(hass, {
        'test_domain.world': entity_registry.RegistryEntry(
            entity_id='test_domain.world',
            unique_id='1234',
            # Using component.async_add_entities is equal to platform "domain"
            platform='test_domain',
            name='Overridden'
        )
    })
    yield from component.async_add_entities([
        MockEntity(unique_id='1234', name='Device Name')])

    state = hass.states.get('test_domain.world')
    assert state is not None
    assert state.name == 'Overridden'
Example #26
0
async def test_registry_respect_entity_disabled(hass):
    """Test that the registry respects entity disabled."""
    mock_registry(
        hass,
        {
            "test_domain.world": er.RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_platform",
                disabled_by=er.DISABLED_USER,
            )
        },
    )
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id="1234")
    await platform.async_add_entities([entity])
    assert entity.entity_id == "test_domain.world"
    assert hass.states.async_entity_ids() == []
async def test_unload_entry_resets_platform(hass):
    """Test unloading an entry removes all entities."""
    mock_setup_entry = Mock(return_value=mock_coro(True))
    loader.set_component(hass, 'test_domain.entry_domain',
                         MockPlatform(async_setup_entry=mock_setup_entry))

    component = EntityComponent(_LOGGER, DOMAIN, hass)
    entry = MockConfigEntry(domain='entry_domain')

    assert await component.async_setup_entry(entry)
    assert len(mock_setup_entry.mock_calls) == 1
    add_entities = mock_setup_entry.mock_calls[0][1][2]
    add_entities([MockEntity()])
    await hass.async_block_till_done()

    assert len(hass.states.async_entity_ids()) == 1

    assert await component.async_unload_entry(entry)
    assert len(hass.states.async_entity_ids()) == 0
async def test_set_service_race(hass):
    """Test race condition on setting service."""
    exception = False

    def async_loop_exception_handler(_, _2) -> None:
        """Handle all exception inside the core loop."""
        nonlocal exception
        exception = True

    hass.loop.set_exception_handler(async_loop_exception_handler)

    await async_setup_component(hass, "group", {})
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    for _ in range(2):
        hass.async_create_task(component.async_add_entities([MockEntity()]))

    await hass.async_block_till_done()
    assert not exception
Example #29
0
async def test_update_entity_no_changes(hass, client):
    """Test update entity with no changes."""
    mock_registry(
        hass,
        {
            'test_domain.world':
            RegistryEntry(
                entity_id='test_domain.world',
                unique_id='1234',
                # Using component.async_add_entities is equal to platform "domain"
                platform='test_platform',
                name='name of entity')
        })
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id='1234')
    await platform.async_add_entities([entity])

    state = hass.states.get('test_domain.world')
    assert state is not None
    assert state.name == 'name of entity'

    await client.send_json({
        'id': 6,
        'type': 'config/entity_registry/update',
        'entity_id': 'test_domain.world',
        'name': 'name of entity',
    })

    msg = await client.receive_json()

    assert msg['result'] == {
        'config_entry_id': None,
        'device_id': None,
        'disabled_by': None,
        'platform': 'test_platform',
        'entity_id': 'test_domain.world',
        'name': 'name of entity'
    }

    state = hass.states.get('test_domain.world')
    assert state.name == 'name of entity'
Example #30
0
async def test_entity_info_added_to_entity_registry(hass):
    """Test entity info is written to entity registry."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20))

    entity_default = MockEntity(
        unique_id="default",
        capability_attributes={"max": 100},
        supported_features=5,
        device_class="mock-device-class",
        unit_of_measurement=PERCENTAGE,
    )

    await component.async_add_entities([entity_default])

    registry = er.async_get(hass)

    entry_default = registry.async_get_or_create(DOMAIN, DOMAIN, "default")
    assert entry_default.capabilities == {"max": 100}
    assert entry_default.supported_features == 5
    assert entry_default.device_class == "mock-device-class"
    assert entry_default.unit_of_measurement == PERCENTAGE
Example #31
0
async def test_overriding_name_from_registry(hass):
    """Test that we can override a name via the Entity Registry."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    mock_registry(
        hass,
        {
            "test_domain.world":
            entity_registry.RegistryEntry(
                entity_id="test_domain.world",
                unique_id="1234",
                # Using component.async_add_entities is equal to platform "domain"
                platform="test_domain",
                name="Overridden",
            )
        },
    )
    await component.async_add_entities(
        [MockEntity(unique_id="1234", name="Device Name")])

    state = hass.states.get("test_domain.world")
    assert state is not None
    assert state.name == "Overridden"
async def test_unload_entry_resets_platform(opp):
    """Test unloading an entry removes all entities."""
    mock_setup_entry = AsyncMock(return_value=True)
    mock_entity_platform(
        opp,
        "test_domain.entry_domain",
        MockPlatform(async_setup_entry=mock_setup_entry),
    )

    component = EntityComponent(_LOGGER, DOMAIN, opp)
    entry = MockConfigEntry(domain="entry_domain")

    assert await component.async_setup_entry(entry)
    assert len(mock_setup_entry.mock_calls) == 1
    add_entities = mock_setup_entry.mock_calls[0][1][2]
    add_entities([MockEntity()])
    await opp.async_block_till_done()

    assert len(opp.states.async_entity_ids()) == 1

    assert await component.async_unload_entry(entry)
    assert len(opp.states.async_entity_ids()) == 0
    def test_polling_updates_entities_with_exception(self):
        """Test the updated entities that not break with an exception."""
        component = EntityComponent(
            _LOGGER, DOMAIN, self.hass, timedelta(seconds=20))

        update_ok = []
        update_err = []

        def update_mock():
            """Mock normal update."""
            update_ok.append(None)

        def update_mock_err():
            """Mock error update."""
            update_err.append(None)
            raise AssertionError("Fake error update")

        ent1 = MockEntity(should_poll=True)
        ent1.update = update_mock_err
        ent2 = MockEntity(should_poll=True)
        ent2.update = update_mock
        ent3 = MockEntity(should_poll=True)
        ent3.update = update_mock
        ent4 = MockEntity(should_poll=True)
        ent4.update = update_mock

        component.add_entities([ent1, ent2, ent3, ent4])

        update_ok.clear()
        update_err.clear()

        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=20))
        self.hass.block_till_done()

        assert len(update_ok) == 3
        assert len(update_err) == 1
Example #34
0
def test_raise_error_on_update(hass):
    """Test the add entity if they raise an error on update."""
    updates = []
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    entity1 = MockEntity(name='test_1')
    entity2 = MockEntity(name='test_2')

    def _raise():
        """Helper to raise an exception."""
        raise AssertionError

    entity1.update = _raise
    entity2.update = lambda: updates.append(1)

    yield from component.async_add_entities([entity1, entity2], True)

    assert len(updates) == 1
    assert 1 in updates
async def test_update_entity_name(hass, client):
    """Test updating entity name."""
    mock_registry(
        hass,
        {
            'test_domain.world':
            RegistryEntry(
                entity_id='test_domain.world',
                unique_id='1234',
                # Using component.async_add_entities is equal to platform "domain"
                platform='test_platform',
                name='before update')
        })
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id='1234')
    await platform.async_add_entities([entity])

    state = hass.states.get('test_domain.world')
    assert state is not None
    assert state.name == 'before update'

    await client.send_json({
        'id': 6,
        'type': 'config/entity_registry/update',
        'entity_id': 'test_domain.world',
        'name': 'after update',
    })

    msg = await client.receive_json()

    assert msg['result'] == {
        'entity_id': 'test_domain.world',
        'name': 'after update'
    }

    state = hass.states.get('test_domain.world')
    assert state.name == 'after update'
Example #36
0
async def test_entity_info_added_to_entity_registry(hass):
    """Test entity info is written to entity registry."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20))

    entity_default = MockEntity(
        capability_attributes={"max": 100},
        device_class="mock-device-class",
        entity_category=EntityCategory.CONFIG,
        icon="nice:icon",
        name="best name",
        supported_features=5,
        unique_id="default",
        unit_of_measurement=PERCENTAGE,
    )

    await component.async_add_entities([entity_default])

    registry = er.async_get(hass)

    entry_default = registry.async_get_or_create(DOMAIN, DOMAIN, "default")
    assert entry_default == er.RegistryEntry(
        "test_domain.best_name",
        "default",
        "test_domain",
        capabilities={"max": 100},
        device_class=None,
        entity_category=EntityCategory.CONFIG,
        icon=None,
        id=ANY,
        name=None,
        original_device_class="mock-device-class",
        original_icon="nice:icon",
        original_name="best name",
        supported_features=5,
        unit_of_measurement=PERCENTAGE,
    )
async def test_entity_disabled_by_device(hass: HomeAssistant):
    """Test entity disabled by device."""

    connections = {(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}
    entity_disabled = MockEntity(
        unique_id="disabled", device_info=DeviceInfo(connections=connections)
    )

    async def async_setup_entry(hass, config_entry, async_add_entities):
        """Mock setup entry method."""
        async_add_entities([entity_disabled])
        return True

    platform = MockPlatform(async_setup_entry=async_setup_entry)
    config_entry = MockConfigEntry(entry_id="super-mock-id", domain=DOMAIN)
    entity_platform = MockEntityPlatform(
        hass, platform_name=config_entry.domain, platform=platform
    )

    device_registry = dr.async_get(hass)
    device_registry.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections=connections,
        disabled_by=dr.DeviceEntryDisabler.USER,
    )

    assert await entity_platform.async_setup_entry(config_entry)
    await hass.async_block_till_done()

    assert entity_disabled.hass is None
    assert entity_disabled.platform is None

    registry = er.async_get(hass)

    entry_disabled = registry.async_get_or_create(DOMAIN, DOMAIN, "disabled")
    assert entry_disabled.disabled_by is er.RegistryEntryDisabler.DEVICE
 def create_entity(number):
     """Create entity helper."""
     entity = MockEntity()
     entity.entity_id = generate_entity_id(DOMAIN + '.{}',
                                           'Number', hass=self.hass)
     return entity