コード例 #1
0
async def test_update_entity_no_changes(hass, client):
    """Test get entry."""
    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'

    resp = await client.post(
        '/api/config/entity_registry/test_domain.world', json={
            'name': 'name of entity'
        })
    assert resp.status == 200
    data = await resp.json()
    assert data == {
        'entity_id': 'test_domain.world',
        'name': 'name of entity'
    }

    state = hass.states.get('test_domain.world')
    assert state.name == 'name of entity'
コード例 #2
0
def test_loading_file(hass, test_client):
    """Test that it loads image from disk."""
    mock_registry(hass)

    with mock.patch('os.path.isfile', mock.Mock(return_value=True)), \
            mock.patch('os.access', mock.Mock(return_value=True)):
        yield from async_setup_component(hass, 'camera', {
            'camera': {
                'name': 'config_test',
                'platform': 'local_file',
                'file_path': 'mock.file',
            }})

    client = yield from test_client(hass.http.app)

    m_open = MockOpen(read_data=b'hello')
    with mock.patch(
            'homeassistant.components.camera.local_file.open',
            m_open, create=True
    ):
        resp = yield from client.get('/api/camera_proxy/camera.config_test')

    assert resp.status == 200
    body = yield from resp.text()
    assert body == 'hello'
コード例 #3
0
async def test_get_entity(hass, client):
    """Test get entry."""
    mock_registry(hass, {
        'test_domain.name': RegistryEntry(
            entity_id='test_domain.name',
            unique_id='1234',
            platform='test_platform',
            name='Hello World'
        ),
        'test_domain.no_name': RegistryEntry(
            entity_id='test_domain.no_name',
            unique_id='6789',
            platform='test_platform',
        ),
    })

    resp = await client.get(
        '/api/config/entity_registry/test_domain.name')
    assert resp.status == 200
    data = await resp.json()
    assert data == {
        'entity_id': 'test_domain.name',
        'name': 'Hello World'
    }

    resp = await client.get(
        '/api/config/entity_registry/test_domain.no_name')
    assert resp.status == 200
    data = await resp.json()
    assert data == {
        'entity_id': 'test_domain.no_name',
        'name': None
    }
コード例 #4
0
async def test_update_file_path(hass):
    """Test update_file_path service."""
    # Setup platform

    mock_registry(hass)

    with mock.patch('os.path.isfile', mock.Mock(return_value=True)), \
            mock.patch('os.access', mock.Mock(return_value=True)):
        await async_setup_component(hass, 'camera', {
            'camera': {
                'platform': 'local_file',
                'file_path': 'mock/path.jpg'
            }
        })

        # Fetch state and check motion detection attribute
        state = hass.states.get('camera.local_file')
        assert state.attributes.get('friendly_name') == 'Local File'
        assert state.attributes.get('file_path') == 'mock/path.jpg'

        service_data = {
            "entity_id": 'camera.local_file',
            "file_path": 'new/path.jpg'
        }

        await hass.services.async_call(DOMAIN,
                                       SERVICE_UPDATE_FILE_PATH,
                                       service_data)
        await hass.async_block_till_done()

        state = hass.states.get('camera.local_file')
        assert state.attributes.get('file_path') == 'new/path.jpg'
コード例 #5
0
async def test_update_entity_no_changes(hass, client):
    """Test get entry."""
    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'] == {
        'entity_id': 'test_domain.world',
        'name': 'name of entity'
    }

    state = hass.states.get('test_domain.world')
    assert state.name == 'name of entity'
コード例 #6
0
def test_registry_respect_entity_namespace(hass):
    """Test that the registry respects entity namespace."""
    mock_registry(hass)
    platform = MockEntityPlatform(hass, entity_namespace='ns')
    entity = MockEntity(unique_id='1234', name='Device Name')
    yield from platform.async_add_entities([entity])
    assert entity.entity_id == 'test_domain.ns_device_name'
コード例 #7
0
async def test_update_entity_id(hass, client):
    """Test update entity id."""
    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',
        )
    })
    platform = MockEntityPlatform(hass)
    entity = MockEntity(unique_id='1234')
    await platform.async_add_entities([entity])

    assert hass.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_id': 'test_domain.planet',
        'name': None
    }

    assert hass.states.get('test_domain.world') is None
    assert hass.states.get('test_domain.planet') is not None
コード例 #8
0
async def test_extract_entity_ids_from_area(hass):
    """Test extract_entity_ids method with areas."""
    hass.states.async_set('light.Bowl', STATE_ON)
    hass.states.async_set('light.Ceiling', STATE_OFF)
    hass.states.async_set('light.Kitchen', STATE_OFF)

    device_in_area = dev_reg.DeviceEntry(area_id='test-area')
    device_no_area = dev_reg.DeviceEntry()
    device_diff_area = dev_reg.DeviceEntry(area_id='diff-area')

    mock_device_registry(hass, {
        device_in_area.id: device_in_area,
        device_no_area.id: device_no_area,
        device_diff_area.id: device_diff_area,
    })

    entity_in_area = ent_reg.RegistryEntry(
        entity_id='light.in_area',
        unique_id='in-area-id',
        platform='test',
        device_id=device_in_area.id,
    )
    entity_no_area = ent_reg.RegistryEntry(
        entity_id='light.no_area',
        unique_id='no-area-id',
        platform='test',
        device_id=device_no_area.id,
    )
    entity_diff_area = ent_reg.RegistryEntry(
        entity_id='light.diff_area',
        unique_id='diff-area-id',
        platform='test',
        device_id=device_diff_area.id,
    )
    mock_registry(hass, {
        entity_in_area.entity_id: entity_in_area,
        entity_no_area.entity_id: entity_no_area,
        entity_diff_area.entity_id: entity_diff_area,
    })

    call = ha.ServiceCall('light', 'turn_on',
                          {'area_id': 'test-area'})

    assert {'light.in_area'} == \
        await service.async_extract_entity_ids(hass, call)

    call = ha.ServiceCall('light', 'turn_on',
                          {'area_id': ['test-area', 'diff-area']})

    assert {'light.in_area', 'light.diff_area'} == \
        await service.async_extract_entity_ids(hass, call)
コード例 #9
0
async def test_entity_registry_updates_entity_id(hass):
    """Test that updates on the entity registry update platform entities."""
    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'
        )
    })
    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'

    registry.async_update_entity('test_domain.world',
                                 new_entity_id='test_domain.planet')
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    assert hass.states.get('test_domain.world') is None
    assert hass.states.get('test_domain.planet') is not None
コード例 #10
0
async def test_setup_entry(hass):
    """Test we can setup an entry."""
    registry = mock_registry(hass)

    async def async_setup_entry(hass, config_entry, async_add_devices):
        """Mock setup entry method."""
        async_add_devices([
            MockEntity(name='test1', unique_id='unique')
        ])
        return True

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

    assert await entity_platform.async_setup_entry(config_entry)
    await hass.async_block_till_done()
    full_name = '{}.{}'.format(entity_platform.domain, config_entry.domain)
    assert full_name in hass.config.components
    assert len(hass.states.async_entity_ids()) == 1
    assert len(registry.entities) == 1
    assert registry.entities['test_domain.test1'].config_entry_id == \
        'super-mock-id'
コード例 #11
0
def test_entities_device_id_boolean(hass):
    """Test entity ID policy applying control on device id."""
    entity_registry = mock_registry(hass, {
        'test_domain.allowed': RegistryEntry(
            entity_id='test_domain.allowed',
            unique_id='1234',
            platform='test_platform',
            device_id='mock-allowed-dev-id'
        ),
        'test_domain.not_allowed': RegistryEntry(
            entity_id='test_domain.not_allowed',
            unique_id='5678',
            platform='test_platform',
            device_id='mock-not-allowed-dev-id'
        ),
    })
    device_registry = mock_device_registry(hass)

    policy = {
        'device_ids': {
            'mock-allowed-dev-id': {
                'read': True,
            }
        }
    }
    ENTITY_POLICY_SCHEMA(policy)
    compiled = compile_entities(policy, PermissionLookup(
        entity_registry, device_registry
    ))
    assert compiled('test_domain.allowed', 'read') is True
    assert compiled('test_domain.allowed', 'control') is False
    assert compiled('test_domain.not_allowed', 'read') is False
    assert compiled('test_domain.not_allowed', 'control') is False
コード例 #12
0
def test_entities_areas_area_true(hass):
    """Test entity ID policy for areas with specific area."""
    entity_registry = mock_registry(hass, {
        'light.kitchen': RegistryEntry(
            entity_id='light.kitchen',
            unique_id='1234',
            platform='test_platform',
            device_id='mock-dev-id'
        ),
    })
    device_registry = mock_device_registry(hass, {
        'mock-dev-id': DeviceEntry(
            id='mock-dev-id',
            area_id='mock-area-id'
        )
    })

    policy = {
        'area_ids': {
            'mock-area-id': {
                'read': True,
                'control': True,
            }
        }
    }
    ENTITY_POLICY_SCHEMA(policy)
    compiled = compile_entities(policy, PermissionLookup(
        entity_registry, device_registry
    ))
    assert compiled('light.kitchen', 'read') is True
    assert compiled('light.kitchen', 'control') is True
    assert compiled('light.kitchen', 'edit') is False
    assert compiled('switch.kitchen', 'read') is False
コード例 #13
0
ファイル: test_lock.py プロジェクト: Martwall/home-assistant
async def test_entity_id_update(hass, mqtt_mock):
    """Test MQTT subscriptions are managed when entity_id is updated."""
    registry = mock_registry(hass, {})
    mock_mqtt = await async_mock_mqtt_component(hass)
    assert await async_setup_component(hass, lock.DOMAIN, {
        lock.DOMAIN: [{
            'platform': 'mqtt',
            'name': 'beer',
            'state_topic': 'test-topic',
            'command_topic': 'test-topic',
            'availability_topic': 'avty-topic',
            'unique_id': 'TOTALLY_UNIQUE'
        }]
    })

    state = hass.states.get('lock.beer')
    assert state is not None
    assert mock_mqtt.async_subscribe.call_count == 2
    mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
    mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
    mock_mqtt.async_subscribe.reset_mock()

    registry.async_update_entity('lock.beer', new_entity_id='lock.milk')
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    state = hass.states.get('lock.beer')
    assert state is None

    state = hass.states.get('lock.milk')
    assert state is not None
    assert mock_mqtt.async_subscribe.call_count == 2
    mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
    mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
コード例 #14
0
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() == []
コード例 #15
0
def registries(hass):
    """Registry mock setup."""
    from types import SimpleNamespace
    ret = SimpleNamespace()
    ret.entity = mock_registry(hass)
    ret.device = mock_device_registry(hass)
    ret.area = mock_area_registry(hass)
    return ret
コード例 #16
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'
コード例 #17
0
async def test_list_entities(hass, client):
    """Test list entries."""
    entities = OrderedDict()
    entities['test_domain.name'] = RegistryEntry(
        entity_id='test_domain.name',
        unique_id='1234',
        platform='test_platform',
        name='Hello World'
    )
    entities['test_domain.no_name'] = RegistryEntry(
        entity_id='test_domain.no_name',
        unique_id='6789',
        platform='test_platform',
    )

    mock_registry(hass, entities)

    await client.send_json({
        'id': 5,
        'type': 'config/entity_registry/list',
    })
    msg = await client.receive_json()

    assert msg['result'] == [
        {
            'config_entry_id': None,
            'device_id': None,
            'disabled_by': None,
            'entity_id': 'test_domain.name',
            'name': 'Hello World',
            'platform': 'test_platform',
        },
        {
            'config_entry_id': None,
            'device_id': None,
            'disabled_by': None,
            'entity_id': 'test_domain.no_name',
            'name': None,
            'platform': 'test_platform',
        }
    ]
コード例 #18
0
async def test_get_entity(hass, client):
    """Test get entry."""
    mock_registry(hass, {
        'test_domain.name': RegistryEntry(
            entity_id='test_domain.name',
            unique_id='1234',
            platform='test_platform',
            name='Hello World'
        ),
        'test_domain.no_name': RegistryEntry(
            entity_id='test_domain.no_name',
            unique_id='6789',
            platform='test_platform',
        ),
    })

    await client.send_json({
        'id': 5,
        'type': 'config/entity_registry/get',
        'entity_id': 'test_domain.name',
    })
    msg = await client.receive_json()

    assert msg['result'] == {
        'entity_id': 'test_domain.name',
        'name': 'Hello World'
    }

    await client.send_json({
        'id': 6,
        'type': 'config/entity_registry/get',
        'entity_id': 'test_domain.no_name',
    })
    msg = await client.receive_json()

    assert msg['result'] == {
        'entity_id': 'test_domain.no_name',
        'name': None
    }
コード例 #19
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()
コード例 #20
0
def test_name_which_conflict_with_registered(hass):
    """Test not generating conflicting entity ID based on name."""
    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')

    yield from component.async_add_entities([
        MockEntity(name='world')])

    assert 'test_domain.world_2' in hass.states.async_entity_ids()
コード例 #21
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
コード例 #22
0
    def setUp(self):
        """Initialize values for this testcase class."""
        self.hass = get_test_home_assistant()
        self.hass.start()
        self.registry = mock_registry(self.hass)

        setup_component(self.hass, 'zwave', {'zwave': {}})
        self.hass.block_till_done()

        self.node = MockNode()
        self.mock_schema = {
            const.DISC_COMPONENT: 'mock_component',
            const.DISC_VALUES: {
                const.DISC_PRIMARY: {
                    const.DISC_COMMAND_CLASS: ['mock_primary_class'],
                },
                'secondary': {
                    const.DISC_COMMAND_CLASS: ['mock_secondary_class'],
                },
                'optional': {
                    const.DISC_COMMAND_CLASS: ['mock_optional_class'],
                    const.DISC_OPTIONAL: True,
                }}}
        self.primary = MockValue(
            command_class='mock_primary_class', node=self.node, value_id=1000)
        self.secondary = MockValue(
            command_class='mock_secondary_class', node=self.node)
        self.duplicate_secondary = MockValue(
            command_class='mock_secondary_class', node=self.node)
        self.optional = MockValue(
            command_class='mock_optional_class', node=self.node)
        self.no_match_value = MockValue(
            command_class='mock_bad_class', node=self.node)

        self.entity_id = 'mock_component.mock_node_mock_value'
        self.zwave_config = {'zwave': {}}
        self.device_config = {self.entity_id: {}}
コード例 #23
0
async def test_alarm_control_panel(hass, canary) -> None:
    """Test the creation and values of the alarm_control_panel for Canary."""
    await async_setup_component(hass, "persistent_notification", {})

    registry = mock_registry(hass)
    online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")

    mocked_location = mock_location(
        location_id=100,
        name="Home",
        is_celsius=True,
        is_private=False,
        mode=mock_mode(7, "standby"),
        devices=[online_device_at_home],
    )

    instance = canary.return_value
    instance.get_locations.return_value = [mocked_location]

    config = {
        DOMAIN: {
            "username": "******",
            "password": "******"
        }
    }
    with patch("homeassistant.components.canary.PLATFORMS",
               ["alarm_control_panel"]):
        assert await async_setup_component(hass, DOMAIN, config)
        await hass.async_block_till_done()

    entity_id = "alarm_control_panel.home"
    entity_entry = registry.async_get(entity_id)
    assert entity_entry
    assert entity_entry.unique_id == "100"

    state = hass.states.get(entity_id)
    assert state
    assert state.state == STATE_UNKNOWN
    assert not state.attributes["private"]

    # test private system
    type(mocked_location).is_private = PropertyMock(return_value=True)

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

    state = hass.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_DISARMED
    assert state.attributes["private"]

    type(mocked_location).is_private = PropertyMock(return_value=False)

    # test armed home
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(4, LOCATION_MODE_HOME))

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

    state = hass.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_HOME

    # test armed away
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(5, LOCATION_MODE_AWAY))

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

    state = hass.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_AWAY

    # test armed night
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(6, LOCATION_MODE_NIGHT))

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

    state = hass.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_NIGHT
コード例 #24
0
def entity_reg(opp: OpenPeerPower) -> entity_registry.EntityRegistry:
    """Return an empty, loaded, registry."""
    return mock_registry(opp)
コード例 #25
0
ファイル: test_file.py プロジェクト: MoshonkaKita/Golovastik
 def setup_method(self, method):
     """Set up things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     # Patch out 'is_allowed_path' as the mock files aren't allowed
     self.hass.config.is_allowed_path = Mock(return_value=True)
     mock_registry(self.hass)
コード例 #26
0
async def test_multi_sensor_migration(
        hass, caplog, legacy_patchable_time,
        pvpc_aioclient_mock: AiohttpClientMocker):
    """Test tariff migration when there are >1 old sensors."""
    entity_reg = mock_registry(hass)
    hass.config.time_zone = dt_util.get_time_zone("Europe/Madrid")
    uid_1 = "discrimination"
    uid_2 = "normal"
    old_conf_1 = {CONF_NAME: "test_pvpc_1", ATTR_TARIFF: uid_1}
    old_conf_2 = {CONF_NAME: "test_pvpc_2", ATTR_TARIFF: uid_2}

    config_entry_1 = MockConfigEntry(domain=DOMAIN,
                                     data=old_conf_1,
                                     unique_id=uid_1)
    config_entry_1.add_to_hass(hass)
    entity1 = entity_reg.async_get_or_create(
        domain="sensor",
        platform=DOMAIN,
        unique_id=uid_1,
        config_entry=config_entry_1,
        suggested_object_id="test_pvpc_1",
    )

    config_entry_2 = MockConfigEntry(domain=DOMAIN,
                                     data=old_conf_2,
                                     unique_id=uid_2)
    config_entry_2.add_to_hass(hass)
    entity2 = entity_reg.async_get_or_create(
        domain="sensor",
        platform=DOMAIN,
        unique_id=uid_2,
        config_entry=config_entry_2,
        suggested_object_id="test_pvpc_2",
    )

    assert len(hass.config_entries.async_entries(DOMAIN)) == 2
    assert len(entity_reg.entities) == 2

    mock_data = {"return_time": datetime(2021, 6, 1, 21, tzinfo=date_util.UTC)}

    def mock_now():
        return mock_data["return_time"]

    caplog.clear()
    with caplog.at_level(logging.WARNING):
        with patch("homeassistant.util.dt.utcnow", new=mock_now):
            assert await hass.config_entries.async_setup(
                config_entry_1.entry_id)
            assert len(caplog.messages) == 2

            # check migration with removal of extra sensors
            assert len(entity_reg.entities) == 1
            assert entity1.entity_id in entity_reg.entities
            assert entity2.entity_id not in entity_reg.entities

            current_entries = hass.config_entries.async_entries(DOMAIN)
            assert len(current_entries) == 1
            migrated_entry = current_entries[0]
            assert migrated_entry.version == 1
            assert migrated_entry.data[ATTR_POWER] == migrated_entry.data[
                ATTR_POWER_P3]
            assert migrated_entry.data[ATTR_TARIFF] == TARIFFS[0]

            await hass.async_block_till_done()
            assert pvpc_aioclient_mock.call_count == 2

            # check state and availability
            state = hass.states.get("sensor.test_pvpc_1")
            check_valid_state(state, tariff=TARIFFS[0], value=0.1565)

            mock_data["return_time"] += timedelta(minutes=60)
            async_fire_time_changed(hass, mock_data["return_time"])
            await list(hass.data[DOMAIN].values())[0].async_refresh()
            await hass.async_block_till_done()
            state = hass.states.get("sensor.test_pvpc_1")
            check_valid_state(state, tariff=TARIFFS[0], value="unavailable")
            assert pvpc_aioclient_mock.call_count == 3
コード例 #27
0
def registry(hass):
    """Return an empty, loaded, registry."""
    return mock_registry(hass)
コード例 #28
0
async def test_google_config_expose_entity_prefs(hass, mock_conf, cloud_prefs):
    """Test Google config should expose using prefs."""
    entity_registry = mock_registry(hass)

    entity_entry1 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_config_id",
        suggested_object_id="config_light",
        entity_category=EntityCategory.CONFIG,
    )
    entity_entry2 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_diagnostic_id",
        suggested_object_id="diagnostic_light",
        entity_category=EntityCategory.DIAGNOSTIC,
    )
    entity_entry3 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_system_id",
        suggested_object_id="system_light",
        entity_category=EntityCategory.SYSTEM,
    )
    entity_entry4 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_hidden_integration_id",
        suggested_object_id="hidden_integration_light",
        hidden_by=er.RegistryEntryHider.INTEGRATION,
    )
    entity_entry5 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_hidden_user_id",
        suggested_object_id="hidden_user_light",
        hidden_by=er.RegistryEntryHider.USER,
    )

    entity_conf = {"should_expose": False}
    await cloud_prefs.async_update(
        google_entity_configs={"light.kitchen": entity_conf},
        google_default_expose=["light"],
    )

    state = State("light.kitchen", "on")
    state_config = State(entity_entry1.entity_id, "on")
    state_diagnostic = State(entity_entry2.entity_id, "on")
    state_system = State(entity_entry3.entity_id, "on")
    state_hidden_integration = State(entity_entry4.entity_id, "on")
    state_hidden_user = State(entity_entry5.entity_id, "on")

    assert not mock_conf.should_expose(state)
    assert not mock_conf.should_expose(state_config)
    assert not mock_conf.should_expose(state_diagnostic)
    assert not mock_conf.should_expose(state_system)
    assert not mock_conf.should_expose(state_hidden_integration)
    assert not mock_conf.should_expose(state_hidden_user)

    entity_conf["should_expose"] = True
    assert mock_conf.should_expose(state)
    # categorized and hidden entities should not be exposed
    assert not mock_conf.should_expose(state_config)
    assert not mock_conf.should_expose(state_diagnostic)
    assert not mock_conf.should_expose(state_system)
    assert not mock_conf.should_expose(state_hidden_integration)
    assert not mock_conf.should_expose(state_hidden_user)

    entity_conf["should_expose"] = None
    assert mock_conf.should_expose(state)
    # categorized and hidden entities should not be exposed
    assert not mock_conf.should_expose(state_config)
    assert not mock_conf.should_expose(state_diagnostic)
    assert not mock_conf.should_expose(state_system)
    assert not mock_conf.should_expose(state_hidden_integration)
    assert not mock_conf.should_expose(state_hidden_user)

    await cloud_prefs.async_update(google_default_expose=["sensor"], )
    assert not mock_conf.should_expose(state)
コード例 #29
0
 def setup_method(self, method):
     """Set up things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     # Patch out 'is_allowed_path' as the mock files aren't allowed
     self.hass.config.is_allowed_path = Mock(return_value=True)
     mock_registry(self.hass)
コード例 #30
0
def entity_reg(hass: HomeAssistant) -> EntityRegistry:
    """Return an empty, loaded, registry."""
    return mock_registry(hass)
コード例 #31
0
ファイル: test_entity.py プロジェクト: jcgoette/core
async def test_get_supported_features_entity_registry(hass):
    """Test get_supported_features falls back to entity registry."""
    entity_reg = mock_registry(hass)
    entity_id = entity_reg.async_get_or_create(
        "hello", "world", "5678", supported_features=456).entity_id
    assert entity.get_supported_features(hass, entity_id) == 456
コード例 #32
0
async def test_update_entity(hass, client):
    """Test updating entity."""
    registry = 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",
                icon="icon: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"
    assert state.attributes["icon"] == "icon:before update"

    # UPDATE NAME & ICON
    await client.send_json({
        "id": 6,
        "type": "config/entity_registry/update",
        "entity_id": "test_domain.world",
        "name": "after update",
        "icon": "icon:after update",
    })

    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": "after update",
        "icon": "icon:after update",
        "original_name": None,
        "original_icon": None,
        "capabilities": None,
        "unique_id": "1234",
    }

    state = hass.states.get("test_domain.world")
    assert state.name == "after update"
    assert state.attributes["icon"] == "icon:after update"

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

    msg = await client.receive_json()

    assert hass.states.get("test_domain.world") is None
    assert registry.entities["test_domain.world"].disabled_by == "user"

    # 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 msg["result"] == {
        "config_entry_id": None,
        "device_id": None,
        "disabled_by": None,
        "platform": "test_platform",
        "entity_id": "test_domain.world",
        "name": "after update",
        "icon": "icon:after update",
        "original_name": None,
        "original_icon": None,
        "capabilities": None,
        "unique_id": "1234",
    }
コード例 #33
0
async def test_get_entity(hass, client):
    """Test get entry."""
    mock_registry(
        hass,
        {
            "test_domain.name":
            RegistryEntry(
                entity_id="test_domain.name",
                unique_id="1234",
                platform="test_platform",
                name="Hello World",
            ),
            "test_domain.no_name":
            RegistryEntry(
                entity_id="test_domain.no_name",
                unique_id="6789",
                platform="test_platform",
            ),
        },
    )

    await client.send_json({
        "id": 5,
        "type": "config/entity_registry/get",
        "entity_id": "test_domain.name"
    })
    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.name",
        "name": "Hello World",
        "icon": None,
        "original_name": None,
        "original_icon": None,
        "capabilities": None,
        "unique_id": "1234",
    }

    await client.send_json({
        "id": 6,
        "type": "config/entity_registry/get",
        "entity_id": "test_domain.no_name",
    })
    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.no_name",
        "name": None,
        "icon": None,
        "original_name": None,
        "original_icon": None,
        "capabilities": None,
        "unique_id": "6789",
    }
コード例 #34
0
ファイル: test_config_entry.py プロジェクト: rikroe/core
async def test_connected_device_registered(hass):
    """Test dispatch on connected device being registered."""

    registry = mock_registry(hass)
    dispatches = []

    @callback
    def _save_dispatch(msg):
        dispatches.append(msg)

    unsub = async_dispatcher_connect(hass, ce.CONNECTED_DEVICE_REGISTERED,
                                     _save_dispatch)

    class MockScannerEntity(ce.ScannerEntity):
        """Mock a scanner entity."""
        @property
        def ip_address(self) -> str:
            return "5.4.3.2"

        @property
        def unique_id(self) -> str:
            return self.mac_address

    class MockDisconnectedScannerEntity(MockScannerEntity):
        """Mock a disconnected scanner entity."""
        @property
        def mac_address(self) -> str:
            return "aa:bb:cc:dd:ee:ff"

        @property
        def is_connected(self) -> bool:
            return True

        @property
        def hostname(self) -> str:
            return "connected"

    class MockConnectedScannerEntity(MockScannerEntity):
        """Mock a disconnected scanner entity."""
        @property
        def mac_address(self) -> str:
            return "aa:bb:cc:dd:ee:00"

        @property
        def is_connected(self) -> bool:
            return False

        @property
        def hostname(self) -> str:
            return "disconnected"

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

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

    assert await entity_platform.async_setup_entry(config_entry)
    await hass.async_block_till_done()
    full_name = f"{entity_platform.domain}.{config_entry.domain}"
    assert full_name in hass.config.components
    assert len(hass.states.async_entity_ids()) == 0  # should be disabled
    assert len(registry.entities) == 2
    assert (registry.entities["test_domain.test_aa_bb_cc_dd_ee_ff"].
            config_entry_id == "super-mock-id")
    unsub()
    assert dispatches == [{
        "ip": "5.4.3.2",
        "mac": "aa:bb:cc:dd:ee:ff",
        "host_name": "connected"
    }]
コード例 #35
0
async def test_alexa_config_expose_entity_prefs(hass, cloud_prefs, cloud_stub):
    """Test Alexa config should expose using prefs."""
    entity_registry = mock_registry(hass)

    entity_entry1 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_config_id",
        suggested_object_id="config_light",
        entity_category=EntityCategory.CONFIG,
    )
    entity_entry2 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_diagnostic_id",
        suggested_object_id="diagnostic_light",
        entity_category=EntityCategory.DIAGNOSTIC,
    )
    entity_entry3 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_hidden_integration_id",
        suggested_object_id="hidden_integration_light",
        hidden_by=er.RegistryEntryHider.INTEGRATION,
    )
    entity_entry4 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_hidden_user_id",
        suggested_object_id="hidden_user_light",
        hidden_by=er.RegistryEntryHider.USER,
    )

    entity_conf = {"should_expose": False}
    await cloud_prefs.async_update(
        alexa_entity_configs={"light.kitchen": entity_conf},
        alexa_default_expose=["light"],
        alexa_enabled=True,
        alexa_report_state=False,
    )
    conf = alexa_config.CloudAlexaConfig(hass, ALEXA_SCHEMA({}),
                                         "mock-user-id", cloud_prefs,
                                         cloud_stub)
    await conf.async_initialize()

    assert not conf.should_expose("light.kitchen")
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)
    assert not conf.should_expose(entity_entry4.entity_id)

    entity_conf["should_expose"] = True
    assert conf.should_expose("light.kitchen")
    # categorized and hidden entities should not be exposed
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)
    assert not conf.should_expose(entity_entry4.entity_id)

    entity_conf["should_expose"] = None
    assert conf.should_expose("light.kitchen")
    # categorized and hidden entities should not be exposed
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)
    assert not conf.should_expose(entity_entry4.entity_id)

    assert "alexa" not in hass.config.components
    await cloud_prefs.async_update(alexa_default_expose=["sensor"], )
    await hass.async_block_till_done()
    assert "alexa" in hass.config.components
    assert not conf.should_expose("light.kitchen")
コード例 #36
0
 def setup_method(self, method):
     """Set up things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     mock_registry(self.hass)
コード例 #37
0
async def test_alexa_config_expose_entity_prefs(hass, cloud_prefs, cloud_stub):
    """Test Alexa config should expose using prefs."""
    entity_registry = mock_registry(hass)

    entity_entry1 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_config_id",
        suggested_object_id="config_light",
        entity_category="config",
    )
    entity_entry2 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_diagnostic_id",
        suggested_object_id="diagnostic_light",
        entity_category="diagnostic",
    )
    entity_entry3 = entity_registry.async_get_or_create(
        "light",
        "test",
        "light_system_id",
        suggested_object_id="system_light",
        entity_category="system",
    )

    entity_conf = {"should_expose": False}
    await cloud_prefs.async_update(
        alexa_entity_configs={"light.kitchen": entity_conf},
        alexa_default_expose=["light"],
        alexa_enabled=True,
        alexa_report_state=False,
    )
    conf = alexa_config.CloudAlexaConfig(
        hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
    )
    await conf.async_initialize()

    assert not conf.should_expose("light.kitchen")
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)

    entity_conf["should_expose"] = True
    assert conf.should_expose("light.kitchen")
    # config and diagnostic entities should not be exposed
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)

    entity_conf["should_expose"] = None
    assert conf.should_expose("light.kitchen")
    # config and diagnostic entities should not be exposed
    assert not conf.should_expose(entity_entry1.entity_id)
    assert not conf.should_expose(entity_entry2.entity_id)
    assert not conf.should_expose(entity_entry3.entity_id)

    assert "alexa" not in hass.config.components
    await cloud_prefs.async_update(
        alexa_default_expose=["sensor"],
    )
    await hass.async_block_till_done()
    assert "alexa" in hass.config.components
    assert not conf.should_expose("light.kitchen")
コード例 #38
0
def entity_reg(hass):
    """Return an empty, loaded, registry."""
    return mock_registry(hass)
コード例 #39
0
async def test_sync_request(hass_fixture, assistant_client, auth_header):
    """Test a sync request."""

    entity_registry = mock_registry(hass_fixture)

    entity_entry1 = entity_registry.async_get_or_create(
        "switch",
        "test",
        "switch_config_id",
        suggested_object_id="config_switch",
        entity_category="config",
    )
    entity_entry2 = entity_registry.async_get_or_create(
        "switch",
        "test",
        "switch_diagnostic_id",
        suggested_object_id="diagnostic_switch",
        entity_category="diagnostic",
    )
    entity_entry3 = entity_registry.async_get_or_create(
        "switch",
        "test",
        "switch_system_id",
        suggested_object_id="system_switch",
        entity_category="system",
    )
    entity_entry4 = entity_registry.async_get_or_create(
        "switch",
        "test",
        "switch_hidden_integration_id",
        suggested_object_id="hidden_integration_switch",
        hidden_by=er.RegistryEntryHider.INTEGRATION,
    )
    entity_entry5 = entity_registry.async_get_or_create(
        "switch",
        "test",
        "switch_hidden_user_id",
        suggested_object_id="hidden_user_switch",
        hidden_by=er.RegistryEntryHider.USER,
    )

    # These should not show up in the sync request
    hass_fixture.states.async_set(entity_entry1.entity_id, "on")
    hass_fixture.states.async_set(entity_entry2.entity_id, "something_else")
    hass_fixture.states.async_set(entity_entry3.entity_id, "blah")
    hass_fixture.states.async_set(entity_entry4.entity_id, "foo")
    hass_fixture.states.async_set(entity_entry5.entity_id, "bar")

    reqid = "5711642932632160983"
    data = {"requestId": reqid, "inputs": [{"intent": "action.devices.SYNC"}]}
    result = await assistant_client.post(
        ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
        data=json.dumps(data),
        headers=auth_header,
    )
    assert result.status == HTTPStatus.OK
    body = await result.json()
    assert body.get("requestId") == reqid
    devices = body["payload"]["devices"]
    assert sorted(dev["id"]
                  for dev in devices) == sorted(dev["id"]
                                                for dev in DEMO_DEVICES)

    for dev in devices:
        assert dev["id"] not in CLOUD_NEVER_EXPOSED_ENTITIES

    for dev, demo in zip(
            sorted(devices, key=lambda d: d["id"]),
            sorted(DEMO_DEVICES, key=lambda d: d["id"]),
    ):
        assert dev["name"] == demo["name"]
        assert set(dev["traits"]) == set(demo["traits"])
        assert dev["type"] == demo["type"]
コード例 #40
0
def entity_reg_fixture(opp):
    """Return an empty, loaded, registry."""
    return mock_registry(opp)
コード例 #41
0
async def test_owserver_switch(owproxy, hass, device_id):
    """Test for 1-Wire switch.

    This test forces all entities to be enabled.
    """
    await async_setup_component(hass, "persistent_notification", {})
    entity_registry = mock_registry(hass)

    mock_device_sensor = MOCK_DEVICE_SENSORS[device_id]

    device_family = device_id[0:2]
    dir_return_value = [f"/{device_id}/"]
    read_side_effect = [device_family.encode()]
    if "inject_reads" in mock_device_sensor:
        read_side_effect += mock_device_sensor["inject_reads"]

    expected_sensors = mock_device_sensor[SWITCH_DOMAIN]
    for expected_sensor in expected_sensors:
        read_side_effect.append(expected_sensor["injected_value"])

    # Ensure enough read side effect
    read_side_effect.extend([ProtocolError("Missing injected value")] * 10)
    owproxy.return_value.dir.return_value = dir_return_value
    owproxy.return_value.read.side_effect = read_side_effect

    # Force enable switches
    patch_device_switches = copy.deepcopy(DEVICE_SWITCHES)
    for item in patch_device_switches[device_family]:
        item["default_disabled"] = False

    with patch("homeassistant.components.onewire.SUPPORTED_PLATFORMS",
               [SWITCH_DOMAIN]), patch.dict(
                   "homeassistant.components.onewire.switch.DEVICE_SWITCHES",
                   patch_device_switches):
        await setup_onewire_patched_owserver_integration(hass)
        await hass.async_block_till_done()

    assert len(entity_registry.entities) == len(expected_sensors)

    for expected_sensor in expected_sensors:
        entity_id = expected_sensor["entity_id"]
        registry_entry = entity_registry.entities.get(entity_id)
        assert registry_entry is not None
        state = hass.states.get(entity_id)
        assert state.state == expected_sensor["result"]

        if state.state == STATE_ON:
            owproxy.return_value.read.side_effect = [b"         0"]
            expected_sensor["result"] = STATE_OFF
        elif state.state == STATE_OFF:
            owproxy.return_value.read.side_effect = [b"         1"]
            expected_sensor["result"] = STATE_ON

        await hass.services.async_call(
            SWITCH_DOMAIN,
            SERVICE_TOGGLE,
            {ATTR_ENTITY_ID: entity_id},
            blocking=True,
        )
        await hass.async_block_till_done()

        state = hass.states.get(entity_id)
        assert state.state == expected_sensor["result"]
        assert state.attributes["device_file"] == expected_sensor.get(
            "device_file", registry_entry.unique_id)
コード例 #42
0
def test_rename_entity_collision(hass_recorder, caplog):
    """Test statistics is migrated when entity_id is changed."""
    hass = hass_recorder()
    setup_component(hass, "sensor", {})

    entity_reg = mock_registry(hass)

    @callback
    def add_entry():
        reg_entry = entity_reg.async_get_or_create(
            "sensor",
            "test",
            "unique_0000",
            suggested_object_id="test1",
        )
        assert reg_entry.entity_id == "sensor.test1"

    hass.add_job(add_entry)
    hass.block_till_done()

    zero, four, states = record_states(hass)
    hist = history.get_significant_states(hass, zero, four)
    assert dict(states) == dict(hist)

    for kwargs in ({}, {"statistic_ids": ["sensor.test1"]}):
        stats = statistics_during_period(hass,
                                         zero,
                                         period="5minute",
                                         **kwargs)
        assert stats == {}
    stats = get_last_short_term_statistics(hass, 0, "sensor.test1", True)
    assert stats == {}

    do_adhoc_statistics(hass, start=zero)
    wait_recording_done(hass)
    expected_1 = {
        "statistic_id": "sensor.test1",
        "start": process_timestamp_to_utc_isoformat(zero),
        "end": process_timestamp_to_utc_isoformat(zero + timedelta(minutes=5)),
        "mean": approx(14.915254237288135),
        "min": approx(10.0),
        "max": approx(20.0),
        "last_reset": None,
        "state": None,
        "sum": None,
    }
    expected_stats1 = [
        {
            **expected_1, "statistic_id": "sensor.test1"
        },
    ]
    expected_stats2 = [
        {
            **expected_1, "statistic_id": "sensor.test2"
        },
    ]

    stats = statistics_during_period(hass, zero, period="5minute")
    assert stats == {
        "sensor.test1": expected_stats1,
        "sensor.test2": expected_stats2
    }

    # Insert metadata for sensor.test99
    metadata_1 = {
        "has_mean": True,
        "has_sum": False,
        "name": "Total imported energy",
        "source": "test",
        "statistic_id": "sensor.test99",
        "unit_of_measurement": "kWh",
    }

    with session_scope(hass=hass) as session:
        session.add(recorder.models.StatisticsMeta.from_meta(metadata_1))

    # Rename entity sensor.test1 to sensor.test99
    @callback
    def rename_entry():
        entity_reg.async_update_entity("sensor.test1",
                                       new_entity_id="sensor.test99")

    hass.add_job(rename_entry)
    wait_recording_done(hass)

    # Statistics failed to migrate due to the collision
    stats = statistics_during_period(hass, zero, period="5minute")
    assert stats == {
        "sensor.test1": expected_stats1,
        "sensor.test2": expected_stats2
    }
    assert "Blocked attempt to insert duplicated statistic rows" in caplog.text
コード例 #43
0
def zwave_migration_data_fixture(opp):
    """Return mock zwave migration data."""
    zwave_source_node_device = dr.DeviceEntry(
        id=ZWAVE_SOURCE_NODE_DEVICE_ID,
        name_by_user=ZWAVE_SOURCE_NODE_DEVICE_NAME,
        area_id=ZWAVE_SOURCE_NODE_DEVICE_AREA,
    )
    zwave_source_node_entry = er.RegistryEntry(
        entity_id=ZWAVE_SOURCE_ENTITY,
        unique_id=ZWAVE_SOURCE_NODE_UNIQUE_ID,
        platform="zwave",
        name="Z-Wave Source Node",
    )
    zwave_battery_device = dr.DeviceEntry(
        id=ZWAVE_BATTERY_DEVICE_ID,
        name_by_user=ZWAVE_BATTERY_DEVICE_NAME,
        area_id=ZWAVE_BATTERY_DEVICE_AREA,
    )
    zwave_battery_entry = er.RegistryEntry(
        entity_id=ZWAVE_BATTERY_ENTITY,
        unique_id=ZWAVE_BATTERY_UNIQUE_ID,
        platform="zwave",
        name=ZWAVE_BATTERY_NAME,
        icon=ZWAVE_BATTERY_ICON,
    )
    zwave_power_device = dr.DeviceEntry(
        id=ZWAVE_POWER_DEVICE_ID,
        name_by_user=ZWAVE_POWER_DEVICE_NAME,
        area_id=ZWAVE_POWER_DEVICE_AREA,
    )
    zwave_power_entry = er.RegistryEntry(
        entity_id=ZWAVE_POWER_ENTITY,
        unique_id=ZWAVE_POWER_UNIQUE_ID,
        platform="zwave",
        name=ZWAVE_POWER_NAME,
        icon=ZWAVE_POWER_ICON,
    )
    zwave_migration_data = {
        ZWAVE_SOURCE_NODE_UNIQUE_ID: {
            "node_id": 10,
            "node_instance": 1,
            "device_id": zwave_source_node_device.id,
            "command_class": 113,
            "command_class_label": "SourceNodeId",
            "value_index": 2,
            "unique_id": ZWAVE_SOURCE_NODE_UNIQUE_ID,
            "entity_entry": zwave_source_node_entry,
        },
        ZWAVE_BATTERY_UNIQUE_ID: {
            "node_id": 36,
            "node_instance": 1,
            "device_id": zwave_battery_device.id,
            "command_class": 128,
            "command_class_label": "Battery Level",
            "value_index": 0,
            "unique_id": ZWAVE_BATTERY_UNIQUE_ID,
            "entity_entry": zwave_battery_entry,
        },
        ZWAVE_POWER_UNIQUE_ID: {
            "node_id": 32,
            "node_instance": 1,
            "device_id": zwave_power_device.id,
            "command_class": 50,
            "command_class_label": "Power",
            "value_index": 8,
            "unique_id": ZWAVE_POWER_UNIQUE_ID,
            "entity_entry": zwave_power_entry,
        },
    }

    mock_device_registry(
        opp,
        {
            zwave_source_node_device.id: zwave_source_node_device,
            zwave_battery_device.id: zwave_battery_device,
            zwave_power_device.id: zwave_power_device,
        },
    )
    mock_registry(
        opp,
        {
            ZWAVE_SOURCE_ENTITY: zwave_source_node_entry,
            ZWAVE_BATTERY_ENTITY: zwave_battery_entry,
            ZWAVE_POWER_ENTITY: zwave_power_entry,
        },
    )

    return zwave_migration_data
コード例 #44
0
def test_rename_entity(hass_recorder):
    """Test statistics is migrated when entity_id is changed."""
    hass = hass_recorder()
    setup_component(hass, "sensor", {})

    entity_reg = mock_registry(hass)

    @callback
    def add_entry():
        reg_entry = entity_reg.async_get_or_create(
            "sensor",
            "test",
            "unique_0000",
            suggested_object_id="test1",
        )
        assert reg_entry.entity_id == "sensor.test1"

    hass.add_job(add_entry)
    hass.block_till_done()

    zero, four, states = record_states(hass)
    hist = history.get_significant_states(hass, zero, four)
    assert dict(states) == dict(hist)

    for kwargs in ({}, {"statistic_ids": ["sensor.test1"]}):
        stats = statistics_during_period(hass,
                                         zero,
                                         period="5minute",
                                         **kwargs)
        assert stats == {}
    stats = get_last_short_term_statistics(hass, 0, "sensor.test1", True)
    assert stats == {}

    do_adhoc_statistics(hass, start=zero)
    wait_recording_done(hass)
    expected_1 = {
        "statistic_id": "sensor.test1",
        "start": process_timestamp_to_utc_isoformat(zero),
        "end": process_timestamp_to_utc_isoformat(zero + timedelta(minutes=5)),
        "mean": approx(14.915254237288135),
        "min": approx(10.0),
        "max": approx(20.0),
        "last_reset": None,
        "state": None,
        "sum": None,
    }
    expected_stats1 = [
        {
            **expected_1, "statistic_id": "sensor.test1"
        },
    ]
    expected_stats2 = [
        {
            **expected_1, "statistic_id": "sensor.test2"
        },
    ]
    expected_stats99 = [
        {
            **expected_1, "statistic_id": "sensor.test99"
        },
    ]

    stats = statistics_during_period(hass, zero, period="5minute")
    assert stats == {
        "sensor.test1": expected_stats1,
        "sensor.test2": expected_stats2
    }

    @callback
    def rename_entry():
        entity_reg.async_update_entity("sensor.test1",
                                       new_entity_id="sensor.test99")

    hass.add_job(rename_entry)
    wait_recording_done(hass)

    stats = statistics_during_period(hass, zero, period="5minute")
    assert stats == {
        "sensor.test99": expected_stats99,
        "sensor.test2": expected_stats2
    }
コード例 #45
0
async def test_sensors_flex(hass, canary) -> None:
    """Test the creation and values of the sensors for Canary Flex."""
    await async_setup_component(hass, "persistent_notification", {})

    registry = mock_registry(hass)
    device_registry = mock_device_registry(hass)

    online_device_at_home = mock_device(20, "Dining Room", True, "Canary Flex")

    instance = canary.return_value
    instance.get_locations.return_value = [
        mock_location(100, "Home", True, devices=[online_device_at_home]),
    ]

    instance.get_latest_readings.return_value = [
        mock_reading("battery", "70.4567"),
        mock_reading("wifi", "-57"),
    ]

    config = {
        DOMAIN: {
            "username": "******",
            "password": "******"
        }
    }
    with patch("homeassistant.components.canary.PLATFORMS", ["sensor"]):
        assert await async_setup_component(hass, DOMAIN, config)
        await hass.async_block_till_done()

    sensors = {
        "home_dining_room_battery": (
            "20_battery",
            "70.46",
            PERCENTAGE,
            DEVICE_CLASS_BATTERY,
            None,
        ),
        "home_dining_room_wifi": (
            "20_wifi",
            "-57.0",
            "dBm",
            DEVICE_CLASS_SIGNAL_STRENGTH,
            None,
        ),
    }

    for (sensor_id, data) in sensors.items():
        entity_entry = registry.async_get(f"sensor.{sensor_id}")
        assert entity_entry
        assert entity_entry.device_class == data[3]
        assert entity_entry.unique_id == data[0]
        assert entity_entry.original_icon == data[4]

        state = hass.states.get(f"sensor.{sensor_id}")
        assert state
        assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == data[2]
        assert state.state == data[1]

    device = device_registry.async_get_device({(DOMAIN, "20")}, set())
    assert device
    assert device.manufacturer == MANUFACTURER
    assert device.name == "Dining Room"
    assert device.model == "Canary Flex"
コード例 #46
0
def area_mock(hass):
    """Mock including area info."""
    hass.states.async_set("light.Bowl", STATE_ON)
    hass.states.async_set("light.Ceiling", STATE_OFF)
    hass.states.async_set("light.Kitchen", STATE_OFF)

    device_in_area = dev_reg.DeviceEntry(area_id="test-area")
    device_no_area = dev_reg.DeviceEntry(id="device-no-area-id")
    device_diff_area = dev_reg.DeviceEntry(area_id="diff-area")
    device_area_a = dev_reg.DeviceEntry(id="device-area-a-id",
                                        area_id="area-a")

    mock_device_registry(
        hass,
        {
            device_in_area.id: device_in_area,
            device_no_area.id: device_no_area,
            device_diff_area.id: device_diff_area,
            device_area_a.id: device_area_a,
        },
    )

    entity_in_own_area = ent_reg.RegistryEntry(
        entity_id="light.in_own_area",
        unique_id="in-own-area-id",
        platform="test",
        area_id="own-area",
    )
    config_entity_in_own_area = ent_reg.RegistryEntry(
        entity_id="light.config_in_own_area",
        unique_id="config-in-own-area-id",
        platform="test",
        area_id="own-area",
        entity_category=EntityCategory.CONFIG,
    )
    hidden_entity_in_own_area = ent_reg.RegistryEntry(
        entity_id="light.hidden_in_own_area",
        unique_id="hidden-in-own-area-id",
        platform="test",
        area_id="own-area",
        hidden_by=ent_reg.RegistryEntryHider.USER,
    )
    entity_in_area = ent_reg.RegistryEntry(
        entity_id="light.in_area",
        unique_id="in-area-id",
        platform="test",
        device_id=device_in_area.id,
    )
    config_entity_in_area = ent_reg.RegistryEntry(
        entity_id="light.config_in_area",
        unique_id="config-in-area-id",
        platform="test",
        device_id=device_in_area.id,
        entity_category=EntityCategory.CONFIG,
    )
    hidden_entity_in_area = ent_reg.RegistryEntry(
        entity_id="light.hidden_in_area",
        unique_id="hidden-in-area-id",
        platform="test",
        device_id=device_in_area.id,
        hidden_by=ent_reg.RegistryEntryHider.USER,
    )
    entity_in_other_area = ent_reg.RegistryEntry(
        entity_id="light.in_other_area",
        unique_id="in-area-a-id",
        platform="test",
        device_id=device_in_area.id,
        area_id="other-area",
    )
    entity_assigned_to_area = ent_reg.RegistryEntry(
        entity_id="light.assigned_to_area",
        unique_id="assigned-area-id",
        platform="test",
        device_id=device_in_area.id,
        area_id="test-area",
    )
    entity_no_area = ent_reg.RegistryEntry(
        entity_id="light.no_area",
        unique_id="no-area-id",
        platform="test",
        device_id=device_no_area.id,
    )
    config_entity_no_area = ent_reg.RegistryEntry(
        entity_id="light.config_no_area",
        unique_id="config-no-area-id",
        platform="test",
        device_id=device_no_area.id,
        entity_category=EntityCategory.CONFIG,
    )
    hidden_entity_no_area = ent_reg.RegistryEntry(
        entity_id="light.hidden_no_area",
        unique_id="hidden-no-area-id",
        platform="test",
        device_id=device_no_area.id,
        hidden_by=ent_reg.RegistryEntryHider.USER,
    )
    entity_diff_area = ent_reg.RegistryEntry(
        entity_id="light.diff_area",
        unique_id="diff-area-id",
        platform="test",
        device_id=device_diff_area.id,
    )
    entity_in_area_a = ent_reg.RegistryEntry(
        entity_id="light.in_area_a",
        unique_id="in-area-a-id",
        platform="test",
        device_id=device_area_a.id,
        area_id="area-a",
    )
    entity_in_area_b = ent_reg.RegistryEntry(
        entity_id="light.in_area_b",
        unique_id="in-area-b-id",
        platform="test",
        device_id=device_area_a.id,
        area_id="area-b",
    )
    mock_registry(
        hass,
        {
            entity_in_own_area.entity_id: entity_in_own_area,
            config_entity_in_own_area.entity_id: config_entity_in_own_area,
            hidden_entity_in_own_area.entity_id: hidden_entity_in_own_area,
            entity_in_area.entity_id: entity_in_area,
            config_entity_in_area.entity_id: config_entity_in_area,
            hidden_entity_in_area.entity_id: hidden_entity_in_area,
            entity_in_other_area.entity_id: entity_in_other_area,
            entity_assigned_to_area.entity_id: entity_assigned_to_area,
            entity_no_area.entity_id: entity_no_area,
            config_entity_no_area.entity_id: config_entity_no_area,
            hidden_entity_no_area.entity_id: hidden_entity_no_area,
            entity_diff_area.entity_id: entity_diff_area,
            entity_in_area_a.entity_id: entity_in_area_a,
            entity_in_area_b.entity_id: entity_in_area_b,
        },
    )
コード例 #47
0
async def test_sensors_pro(hass, canary) -> None:
    """Test the creation and values of the sensors for Canary Pro."""
    await async_setup_component(hass, "persistent_notification", {})

    registry = mock_registry(hass)
    device_registry = mock_device_registry(hass)

    online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")

    instance = canary.return_value
    instance.get_locations.return_value = [
        mock_location(100, "Home", True, devices=[online_device_at_home]),
    ]

    instance.get_latest_readings.return_value = [
        mock_reading("temperature", "21.12"),
        mock_reading("humidity", "50.46"),
        mock_reading("air_quality", "0.59"),
    ]

    config = {
        DOMAIN: {
            "username": "******",
            "password": "******"
        }
    }
    with patch("homeassistant.components.canary.PLATFORMS", ["sensor"]):
        assert await async_setup_component(hass, DOMAIN, config)
        await hass.async_block_till_done()

    sensors = {
        "home_dining_room_temperature": (
            "20_temperature",
            "21.12",
            TEMP_CELSIUS,
            DEVICE_CLASS_TEMPERATURE,
            None,
        ),
        "home_dining_room_humidity": (
            "20_humidity",
            "50.46",
            PERCENTAGE,
            DEVICE_CLASS_HUMIDITY,
            None,
        ),
        "home_dining_room_air_quality": (
            "20_air_quality",
            "0.59",
            None,
            None,
            "mdi:weather-windy",
        ),
    }

    for (sensor_id, data) in sensors.items():
        entity_entry = registry.async_get(f"sensor.{sensor_id}")
        assert entity_entry
        assert entity_entry.device_class == data[3]
        assert entity_entry.unique_id == data[0]
        assert entity_entry.original_icon == data[4]

        state = hass.states.get(f"sensor.{sensor_id}")
        assert state
        assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == data[2]
        assert state.state == data[1]

    device = device_registry.async_get_device({(DOMAIN, "20")}, set())
    assert device
    assert device.manufacturer == MANUFACTURER
    assert device.name == "Dining Room"
    assert device.model == "Canary Pro"
コード例 #48
0
ファイル: test_service.py プロジェクト: qq840873731/core-1
def area_mock(hass):
    """Mock including area info."""
    hass.states.async_set("light.Bowl", STATE_ON)
    hass.states.async_set("light.Ceiling", STATE_OFF)
    hass.states.async_set("light.Kitchen", STATE_OFF)

    device_in_area = dev_reg.DeviceEntry(area_id="test-area")
    device_no_area = dev_reg.DeviceEntry()
    device_diff_area = dev_reg.DeviceEntry(area_id="diff-area")

    mock_device_registry(
        hass,
        {
            device_in_area.id: device_in_area,
            device_no_area.id: device_no_area,
            device_diff_area.id: device_diff_area,
        },
    )

    entity_in_own_area = ent_reg.RegistryEntry(
        entity_id="light.in_own_area",
        unique_id="in-own-area-id",
        platform="test",
        area_id="own-area",
    )
    entity_in_area = ent_reg.RegistryEntry(
        entity_id="light.in_area",
        unique_id="in-area-id",
        platform="test",
        device_id=device_in_area.id,
    )
    entity_in_other_area = ent_reg.RegistryEntry(
        entity_id="light.in_other_area",
        unique_id="in-other-area-id",
        platform="test",
        device_id=device_in_area.id,
        area_id="other-area",
    )
    entity_assigned_to_area = ent_reg.RegistryEntry(
        entity_id="light.assigned_to_area",
        unique_id="assigned-area-id",
        platform="test",
        device_id=device_in_area.id,
        area_id="test-area",
    )
    entity_no_area = ent_reg.RegistryEntry(
        entity_id="light.no_area",
        unique_id="no-area-id",
        platform="test",
        device_id=device_no_area.id,
    )
    entity_diff_area = ent_reg.RegistryEntry(
        entity_id="light.diff_area",
        unique_id="diff-area-id",
        platform="test",
        device_id=device_diff_area.id,
    )
    mock_registry(
        hass,
        {
            entity_in_own_area.entity_id: entity_in_own_area,
            entity_in_area.entity_id: entity_in_area,
            entity_in_other_area.entity_id: entity_in_other_area,
            entity_assigned_to_area.entity_id: entity_assigned_to_area,
            entity_no_area.entity_id: entity_no_area,
            entity_diff_area.entity_id: entity_diff_area,
        },
    )