예제 #1
0
async def test_controller_site_already_configured(hass):
    """Test config flow."""
    flow = unifi.UnifiFlowHandler()
    flow.hass = hass

    entry = MockConfigEntry(domain=unifi.DOMAIN, data={
        'controller': {
            'host': '1.2.3.4',
            'site': 'default',
        }
    })
    entry.add_to_hass(hass)

    flow.config = {
        unifi.CONF_HOST: '1.2.3.4',
        unifi.CONF_USERNAME: '******',
        unifi.CONF_PASSWORD: '******',
    }
    flow.desc = 'site name'
    flow.sites = {
        'site1': {
            'name': 'default', 'role': 'admin', 'desc': 'site name'
        }
    }

    result = await flow.async_step_site()

    assert result['type'] == 'abort'
예제 #2
0
async def test_service_refresh_devices(hass):
    """Test that service can refresh devices."""
    entry = MockConfigEntry(domain=deconz.DOMAIN, data={
        'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'
    })
    entry.add_to_hass(hass)
    mock_registry = Mock()

    with patch.object(deconz, 'DeconzGateway') as mock_gateway, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(mock_registry)):
        mock_gateway.return_value.async_setup.return_value = mock_coro(True)
        assert await deconz.async_setup_entry(hass, entry) is True

    with patch.object(hass.data[deconz.DOMAIN].api, 'async_load_parameters',
                      return_value=mock_coro(True)):
        await hass.services.async_call(
            'deconz', 'device_refresh', service_data={})
        await hass.async_block_till_done()

    with patch.object(hass.data[deconz.DOMAIN].api, 'async_load_parameters',
                      return_value=mock_coro(False)):
        await hass.services.async_call(
            'deconz', 'device_refresh', service_data={})
        await hass.async_block_till_done()
예제 #3
0
async def test_unload_entry(hass):
    """Test being able to unload an entry."""
    entry = MockConfigEntry(domain=unifi.DOMAIN, data={
        'controller': {
            'host': '0.0.0.0',
            'username': '******',
            'password': '******',
            'port': 80,
            'site': 'default',
            'verify_ssl': True
        },
        'poe_control': True
    })
    entry.add_to_hass(hass)

    with patch.object(unifi, 'UniFiController') as mock_controller, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(Mock())):
        mock_controller.return_value.async_setup.return_value = mock_coro(True)
        mock_controller.return_value.mac = '00:11:22:33:44:55'
        assert await unifi.async_setup_entry(hass, entry) is True

    assert len(mock_controller.return_value.mock_calls) == 1

    mock_controller.return_value.async_reset.return_value = mock_coro(True)
    assert await unifi.async_unload_entry(hass, entry)
    assert len(mock_controller.return_value.async_reset.mock_calls) == 1
    assert hass.data[unifi.DOMAIN] == {}
예제 #4
0
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
    """Test MQTT climate device registry integration."""
    entry = MockConfigEntry(domain=mqtt.DOMAIN)
    entry.add_to_hass(hass)
    await async_start(hass, 'homeassistant', {}, entry)
    registry = await hass.helpers.device_registry.async_get_registry()

    data = json.dumps({
        'platform': 'mqtt',
        'name': 'Test 1',
        'device': {
            'identifiers': ['helloworld'],
            'connections': [
                ["mac", "02:5b:26:a8:dc:12"],
            ],
            'manufacturer': 'Whatever',
            'name': 'Beer',
            'model': 'Glass',
            'sw_version': '0.1-beta',
        },
        'unique_id': 'veryunique'
    })
    async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
                            data)
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    device = registry.async_get_device({('mqtt', 'helloworld')}, set())
    assert device is not None
    assert device.identifiers == {('mqtt', 'helloworld')}
    assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
    assert device.manufacturer == 'Whatever'
    assert device.name == 'Beer'
    assert device.model == 'Glass'
    assert device.sw_version == '0.1-beta'
예제 #5
0
async def test_config_passed_to_config_entry(hass):
    """Test that configured options for a host are loaded via config entry."""
    entry = MockConfigEntry(domain=hue.DOMAIN, data={
        'host': '0.0.0.0',
    })
    entry.add_to_hass(hass)

    with patch.object(hue, 'HueBridge') as mock_bridge:
        mock_bridge.return_value.async_setup.return_value = mock_coro(True)
        assert await async_setup_component(hass, hue.DOMAIN, {
            hue.DOMAIN: {
                hue.CONF_BRIDGES: {
                    hue.CONF_HOST: '0.0.0.0',
                    hue.CONF_FILENAME: 'bla.conf',
                    hue.CONF_ALLOW_HUE_GROUPS: False,
                    hue.CONF_ALLOW_UNREACHABLE: True
                }
            }
        }) is True

    assert len(mock_bridge.mock_calls) == 2
    p_hass, p_entry, p_allow_unreachable, p_allow_groups = \
        mock_bridge.mock_calls[0][1]

    assert p_hass is hass
    assert p_entry is entry
    assert p_allow_unreachable is True
    assert p_allow_groups is False
예제 #6
0
async def test_import_already_configured(hass):
    """Test importing a device from .homekit that is already a ConfigEntry."""
    discovery_info = {
        'host': '127.0.0.1',
        'port': 8080,
        'properties': {
            'md': 'TestDevice',
            'id': '00:00:00:00:00:00',
            'c#': 1,
            'sf': 1,
        }
    }

    import_info = {
        'AccessoryPairingID': '00:00:00:00:00:00',
    }

    config_entry = MockConfigEntry(
        domain='homekit_controller',
        data=import_info
    )
    config_entry.add_to_hass(hass)

    flow = config_flow.HomekitControllerFlowHandler()
    flow.hass = hass

    result = await flow.async_import_legacy_pairing(
        discovery_info['properties'], import_info)
    assert result['type'] == 'abort'
    assert result['reason'] == 'already_configured'
예제 #7
0
async def test_entity_device_info_with_hub(hass, mqtt_mock):
    """Test MQTT sensor device registry integration."""
    entry = MockConfigEntry(domain=mqtt.DOMAIN)
    entry.add_to_hass(hass)
    await async_start(hass, 'homeassistant', {}, entry)

    registry = await hass.helpers.device_registry.async_get_registry()
    hub = registry.async_get_or_create(
        config_entry_id='123',
        connections=set(),
        identifiers={('mqtt', 'hub-id')},
        manufacturer='manufacturer', model='hub'
    )

    data = json.dumps({
        'platform': 'mqtt',
        'name': 'Test 1',
        'state_topic': 'test-topic',
        'device': {
            'identifiers': ['helloworld'],
            'via_hub': 'hub-id',
        },
        'unique_id': 'veryunique'
    })
    async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config', data)
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    device = registry.async_get_device({('mqtt', 'helloworld')}, set())
    assert device is not None
    assert device.hub_device_id == hub.id
예제 #8
0
async def test_controller_no_mac(hass):
    """Test that configured options for a host are loaded via config entry."""
    entry = MockConfigEntry(domain=unifi.DOMAIN, data={
        'controller': {
            'host': '0.0.0.0',
            'username': '******',
            'password': '******',
            'port': 80,
            'site': 'default',
            'verify_ssl': True
        },
        'poe_control': True
    })
    entry.add_to_hass(hass)
    mock_registry = Mock()
    with patch.object(unifi, 'UniFiController') as mock_controller, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(mock_registry)):
        mock_controller.return_value.async_setup.return_value = mock_coro(True)
        mock_controller.return_value.mac = None
        assert await unifi.async_setup_entry(hass, entry) is True

    assert len(mock_controller.mock_calls) == 2

    assert len(mock_registry.mock_calls) == 0
예제 #9
0
async def test_entry_reload_error(hass, manager, state):
    """Test that we can reload an entry."""
    entry = MockConfigEntry(
        domain='comp',
        state=state
    )
    entry.add_to_hass(hass)

    async_setup = MagicMock(return_value=mock_coro(True))
    async_setup_entry = MagicMock(return_value=mock_coro(True))
    async_unload_entry = MagicMock(return_value=mock_coro(True))

    loader.set_component(hass, 'comp', MockModule(
        'comp',
        async_setup=async_setup,
        async_setup_entry=async_setup_entry,
        async_unload_entry=async_unload_entry
    ))

    with pytest.raises(config_entries.OperationNotAllowed):
        assert await manager.async_reload(entry.entry_id)

    assert len(async_unload_entry.mock_calls) == 0
    assert len(async_setup.mock_calls) == 0
    assert len(async_setup_entry.mock_calls) == 0

    assert entry.state == state
예제 #10
0
 def test_setup_registered_zone_skips_home_zone(self):
     """Test that config entry named home should override hass home zone."""
     entry = MockConfigEntry(domain=zone.DOMAIN, data={
         zone.CONF_NAME: 'home'
     })
     entry.add_to_hass(self.hass)
     assert setup.setup_component(self.hass, zone.DOMAIN, {'zone': None})
     assert len(self.hass.states.entity_ids('zone')) == 0
async def test_remove_entry_unauth(hass, client, hass_admin_user):
    """Test removing an entry via the API."""
    hass_admin_user.groups = []
    entry = MockConfigEntry(domain='demo', state=core_ce.ENTRY_STATE_LOADED)
    entry.add_to_hass(hass)
    resp = await client.delete(
        '/api/config/config_entries/entry/{}'.format(entry.entry_id))
    assert resp.status == 401
    assert len(hass.config_entries.async_entries()) == 1
예제 #12
0
async def test_service_configure(hass):
    """Test that service invokes pydeconz with the correct path and data."""
    entry = MockConfigEntry(domain=deconz.DOMAIN, data={
        'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'
    })
    entry.add_to_hass(hass)
    mock_registry = Mock()
    with patch.object(deconz, 'DeconzGateway') as mock_gateway, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(mock_registry)):
        mock_gateway.return_value.async_setup.return_value = mock_coro(True)
        assert await deconz.async_setup_entry(hass, entry) is True

    hass.data[deconz.DOMAIN].deconz_ids = {
        'light.test': '/light/1'
    }
    data = {'on': True, 'attr1': 10, 'attr2': 20}

    # only field
    with patch('pydeconz.DeconzSession.async_put_state',
               return_value=mock_coro(True)):
        await hass.services.async_call('deconz', 'configure', service_data={
            'field': '/light/42', 'data': data
        })
        await hass.async_block_till_done()

    # only entity
    with patch('pydeconz.DeconzSession.async_put_state',
               return_value=mock_coro(True)):
        await hass.services.async_call('deconz', 'configure', service_data={
            'entity': 'light.test', 'data': data
        })
        await hass.async_block_till_done()

    # entity + field
    with patch('pydeconz.DeconzSession.async_put_state',
               return_value=mock_coro(True)):
        await hass.services.async_call('deconz', 'configure', service_data={
            'entity': 'light.test', 'field': '/state', 'data': data})
        await hass.async_block_till_done()

    # non-existing entity (or not from deCONZ)
    with patch('pydeconz.DeconzSession.async_put_state',
               return_value=mock_coro(True)):
        await hass.services.async_call('deconz', 'configure', service_data={
            'entity': 'light.nonexisting', 'field': '/state', 'data': data})
        await hass.async_block_till_done()

    # field does not start with /
    with pytest.raises(vol.Invalid):
        with patch('pydeconz.DeconzSession.async_put_state',
                   return_value=mock_coro(True)):
            await hass.services.async_call(
                'deconz', 'configure', service_data={
                    'entity': 'light.test', 'field': 'state', 'data': data})
            await hass.async_block_till_done()
예제 #13
0
async def test_config_passed_to_config_entry(hass):
    """Test that configured options for a host are loaded via config entry."""
    entry = MockConfigEntry(domain=hue.DOMAIN, data={
        'host': '0.0.0.0',
    })
    entry.add_to_hass(hass)
    mock_registry = Mock()
    with patch.object(hue, 'HueBridge') as mock_bridge, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(mock_registry)):
        mock_bridge.return_value.async_setup.return_value = mock_coro(True)
        mock_bridge.return_value.api.config = Mock(
            mac='mock-mac',
            bridgeid='mock-bridgeid',
            raw={
                'modelid': 'mock-modelid',
                'swversion': 'mock-swversion',
            }
        )
        # Can't set name via kwargs
        mock_bridge.return_value.api.config.name = 'mock-name'
        assert await async_setup_component(hass, hue.DOMAIN, {
            hue.DOMAIN: {
                hue.CONF_BRIDGES: {
                    hue.CONF_HOST: '0.0.0.0',
                    hue.CONF_FILENAME: 'bla.conf',
                    hue.CONF_ALLOW_HUE_GROUPS: False,
                    hue.CONF_ALLOW_UNREACHABLE: True
                }
            }
        }) is True

    assert len(mock_bridge.mock_calls) == 2
    p_hass, p_entry, p_allow_unreachable, p_allow_groups = \
        mock_bridge.mock_calls[0][1]

    assert p_hass is hass
    assert p_entry is entry
    assert p_allow_unreachable is True
    assert p_allow_groups is False

    assert len(mock_registry.mock_calls) == 1
    assert mock_registry.mock_calls[0][2] == {
        'config_entry_id': entry.entry_id,
        'connections': {
            ('mac', 'mock-mac')
        },
        'identifiers': {
            ('hue', 'mock-bridgeid')
        },
        'manufacturer': 'Signify',
        'name': 'mock-name',
        'model': 'mock-modelid',
        'sw_version': 'mock-swversion',
    }
def test_remove_entry(hass, client):
    """Test removing an entry via the API."""
    entry = MockConfigEntry(domain='demo', state=core_ce.ENTRY_STATE_LOADED)
    entry.add_to_hass(hass)
    resp = yield from client.delete(
        '/api/config/config_entries/entry/{}'.format(entry.entry_id))
    assert resp.status == 200
    data = yield from resp.json()
    assert data == {
        'require_restart': True
    }
    assert len(hass.config_entries.async_entries()) == 0
예제 #15
0
async def test_configured_devices(hass):
    """Test that configured devices works as expected."""
    result = config_flow.configured_devices(hass)

    assert not result

    entry = MockConfigEntry(domain=axis.DOMAIN,
                            data={axis.CONF_DEVICE: {axis.CONF_HOST: ''}})
    entry.add_to_hass(hass)

    result = config_flow.configured_devices(hass)

    assert len(result) == 1
예제 #16
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = MockConfigEntry(domain=deconz.DOMAIN, data={
        'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'
    })
    entry.add_to_hass(hass)
    mock_registry = Mock()
    with patch.object(deconz, 'DeconzGateway') as mock_gateway, \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(mock_registry)):
        mock_gateway.return_value.async_setup.return_value = mock_coro(True)
        assert await deconz.async_setup_entry(hass, entry) is True
    assert hass.data[deconz.DOMAIN]
예제 #17
0
async def setup_push_receiver(hass, aioclient_mock):
    """Fixture that sets up a mocked push receiver."""
    push_url = 'https://mobile-push.home-assistant.dev/push'

    from datetime import datetime, timedelta
    now = (datetime.now() + timedelta(hours=24))
    iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")

    aioclient_mock.post(push_url, json={
        'rateLimits': {
            'attempts': 1,
            'successful': 1,
            'errors': 0,
            'total': 1,
            'maximum': 150,
            'remaining': 149,
            'resetsAt': iso_time
        }
    })

    entry = MockConfigEntry(
        connection_class="cloud_push",
        data={
            "app_data": {
                "push_token": "PUSH_TOKEN",
                "push_url": push_url
            },
            "app_id": "io.homeassistant.mobile_app",
            "app_name": "mobile_app tests",
            "app_version": "1.0",
            "device_id": "4d5e6f",
            "device_name": "Test",
            "manufacturer": "Home Assistant",
            "model": "mobile_app",
            "os_name": "Linux",
            "os_version": "5.0.6",
            "secret": "123abc",
            "supports_encryption": False,
            "user_id": "1a2b3c",
            "webhook_id": "webhook_id"
        },
        domain=DOMAIN,
        source="registration",
        title="mobile_app test entry",
        version=1
    )
    entry.add_to_hass(hass)

    await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
    await hass.async_block_till_done()
예제 #18
0
async def test_populate_options(hass):
    """Test successful populate options."""
    entry = MockConfigEntry(domain=axis.DOMAIN, data={'device': {}})
    entry.add_to_hass(hass)

    with patch.object(axis, 'get_device', return_value=mock_coro(Mock())):

        await axis.async_populate_options(hass, entry)

    assert entry.options == {
        axis.CONF_CAMERA: True,
        axis.CONF_EVENTS: True,
        axis.CONF_TRIGGER_TIME: axis.DEFAULT_TRIGGER_TIME
    }
예제 #19
0
async def test_entity_device_info_update(hass, mqtt_mock):
    """Test device registry update."""
    entry = MockConfigEntry(domain=mqtt.DOMAIN)
    entry.add_to_hass(hass)
    await async_start(hass, 'homeassistant', {}, entry)
    registry = await hass.helpers.device_registry.async_get_registry()

    config = {
        'platform': 'mqtt',
        'name': 'Test 1',
        'schema': 'template',
        'state_topic': 'test-topic',
        'command_topic': 'test-command-topic',
        'command_on_template': 'on,{{ transition }}',
        'command_off_template': 'off,{{ transition|d }}',
        'device': {
            'identifiers': ['helloworld'],
            'connections': [
                ["mac", "02:5b:26:a8:dc:12"],
            ],
            'manufacturer': 'Whatever',
            'name': 'Beer',
            'model': 'Glass',
            'sw_version': '0.1-beta',
        },
        'unique_id': 'veryunique'
    }

    data = json.dumps(config)
    async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
                            data)
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    device = registry.async_get_device({('mqtt', 'helloworld')}, set())
    assert device is not None
    assert device.name == 'Beer'

    config['device']['name'] = 'Milk'
    data = json.dumps(config)
    async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
                            data)
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    device = registry.async_get_device({('mqtt', 'helloworld')}, set())
    assert device is not None
    assert device.name == 'Milk'
예제 #20
0
    def test_setup_registered_zone_skips_configured_zone(self):
        """Test if config entry will override configured zone."""
        entry = MockConfigEntry(domain=zone.DOMAIN, data={
            zone.CONF_NAME: 'Test Zone'
        })
        entry.add_to_hass(self.hass)
        info = {
            'name': 'Test Zone',
            'latitude': 1.1,
            'longitude': -2.2,
        }
        assert setup.setup_component(self.hass, zone.DOMAIN, {'zone': info})

        assert len(self.hass.states.entity_ids('zone')) == 1
        state = self.hass.states.get('zone.test_zone')
        assert not state
예제 #21
0
async def test_call_async_migrate_entry_failure_not_supported(hass):
    """Test migration fails if async_migrate_entry not implemented."""
    entry = MockConfigEntry(domain='comp')
    entry.version = 2
    entry.add_to_hass(hass)

    mock_setup_entry = MagicMock(return_value=mock_coro(True))

    loader.set_component(
        hass, 'comp',
        MockModule('comp', async_setup_entry=mock_setup_entry))

    result = await async_setup_component(hass, 'comp', {})
    assert result
    assert len(mock_setup_entry.mock_calls) == 0
    assert entry.state == config_entries.ENTRY_STATE_MIGRATION_ERROR
예제 #22
0
async def test_unload_entry(hass):
    """Test being able to unload an entry."""
    entry = MockConfigEntry(domain=hue.DOMAIN, data={
        'host': '0.0.0.0',
    })
    entry.add_to_hass(hass)

    with patch.object(hue, 'HueBridge') as mock_bridge:
        mock_bridge.return_value.async_setup.return_value = mock_coro(True)
        assert await async_setup_component(hass, hue.DOMAIN, {}) is True

    assert len(mock_bridge.return_value.mock_calls) == 1

    mock_bridge.return_value.async_reset.return_value = mock_coro(True)
    assert await hue.async_unload_entry(hass, entry)
    assert len(mock_bridge.return_value.async_reset.mock_calls) == 1
    assert hass.data[hue.DOMAIN] == {}
예제 #23
0
async def test_entry_unload_failed_to_load(hass, manager, state):
    """Test that we can unload an entry."""
    entry = MockConfigEntry(
        domain='comp',
        state=state,
    )
    entry.add_to_hass(hass)

    async_unload_entry = MagicMock(return_value=mock_coro(True))

    loader.set_component(hass, 'comp', MockModule(
        'comp',
        async_unload_entry=async_unload_entry
    ))

    assert await manager.async_unload(entry.entry_id)
    assert len(async_unload_entry.mock_calls) == 0
    assert entry.state == config_entries.ENTRY_STATE_NOT_LOADED
예제 #24
0
async def test_flow_create_entry_more_entries(hass):
    """Test that create entry can generate a name with other entries."""
    entry = MockConfigEntry(
        domain=axis.DOMAIN, data={config_flow.CONF_NAME: 'model 0',
                                  config_flow.CONF_MODEL: 'model'})
    entry.add_to_hass(hass)
    entry2 = MockConfigEntry(
        domain=axis.DOMAIN, data={config_flow.CONF_NAME: 'model 1',
                                  config_flow.CONF_MODEL: 'model'})
    entry2.add_to_hass(hass)

    flow = config_flow.AxisFlowHandler()
    flow.hass = hass
    flow.model = 'model'

    result = await flow._create_entry()

    assert result['data'][config_flow.CONF_NAME] == 'model 2'
예제 #25
0
async def test_discovery_flow_already_configured(hass):
    """Test that discovery doesn't setup already configured devices."""
    flow = config_flow.AxisFlowHandler()
    flow.hass = hass

    entry = MockConfigEntry(domain=axis.DOMAIN, data={axis.CONF_DEVICE: {
        axis.CONF_HOST: '1.2.3.4'
    }})
    entry.add_to_hass(hass)

    result = await flow.async_step_discovery(discovery_info={
        config_flow.CONF_HOST: '1.2.3.4',
        config_flow.CONF_USERNAME: '******',
        config_flow.CONF_PASSWORD: '******',
        config_flow.CONF_PORT: 81
    })
    print(result)
    assert result['type'] == 'abort'
예제 #26
0
async def test_flow_fails_already_configured(hass):
    """Test that config flow fails on already configured device."""
    flow = config_flow.AxisFlowHandler()
    flow.hass = hass

    entry = MockConfigEntry(domain=axis.DOMAIN, data={axis.CONF_DEVICE: {
        axis.CONF_HOST: '1.2.3.4'
    }})
    entry.add_to_hass(hass)

    result = await flow.async_step_user(user_input={
        config_flow.CONF_HOST: '1.2.3.4',
        config_flow.CONF_USERNAME: '******',
        config_flow.CONF_PASSWORD: '******',
        config_flow.CONF_PORT: 81
    })

    assert result['errors'] == {'base': 'already_configured'}
예제 #27
0
async def test_call_setup_entry(hass):
    """Test we call <component>.setup_entry."""
    entry = MockConfigEntry(domain='comp')
    entry.add_to_hass(hass)

    mock_setup_entry = MagicMock(return_value=mock_coro(True))
    mock_migrate_entry = MagicMock(return_value=mock_coro(True))

    loader.set_component(
        hass, 'comp',
        MockModule('comp', async_setup_entry=mock_setup_entry,
                   async_migrate_entry=mock_migrate_entry))

    result = await async_setup_component(hass, 'comp', {})
    assert result
    assert len(mock_migrate_entry.mock_calls) == 0
    assert len(mock_setup_entry.mock_calls) == 1
    assert entry.state == config_entries.ENTRY_STATE_LOADED
예제 #28
0
async def test_unload_entry(hass):
    """Test being able to unload an entry."""
    entry = MockConfigEntry(domain=hmipc.DOMAIN, data={
        hmipc.HMIPC_HAPID: 'ABC123',
        hmipc.HMIPC_AUTHTOKEN: '123',
        hmipc.HMIPC_NAME: 'hmip',
    })
    entry.add_to_hass(hass)

    with patch.object(hmipc, 'HomematicipHAP') as mock_hap:
        mock_hap.return_value.async_setup.return_value = mock_coro(True)
        assert await async_setup_component(hass, hmipc.DOMAIN, {}) is True

    assert len(mock_hap.return_value.mock_calls) >= 1

    mock_hap.return_value.async_reset.return_value = mock_coro(True)
    assert await hmipc.async_unload_entry(hass, entry)
    assert len(mock_hap.return_value.async_reset.mock_calls) == 1
    assert hass.data[hmipc.DOMAIN] == {}
예제 #29
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = MockConfigEntry(domain=hmipc.DOMAIN, data={
        hmipc.HMIPC_HAPID: 'ABC123',
        hmipc.HMIPC_AUTHTOKEN: '123',
        hmipc.HMIPC_NAME: 'hmip',
    })
    entry.add_to_hass(hass)
    with patch.object(hmipc, 'HomematicipHAP') as mock_hap:
        mock_hap.return_value.async_setup.return_value = mock_coro(True)
        assert await async_setup_component(hass, hmipc.DOMAIN, {
            hmipc.DOMAIN: {
                hmipc.CONF_ACCESSPOINT: 'ABC123',
                hmipc.CONF_AUTHTOKEN: '123',
                hmipc.CONF_NAME: 'hmip',
            }
        }) is True

    assert len(mock_hap.mock_calls) >= 2
예제 #30
0
async def test_entry_setup_succeed(hass, manager):
    """Test that we can setup an entry."""
    entry = MockConfigEntry(
        domain='comp',
        state=config_entries.ENTRY_STATE_NOT_LOADED
    )
    entry.add_to_hass(hass)

    mock_setup = MagicMock(return_value=mock_coro(True))
    mock_setup_entry = MagicMock(return_value=mock_coro(True))

    loader.set_component(hass, 'comp', MockModule(
        'comp',
        async_setup=mock_setup,
        async_setup_entry=mock_setup_entry
    ))

    assert await manager.async_setup(entry.entry_id)
    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1
    assert entry.state == config_entries.ENTRY_STATE_LOADED
예제 #31
0
async def test_get_trigger_capabilities_none(
    hass, device_reg, entity_reg, enable_custom_integrations
):
    """Test we get the expected capabilities from a sensor trigger."""
    platform = getattr(hass.components, f"test.{DOMAIN}")
    platform.init()

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)

    assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
    await hass.async_block_till_done()

    triggers = [
        {
            "platform": "device",
            "device_id": "8770c43885354d5fa27604db6817f63f",
            "domain": "sensor",
            "entity_id": "sensor.beer",
            "type": "is_battery_level",
        },
        {
            "platform": "device",
            "device_id": "8770c43885354d5fa27604db6817f63f",
            "domain": "sensor",
            "entity_id": platform.ENTITIES["none"].entity_id,
            "type": "is_battery_level",
        },
    ]

    expected_capabilities = {}
    for trigger in triggers:
        capabilities = await async_get_device_automation_capabilities(
            hass, DeviceAutomationType.TRIGGER, trigger
        )
        assert capabilities == expected_capabilities
예제 #32
0
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
    """Test MQTT binary sensor device registry integration."""
    entry = MockConfigEntry(domain=mqtt.DOMAIN)
    entry.add_to_hass(hass)
    await async_start(hass, 'homeassistant', {}, entry)
    registry = await hass.helpers.device_registry.async_get_registry()

    data = json.dumps({
        'platform': 'mqtt',
        'name': 'Test 1',
        'state_topic': 'test-topic',
        'device': {
            'identifiers': ['helloworld'],
            'connections': [
                ["mac", "02:5b:26:a8:dc:12"],
            ],
            'manufacturer': 'Whatever',
            'name': 'Beer',
            'model': 'Glass',
            'sw_version': '0.1-beta',
        },
        'unique_id': 'veryunique'
    })
    async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
                            data)
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    device = registry.async_get_device({('mqtt', 'helloworld')}, set())
    assert device is not None
    assert device.identifiers == {('mqtt', 'helloworld')}
    assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
    assert device.manufacturer == 'Whatever'
    assert device.name == 'Beer'
    assert device.model == 'Glass'
    assert device.sw_version == '0.1-beta'
예제 #33
0
async def test_form_user_already_configured(hass):
    """Test we abort if already configured."""

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_HOST: "1.1.1.1",
            CONF_PORT: 12,
            CONF_SYSTEM_ID: 46
        },
    )
    config_entry.add_to_hass(hass)
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})
    assert result["type"] == "form"
    assert result["errors"] == {}

    with patch(
            "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
            return_value={"any": "data"},
    ), patch(
            "homeassistant.components.somfy_mylink.async_setup_entry",
            return_value=True,
    ) as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_HOST: "1.1.1.1",
                CONF_PORT: 1234,
                CONF_SYSTEM_ID: "456",
            },
        )
        await hass.async_block_till_done()

    assert result2["type"] == "abort"
    assert len(mock_setup_entry.mock_calls) == 0
예제 #34
0
async def test_user_already_configured(hass: HomeAssistant):
    """Test starting a flow by user with an already configured region."""

    mock_config = MockConfigEntry(
        domain=DOMAIN,
        data={
            **MOCK_USER_DATA,
            **MOCK_STATIONS_DATA
        },
        unique_id=
        f"{MOCK_USER_DATA[CONF_LOCATION][CONF_LATITUDE]}_{MOCK_USER_DATA[CONF_LOCATION][CONF_LONGITUDE]}",
    )
    mock_config.add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER})
    assert result["type"] == FlowResultType.FORM
    assert result["step_id"] == "user"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], user_input=MOCK_USER_DATA)

    assert result["type"] == FlowResultType.ABORT
    assert result["reason"] == "already_configured"
async def test_zercoconf_discovery_update_configuration(hass):
    """Test if a discovered device is configured and updated with new host."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        title=CONF_NAME,
        data={
            CONF_HOST: "0.0.0.0",
            CONF_PASSWORD: TEST_PASSWORD
        },
        unique_id=TEST_HOSTNAME,
    )
    entry.add_to_hass(hass)

    assert entry.data[CONF_HOST] == "0.0.0.0"

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={CONF_SOURCE: SOURCE_ZEROCONF},
        data=TEST_DISCOVERY,
    )

    assert result["type"] == "abort"
    assert result["reason"] == "already_configured"
    assert entry.data[CONF_HOST] == "1.1.1.1"
async def test_ssdp_already_configured_host_uuid(hass: HomeAssistant,
                                                 fc_class_mock,
                                                 mock_get_source_ip):
    """Test starting a flow from discovery with an already configured uuid."""

    mock_config = MockConfigEntry(
        domain=DOMAIN,
        data=MOCK_USER_DATA,
        unique_id=None,
    )
    mock_config.add_to_hass(hass)

    with patch(
            "homeassistant.components.fritz.common.FritzConnection",
            side_effect=fc_class_mock,
    ), patch("homeassistant.components.fritz.common.FritzStatus"), patch(
            "homeassistant.components.fritz.config_flow.socket.gethostbyname",
            return_value=MOCK_IP,
    ):

        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA)
        assert result["type"] == RESULT_TYPE_ABORT
        assert result["reason"] == "already_configured"
예제 #37
0
async def test_load_failed_host_unavailable(aioclient_mock, hass):
    """Test setup handles unreachable host."""
    def MockInitialize():
        raise TimeoutError()

    device = get_mock_device()
    device.device.side_effect = MockInitialize

    entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_IP_ADDRESS: "1.1.1.1"},
        unique_id=DOMAIN,
    )
    entry.add_to_hass(hass)

    with patch(
            "homeassistant.components.homewizard.coordinator.HomeWizardEnergy",
            return_value=device,
    ):
        await hass.config_entries.async_setup(entry.entry_id)

    await hass.async_block_till_done()

    assert entry.state is ConfigEntryState.SETUP_RETRY
예제 #38
0
async def test_set_config_unique_id(
    hass: HomeAssistant, component_factory: ComponentFactory
) -> None:
    """Test upgrading configs to use a unique id."""
    person0 = new_profile_config("person0", 0)

    await component_factory.configure_component(profile_configs=(person0,))

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={"token": {"userid": "my_user_id"}, "profile": person0.profile},
    )

    with patch("homeassistant.components.withings.async_get_data_manager") as mock:
        data_manager: DataManager = MagicMock(spec=DataManager)
        data_manager.poll_data_update_coordinator = MagicMock(
            spec=DataUpdateCoordinator
        )
        data_manager.poll_data_update_coordinator.last_update_success = True
        mock.return_value = data_manager
        config_entry.add_to_hass(hass)

        await hass.config_entries.async_setup(config_entry.entry_id)
        assert config_entry.unique_id == "my_user_id"
예제 #39
0
async def test_options_flow_disabled_macos(
    hass, hass_ws_client, mock_bleak_scanner_start, macos_adapter
):
    """Test options are disabled on MacOS."""
    await async_setup_component(hass, "config", {})
    entry = MockConfigEntry(
        domain=DOMAIN, data={}, options={}, unique_id=DEFAULT_ADDRESS
    )
    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    ws_client = await hass_ws_client(hass)

    await ws_client.send_json(
        {
            "id": 5,
            "type": "config_entries/get",
            "domain": "bluetooth",
            "type_filter": "integration",
        }
    )
    response = await ws_client.receive_json()
    assert response["result"][0]["supports_options"] is False
예제 #40
0
async def test_options(hass):
    """Test updating options."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        title="NAME",
        data={},
        options={CONF_SCAN_INTERVAL: 5},
    )
    config_entry.add_to_hass(hass)

    with patch("homeassistant.components.plaato.async_setup",
               return_value=True) as mock_setup, patch(
                   "homeassistant.components.plaato.async_setup_entry",
                   return_value=True) as mock_setup_entry:

        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

        result = await hass.config_entries.options.async_init(
            config_entry.entry_id)

        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "user"

        result = await hass.config_entries.options.async_configure(
            result["flow_id"],
            user_input={CONF_SCAN_INTERVAL: 10},
        )

        await hass.async_block_till_done()

        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
        assert result["data"][CONF_SCAN_INTERVAL] == 10

        assert len(mock_setup.mock_calls) == 1
        assert len(mock_setup_entry.mock_calls) == 1
예제 #41
0
async def test_none(hass, mock_simple_nws):
    """Test with None as observation and forecast."""
    instance = mock_simple_nws.return_value
    instance.observation = None
    instance.forecast = None

    entry = MockConfigEntry(
        domain=nws.DOMAIN,
        data=NWS_CONFIG,
    )
    entry.add_to_hass(hass)
    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get("weather.abc_daynight")
    assert state
    assert state.state == STATE_UNKNOWN

    data = state.attributes
    for key in EXPECTED_OBSERVATION_IMPERIAL:
        assert data.get(key) is None

    forecast = data.get(ATTR_FORECAST)
    assert forecast is None
async def test_option_flow_input_floor(hass):
    """Test config flow options."""
    entry = MockConfigEntry(domain=DOMAIN)
    entry.add_to_hass(hass)

    with patch(
        "homeassistant.components.screenlogic.async_setup_entry",
        return_value=True,
    ):
        await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

    result = await hass.config_entries.options.async_init(entry.entry_id)

    assert result["type"] == "form"
    assert result["step_id"] == "init"

    result = await hass.config_entries.options.async_configure(
        result["flow_id"], user_input={CONF_SCAN_INTERVAL: 1}
    )
    assert result["type"] == "create_entry"
    assert result["data"] == {
        CONF_SCAN_INTERVAL: MIN_SCAN_INTERVAL,
    }
async def test_options_flow_thermo(hass, mock_smile) -> None:
    """Test config flow options for thermostatic environments."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        title=CONF_NAME,
        data={
            CONF_HOST: TEST_HOST,
            CONF_PASSWORD: TEST_PASSWORD
        },
        options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
    )

    hass.data[DOMAIN] = {
        entry.entry_id: {
            "api": MagicMock(smile_type="thermostat")
        }
    }
    entry.add_to_hass(hass)

    with patch("homeassistant.components.plugwise.async_setup_entry",
               return_value=True):
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        result = await hass.config_entries.options.async_init(entry.entry_id)

        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "init"

        result = await hass.config_entries.options.async_configure(
            result["flow_id"], user_input={CONF_SCAN_INTERVAL: 60})

        assert result["type"] == RESULT_TYPE_CREATE_ENTRY
        assert result["data"] == {
            CONF_SCAN_INTERVAL: 60,
        }
async def test_get_trigger_capabilities(hass, device_reg, entity_reg):
    """Test we get the expected capabilities from an alarm_control_panel."""
    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )
    entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
    hass.states.async_set(
        "alarm_control_panel.test_5678", "attributes", {"supported_features": 15}
    )

    triggers = await async_get_device_automations(hass, "trigger", device_entry.id)
    assert len(triggers) == 6
    for trigger in triggers:
        capabilities = await async_get_device_automation_capabilities(
            hass, "trigger", trigger
        )
        assert capabilities == {
            "extra_fields": [
                {"name": "for", "optional": True, "type": "positive_time_period_dict"}
            ]
        }
예제 #45
0
async def test_auth_fails(hass):
    """Config entry state is SETUP_ERROR when auth fails."""

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data=_mock_get_config()[DOMAIN],
        title="August august",
    )
    config_entry.add_to_hass(hass)
    assert hass.config_entries.flow.async_progress() == []

    await setup.async_setup_component(hass, "persistent_notification", {})
    with patch(
            "yalexs.authenticator_async.AuthenticatorAsync.async_authenticate",
            side_effect=ClientResponseError(None, None, status=401),
    ):
        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    assert config_entry.state is ConfigEntryState.SETUP_ERROR

    flows = hass.config_entries.flow.async_progress()

    assert flows[0]["step_id"] == "reauth_validate"
async def test_get_actions_not_support_open(hass, device_reg, entity_reg):
    """Test we get the expected actions from a lock which doesn't support open."""
    platform = getattr(hass.components, f"test.{DOMAIN}")
    platform.init()
    assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
    await hass.async_block_till_done()

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )
    entity_reg.async_get_or_create(
        DOMAIN,
        "test",
        platform.ENTITIES["no_support_open"].unique_id,
        device_id=device_entry.id,
    )

    expected_actions = [
        {
            "domain": DOMAIN,
            "type": "lock",
            "device_id": device_entry.id,
            "entity_id": "lock.no_support_open_lock",
        },
        {
            "domain": DOMAIN,
            "type": "unlock",
            "device_id": device_entry.id,
            "entity_id": "lock.no_support_open_lock",
        },
    ]
    actions = await async_get_device_automations(hass, "action", device_entry.id)
    assert_lists_same(actions, expected_actions)
async def test_get_action_no_state(hass, device_reg, entity_reg):
    """Test we get the expected actions for an entity."""
    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC,
                      "12:34:56:AB:CD:EF")},
    )
    entity_reg.async_get_or_create(DOMAIN,
                                   "test",
                                   "5678",
                                   device_id=device_entry.id)
    expected_actions = [
        {
            "domain": DOMAIN,
            "type": "set_value",
            "device_id": device_entry.id,
            "entity_id": "number.test_5678",
        },
    ]
    actions = await async_get_device_automations(hass, "action",
                                                 device_entry.id)
    assert_lists_same(actions, expected_actions)
예제 #48
0
async def test_options_add_duplicate_device(hass):
    """Test we can add a device."""

    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            "host": None,
            "port": None,
            "device": "/dev/tty123",
            "debug": False,
            "automatic_add": False,
            "devices": {
                "0b1100cd0213c7f230010f71": {}
            },
        },
        unique_id=DOMAIN,
    )
    entry.add_to_hass(hass)

    result = await hass.config_entries.options.async_init(entry.entry_id)

    assert result["type"] == "form"
    assert result["step_id"] == "prompt_options"

    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={
            "automatic_add": True,
            "event_code": "0b1100cd0213c7f230010f71",
        },
    )

    assert result["type"] == "form"
    assert result["step_id"] == "prompt_options"
    assert result["errors"]
    assert result["errors"]["event_code"] == "already_configured_device"
예제 #49
0
async def test_get_triggers(hass, device_reg, entity_reg):
    """Test we get the expected triggers from a sensor."""
    platform = getattr(hass.components, f"test.{DOMAIN}")
    platform.init()

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )
    for device_class in DEVICE_CLASSES:
        entity_reg.async_get_or_create(
            DOMAIN,
            "test",
            platform.ENTITIES[device_class].unique_id,
            device_id=device_entry.id,
        )

    assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})

    expected_triggers = [
        {
            "platform": "device",
            "domain": DOMAIN,
            "type": trigger["type"],
            "device_id": device_entry.id,
            "entity_id": platform.ENTITIES[device_class].entity_id,
        }
        for device_class in DEVICE_CLASSES
        for trigger in ENTITY_TRIGGERS[device_class]
        if device_class != "none"
    ]
    triggers = await async_get_device_automations(hass, "trigger", device_entry.id)
    assert len(triggers) == 8
    assert triggers == expected_triggers
예제 #50
0
async def test_cleanup_device(hass, device_reg, entity_reg, mqtt_mock):
    """Test removal from device registry when trigger is removed."""
    config_entry = MockConfigEntry(domain=DOMAIN)
    config_entry.add_to_hass(hass)
    await async_start(hass, "homeassistant", {}, config_entry)

    config = {
        "automation_type": "trigger",
        "topic": "test-topic",
        "type": "foo",
        "subtype": "bar",
        "device": {
            "identifiers": ["helloworld"]
        },
    }

    data = json.dumps(config)
    async_fire_mqtt_message(hass, "homeassistant/device_automation/bla/config",
                            data)
    await hass.async_block_till_done()

    # Verify device registry entry is created
    device_entry = device_reg.async_get_device({("mqtt", "helloworld")}, set())
    assert device_entry is not None

    triggers = await async_get_device_automations(hass, "trigger",
                                                  device_entry.id)
    assert triggers[0]["type"] == "foo"

    async_fire_mqtt_message(hass, "homeassistant/device_automation/bla/config",
                            "")
    await hass.async_block_till_done()

    # Verify device registry entry is cleared
    device_entry = device_reg.async_get_device({("mqtt", "helloworld")}, set())
    assert device_entry is None
예제 #51
0
async def test_forecast_hourly_disable_enable(hass, mock_simple_nws):
    """Test error during update forecast hourly."""
    entry = MockConfigEntry(
        domain=nws.DOMAIN,
        data=NWS_CONFIG,
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    registry = await hass.helpers.entity_registry.async_get_registry()
    entry = registry.async_get_or_create(
        WEATHER_DOMAIN,
        nws.DOMAIN,
        "35_-75_hourly",
    )
    assert entry.disabled is True

    # Test enabling entity
    updated_entry = registry.async_update_entity(entry.entity_id,
                                                 **{"disabled_by": None})
    assert updated_entry != entry
    assert updated_entry.disabled is False
예제 #52
0
async def setup_risco(hass, events=[], options={}):
    """Set up a Risco integration for testing."""
    config_entry = MockConfigEntry(domain=DOMAIN,
                                   data=TEST_CONFIG,
                                   options=options)
    config_entry.add_to_hass(hass)

    with patch(
            "homeassistant.components.risco.RiscoAPI.login",
            return_value=True,
    ), patch(
            "homeassistant.components.risco.RiscoAPI.site_uuid",
            new_callable=PropertyMock(return_value=TEST_SITE_UUID),
    ), patch(
            "homeassistant.components.risco.RiscoAPI.site_name",
            new_callable=PropertyMock(return_value=TEST_SITE_NAME),
    ), patch("homeassistant.components.risco.RiscoAPI.close"), patch(
            "homeassistant.components.risco.RiscoAPI.get_events",
            return_value=events,
    ):
        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    return config_entry
예제 #53
0
파일: test_sensor.py 프로젝트: jbouwh/core
async def test_sensors(hass):
    """Test setting up creates the sensors."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        unique_id="61DE521B-F0BF-9F44-64D4-75BBE1738105",
    )
    entry.add_to_hass(hass)

    saved_callback = None

    def _async_register_callback(_hass, _callback, _matcher, _mode):
        nonlocal saved_callback
        saved_callback = _callback
        return lambda: None

    with patch(
            "homeassistant.components.bluetooth.update_coordinator.async_register_callback",
            _async_register_callback,
    ):
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

    assert len(hass.states.async_all()) == 0
    saved_callback(MOAT_S2_SERVICE_INFO, BluetoothChange.ADVERTISEMENT)
    await hass.async_block_till_done()
    assert len(hass.states.async_all()) == 4

    temp_sensor = hass.states.get("sensor.moat_s2_eeff_voltage")
    temp_sensor_attribtes = temp_sensor.attributes
    assert temp_sensor.state == "3.061"
    assert temp_sensor_attribtes[ATTR_FRIENDLY_NAME] == "Moat S2 EEFF Voltage"
    assert temp_sensor_attribtes[ATTR_UNIT_OF_MEASUREMENT] == "V"
    assert temp_sensor_attribtes[ATTR_STATE_CLASS] == "measurement"

    assert await hass.config_entries.async_unload(entry.entry_id)
    await hass.async_block_till_done()
예제 #54
0
async def test_call_async_migrate_entry_failure_not_bool(hass):
    """Test migration fails if boolean not returned."""
    entry = MockConfigEntry(domain="comp")
    entry.version = 2
    entry.add_to_hass(hass)

    mock_migrate_entry = MagicMock(return_value=mock_coro())
    mock_setup_entry = MagicMock(return_value=mock_coro(True))

    mock_integration(
        hass,
        MockModule(
            "comp",
            async_setup_entry=mock_setup_entry,
            async_migrate_entry=mock_migrate_entry,
        ),
    )
    mock_entity_platform(hass, "config_flow.comp", None)

    result = await async_setup_component(hass, "comp", {})
    assert result
    assert len(mock_migrate_entry.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 0
    assert entry.state == config_entries.ENTRY_STATE_MIGRATION_ERROR
예제 #55
0
async def test_call_async_migrate_entry(hass):
    """Test we call <component>.async_migrate_entry when version mismatch."""
    entry = MockConfigEntry(domain="comp")
    entry.version = 2
    entry.add_to_hass(hass)

    mock_migrate_entry = MagicMock(return_value=mock_coro(True))
    mock_setup_entry = MagicMock(return_value=mock_coro(True))

    mock_integration(
        hass,
        MockModule(
            "comp",
            async_setup_entry=mock_setup_entry,
            async_migrate_entry=mock_migrate_entry,
        ),
    )
    mock_entity_platform(hass, "config_flow.comp", None)

    result = await async_setup_component(hass, "comp", {})
    assert result
    assert len(mock_migrate_entry.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1
    assert entry.state == config_entries.ENTRY_STATE_LOADED
예제 #56
0
async def test_set_up_local(hass, aioclient_mock):
    """Test we do not set up Almond to connect to HA if we use local."""

    # Set up an internal URL, as Almond won't be set up if there is no URL available
    await async_process_ha_core_config(
        hass,
        {"internal_url": "https://192.168.0.1"},
    )

    entry = MockConfigEntry(
        domain="almond",
        data={
            "type": const.TYPE_LOCAL,
            "host": "http://localhost:9999"
        },
    )
    entry.add_to_hass(hass)

    with patch(
            "pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
        assert await async_setup_component(hass, "almond", {})

    assert entry.state == config_entries.ENTRY_STATE_LOADED
    assert len(mock_create_device.mock_calls) == 1
예제 #57
0
async def test_get_conditions_hidden_auxiliary(
    hass,
    device_reg,
    entity_reg,
    hidden_by,
    entity_category,
):
    """Test we get the expected conditions from a hidden or auxiliary entity."""
    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC,
                      "12:34:56:AB:CD:EF")},
    )
    entity_reg.async_get_or_create(
        DOMAIN,
        "test",
        "5678",
        device_id=device_entry.id,
        entity_category=entity_category,
        hidden_by=hidden_by,
    )
    expected_conditions = [{
        "condition": "device",
        "domain": DOMAIN,
        "type": condition,
        "device_id": device_entry.id,
        "entity_id": f"{DOMAIN}.test_5678",
        "metadata": {
            "secondary": True
        },
    } for condition in ["is_on", "is_off"]]
    conditions = await async_get_device_automations(
        hass, DeviceAutomationType.CONDITION, device_entry.id)
    assert_lists_same(conditions, expected_conditions)
예제 #58
0
async def test_set_up_oauth_no_external_url(hass, aioclient_mock):
    """Test we do not set up Almond to connect to HA if we have no external url."""
    entry = MockConfigEntry(
        domain="almond",
        data={
            "type": const.TYPE_OAUTH2,
            "auth_implementation": "local",
            "host": "http://localhost:9999",
            "token": {
                "expires_at": time() + 1000,
                "access_token": "abcd"
            },
        },
    )
    entry.add_to_hass(hass)

    with patch(
            "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
    ), patch(
            "pyalmond.WebAlmondAPI.async_create_device") as mock_create_device:
        assert await async_setup_component(hass, "almond", {})

    assert entry.state == config_entries.ENTRY_STATE_LOADED
    assert len(mock_create_device.mock_calls) == 0
예제 #59
0
async def test_options_flow(hass: HomeAssistant):
    """Test config flow options."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_LATITUDE: CITY_1_LAT,
            CONF_LONGITUDE: CITY_1_LON
        },
        unique_id=f"{CITY_1_LAT}, {CITY_1_LON}",
    )
    config_entry.add_to_hass(hass)

    assert config_entry.options == {}

    result = await hass.config_entries.options.async_init(config_entry.entry_id
                                                          )
    assert result["type"] == data_entry_flow.FlowResultType.FORM
    assert result["step_id"] == "init"

    # Default
    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={},
    )
    assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
    assert config_entry.options[CONF_MODE] == FORECAST_MODE_DAILY

    # Manual
    result = await hass.config_entries.options.async_init(config_entry.entry_id
                                                          )
    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={CONF_MODE: FORECAST_MODE_HOURLY},
    )
    assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
    assert config_entry.options[CONF_MODE] == FORECAST_MODE_HOURLY
예제 #60
0
async def test_load_handles_generic_exception(aioclient_mock, hass):
    """Test setup handles global exception."""
    def MockInitialize():
        raise Exception()

    device = get_mock_device()
    device.device.side_effect = MockInitialize

    entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_IP_ADDRESS: "1.1.1.1"},
        unique_id=DOMAIN,
    )
    entry.add_to_hass(hass)

    with patch(
            "homeassistant.components.homewizard.coordinator.HomeWizardEnergy",
            return_value=device,
    ):
        await hass.config_entries.async_setup(entry.entry_id)

    await hass.async_block_till_done()

    assert entry.state is ConfigEntryState.SETUP_RETRY or ConfigEntryState.SETUP_ERROR