Beispiel #1
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    with patch.object(hass, 'async_create_task') as mock_add_job, \
        patch.object(hass, 'config_entries') as mock_config_entries, \
        patch('pydeconz.DeconzSession.async_get_state',
              return_value=mock_coro(CONFIG)), \
        patch('pydeconz.DeconzSession.start', return_value=True), \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(Mock())):
        assert await deconz.async_setup_entry(hass, entry) is True
    assert hass.data[deconz.DOMAIN]
    assert hass.data[deconz.DATA_DECONZ_ID] == {}
    assert len(hass.data[deconz.DATA_DECONZ_UNSUB]) == 1
    assert len(mock_add_job.mock_calls) == 5
    assert len(mock_config_entries.async_forward_entry_setup.mock_calls) == 5
    assert mock_config_entries.async_forward_entry_setup.mock_calls[0][1] == \
        (entry, 'binary_sensor')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[1][1] == \
        (entry, 'light')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[2][1] == \
        (entry, 'scene')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[3][1] == \
        (entry, 'sensor')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[4][1] == \
        (entry, 'switch')
Beispiel #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()
Beispiel #3
0
async def test_flow_works(hass, aioclient_mock):
    """Test config flow ."""
    aioclient_mock.get(hue.API_NUPNP, json=[
        {'internalipaddress': '1.2.3.4', 'id': 'bla'}
    ])

    flow = hue.HueFlowHandler()
    flow.hass = hass
    await flow.async_step_init()

    with patch('aiohue.Bridge') as mock_bridge:
        def mock_constructor(host, websession):
            mock_bridge.host = host
            return mock_bridge

        mock_bridge.side_effect = mock_constructor
        mock_bridge.username = '******'
        mock_bridge.config.name = 'Mock Bridge'
        mock_bridge.config.bridgeid = 'bridge-id-1234'
        mock_bridge.create_user.return_value = mock_coro()
        mock_bridge.initialize.return_value = mock_coro()

        result = await flow.async_step_link(user_input={})

    assert mock_bridge.host == '1.2.3.4'
    assert len(mock_bridge.create_user.mock_calls) == 1
    assert len(mock_bridge.initialize.mock_calls) == 1

    assert result['type'] == 'create_entry'
    assert result['title'] == 'Mock Bridge'
    assert result['data'] == {
        'host': '1.2.3.4',
        'bridge_id': 'bridge-id-1234',
        'username': '******'
    }
Beispiel #4
0
async def test_user_permissions_low(hass, aioclient_mock):
    """Test config flow."""
    flow = unifi.UnifiFlowHandler()
    flow.hass = hass

    with patch('aiounifi.Controller') as mock_controller:
        def mock_constructor(host, username, password, port, site, websession):
            """Fake the controller constructor."""
            mock_controller.host = host
            mock_controller.username = username
            mock_controller.password = password
            mock_controller.port = port
            mock_controller.site = site
            return mock_controller

        mock_controller.side_effect = mock_constructor
        mock_controller.login.return_value = mock_coro()
        mock_controller.sites.return_value = mock_coro({
            'site1': {'name': 'default', 'role': 'viewer', 'desc': 'site name'}
        })

        await flow.async_step_user(user_input={
            unifi.CONF_HOST: '1.2.3.4',
            unifi.CONF_USERNAME: '******',
            unifi.CONF_PASSWORD: '******',
            unifi.CONF_PORT: 1234,
            unifi.CONF_VERIFY_SSL: True
        })

        result = await flow.async_step_site(user_input={})

    assert result['type'] == 'abort'
Beispiel #5
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
async def test_full_flow_implementation(hass):
    """Test registering an implementation and finishing flow works."""
    gen_authorize_url = Mock(return_value=mock_coro('https://example.com'))
    convert_code = Mock(return_value=mock_coro({'access_token': 'yoo'}))
    config_flow.register_flow_implementation(
        hass, 'test', 'Test', gen_authorize_url, convert_code)
    config_flow.register_flow_implementation(
        hass, 'test-other', 'Test Other', None, None)

    flow = config_flow.NestFlowHandler()
    flow.hass = hass
    result = await flow.async_step_init()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'init'

    result = await flow.async_step_init({'flow_impl': 'test'})
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'
    assert result['description_placeholders'] == {
        'url': 'https://example.com',
    }

    result = await flow.async_step_link({'code': '123ABC'})
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data']['tokens'] == {'access_token': 'yoo'}
    assert result['data']['impl_domain'] == 'test'
    assert result['title'] == 'Nest (via Test)'
Beispiel #7
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] == {}
async def test_smartapp_sync_subscriptions_handles_exceptions(
        hass, smartthings_mock, device_factory, subscription_factory):
    """Test synchronization does nothing when current."""
    api = smartthings_mock.return_value
    api.delete_subscription.side_effect = \
        lambda loc_id, sub_id: mock_coro(exception=Exception)
    api.create_subscription.side_effect = \
        lambda sub: mock_coro(exception=Exception)
    subscriptions = [
        subscription_factory(Capability.battery),
        subscription_factory(Capability.switch),
        subscription_factory(Capability.switch_level)
    ]
    api.subscriptions.return_value = mock_coro(return_value=subscriptions)
    devices = [
        device_factory('', [Capability.thermostat, 'ping']),
        device_factory('', [Capability.switch, Capability.switch_level]),
        device_factory('', [Capability.switch])
    ]

    await smartapp.smartapp_sync_subscriptions(
        hass, str(uuid4()), str(uuid4()), str(uuid4()), devices)

    assert api.subscriptions.call_count == 1
    assert api.delete_subscription.call_count == 1
    assert api.create_subscription.call_count == 1
def test_validate_config_ok(hass, test_client):
    """Test checking config."""
    app = mock_http_component_app(hass)
    with patch.object(config, 'SECTIONS', ['core']):
        yield from async_setup_component(hass, 'config', {})

    hass.http.views[CheckConfigView.name].register(app.router)
    client = yield from test_client(app)

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro()):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'valid'
    assert result['errors'] is None

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro('beer')):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'invalid'
    assert result['errors'] == 'beer'
async def test_flow_entry_created_from_user_input() -> None:
    """Test that create data from user input.

    Test when the form should show when no configurations exists
    """
    hass = Mock()
    flow = config_flow.SmhiFlowHandler()
    flow.hass = hass

    test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}

    # Test that entry created when user_input name not exists
    with \
        patch.object(flow, '_show_config_form',
                     return_value=mock_coro()) as config_form, \
        patch.object(flow, '_name_in_configuration_exists',
                     return_value=False), \
        patch.object(flow, '_homeassistant_location_exists',
                     return_value=mock_coro(False)), \
        patch.object(config_flow, 'smhi_locations',
                     return_value={
                         'test': 'something', 'name_exist': 'config'
                         }), \
        patch.object(flow, '_check_location',
                     return_value=mock_coro(True)):

        result = await flow.async_step_user(user_input=test_data)

        assert result['type'] == 'create_entry'
        assert result['data'] == test_data
        assert not config_form.mock_calls
async def test_flow_entry_created_user_input_faulty() -> None:
    """Test that create data from user input and are faulty.

    Test when the form should show when user puts faulty location
    in the config gui. Then the form should show with error
    """
    hass = Mock()
    flow = config_flow.SmhiFlowHandler()
    flow.hass = hass

    test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}

    # Test that entry created when user_input name not exists
    with \
        patch.object(flow, '_check_location',
                     return_value=mock_coro(True)), \
        patch.object(flow, '_show_config_form',
                     return_value=mock_coro()) as config_form, \
        patch.object(flow, '_name_in_configuration_exists',
                     return_value=False), \
        patch.object(flow, '_homeassistant_location_exists',
                     return_value=mock_coro(False)), \
        patch.object(config_flow, 'smhi_locations',
                     return_value={
                         'test': 'something', 'name_exist': 'config'
                         }), \
        patch.object(flow, '_check_location',
                     return_value=mock_coro(False)):

        await flow.async_step_user(user_input=test_data)

        assert len(config_form.mock_calls) == 1
        assert len(flow._errors) == 1
Beispiel #12
0
async def test_smartapp_update_syncs_subs(
        hass, smartthings_mock, config_entry, location, device_factory):
    """Test update synchronizes subscriptions."""
    # Arrange
    setattr(hass.config_entries, '_entries', [config_entry])
    app = Mock()
    app.app_id = config_entry.data['app_id']
    api = smartthings_mock.return_value
    api.delete_subscriptions = Mock()
    api.delete_subscriptions.return_value = mock_coro()
    api.create_subscription.return_value = mock_coro()
    request = Mock()
    request.installed_app_id = str(uuid4())
    request.auth_token = str(uuid4())
    request.location_id = location.location_id
    devices = [
        device_factory('', [Capability.battery, 'ping']),
        device_factory('', [Capability.switch, Capability.switch_level]),
        device_factory('', [Capability.switch])
    ]
    api.devices = Mock()
    api.devices.return_value = mock_coro(return_value=devices)
    # Act
    await smartapp.smartapp_update(hass, request, None, app)
    # Assert
    assert api.create_subscription.call_count == 3
    assert api.delete_subscriptions.call_count == 1
async def test_flow_show_form_name_exists() -> None:
    """Test show form if name already exists.

    Test when the form should show when no configurations exists
    """
    hass = Mock()
    flow = config_flow.SmhiFlowHandler()
    flow.hass = hass
    test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}
    # Test show form when home assistant config exists and
    # home is already configured, then new config is allowed
    with \
        patch.object(flow, '_show_config_form',
                     return_value=mock_coro()) as config_form, \
        patch.object(flow, '_name_in_configuration_exists',
                     return_value=True), \
        patch.object(config_flow, 'smhi_locations',
                     return_value={
                         'test': 'something', 'name_exist': 'config'
                         }), \
        patch.object(flow, '_check_location',
                     return_value=mock_coro(True)):

        await flow.async_step_user(user_input=test_data)

        assert len(config_form.mock_calls) == 1
        assert len(flow._errors) == 1
Beispiel #14
0
async def test_smartapp_install_creates_flow(
        hass, smartthings_mock, config_entry, location, device_factory):
    """Test installation creates flow."""
    # Arrange
    setattr(hass.config_entries, '_entries', [config_entry])
    api = smartthings_mock.return_value
    api.create_subscription.return_value = mock_coro()
    app = Mock()
    app.app_id = config_entry.data['app_id']
    request = Mock()
    request.installed_app_id = str(uuid4())
    request.auth_token = str(uuid4())
    request.location_id = location.location_id
    devices = [
        device_factory('', [Capability.battery, 'ping']),
        device_factory('', [Capability.switch, Capability.switch_level]),
        device_factory('', [Capability.switch])
    ]
    api.devices = Mock()
    api.devices.return_value = mock_coro(return_value=devices)
    # Act
    await smartapp.smartapp_install(hass, request, None, app)
    # Assert
    await hass.async_block_till_done()
    entries = hass.config_entries.async_entries('smartthings')
    assert len(entries) == 2
    assert api.create_subscription.call_count == 3
    assert entries[1].data['app_id'] == app.app_id
    assert entries[1].data['installed_app_id'] == request.installed_app_id
    assert entries[1].data['location_id'] == request.location_id
    assert entries[1].data['access_token'] == \
        config_entry.data['access_token']
    assert entries[1].title == location.name
Beispiel #15
0
async def test_smartapp_install_abort_if_no_other(
        hass, smartthings_mock, device_factory):
    """Test aborts if no other app was configured already."""
    # Arrange
    api = smartthings_mock.return_value
    api.create_subscription.return_value = mock_coro()
    app = Mock()
    app.app_id = uuid4()
    request = Mock()
    request.installed_app_id = uuid4()
    request.auth_token = uuid4()
    request.location_id = uuid4()
    devices = [
        device_factory('', [Capability.battery, 'ping']),
        device_factory('', [Capability.switch, Capability.switch_level]),
        device_factory('', [Capability.switch])
    ]
    api.devices = Mock()
    api.devices.return_value = mock_coro(return_value=devices)
    # Act
    await smartapp.smartapp_install(hass, request, None, app)
    # Assert
    entries = hass.config_entries.async_entries('smartthings')
    assert not entries
    assert api.create_subscription.call_count == 3
Beispiel #16
0
async def async_test_device_join(
        hass, zha_gateway, cluster_id, domain, device_type=None):
    """Test a newly joining device.

    This creates a new fake device and adds it to the network. It is meant to
    simulate pairing a new device to the network so that code pathways that
    only trigger during device joins can be tested.
    """
    from zigpy.zcl.foundation import Status
    from zigpy.zcl.clusters.general import Basic
    # create zigpy device mocking out the zigbee network operations
    with patch(
            'zigpy.zcl.Cluster.configure_reporting',
            return_value=mock_coro([Status.SUCCESS, Status.SUCCESS])):
        with patch(
                'zigpy.zcl.Cluster.bind',
                return_value=mock_coro([Status.SUCCESS, Status.SUCCESS])):
            zigpy_device = await async_init_zigpy_device(
                hass, [cluster_id, Basic.cluster_id], [], device_type,
                zha_gateway,
                ieee="00:0d:6f:00:0a:90:69:f7",
                manufacturer="FakeMan{}".format(cluster_id),
                model="FakeMod{}".format(cluster_id),
                is_new_join=True)
            cluster = zigpy_device.endpoints.get(1).in_clusters[cluster_id]
            entity_id = make_entity_id(
                domain, zigpy_device, cluster, use_suffix=device_type is None)
            assert hass.states.get(entity_id) is not None
async def test_configurator_callback(hass, mock_request):
    """."""
    hass.data[hue.DOMAIN] = {}
    with patch('aiohue.Bridge.create_user',
               side_effect=aiohue.LinkButtonNotPressed):
        await MockBridge(hass).async_setup()

    assert len(mock_request.mock_calls) == 1

    callback = mock_request.mock_calls[0][1][2]

    mock_init = Mock(return_value=mock_coro())
    mock_create = Mock(return_value=mock_coro())

    with patch('aiohue.Bridge') as mock_bridge, \
            patch('homeassistant.helpers.discovery.async_load_platform',
                  return_value=mock_coro()) as mock_load_platform, \
            patch('homeassistant.components.hue.save_json') as mock_save:
        inst = mock_bridge()
        inst.username = '******'
        inst.create_user = mock_create
        inst.initialize = mock_init
        await callback(None)

    assert len(mock_create.mock_calls) == 1
    assert len(mock_init.mock_calls) == 1
    assert len(mock_save.mock_calls) == 1
    assert mock_save.mock_calls[0][1][1] == {
        '1.2.3.4': {
            'username': '******'
        }
    }
    assert len(mock_load_platform.mock_calls) == 1
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
Beispiel #19
0
def app_fixture(hass, config_file):
    """Fixture for a single app."""
    app = AppEntity(Mock())
    app.apply_data({
        'appName': APP_NAME_PREFIX + str(uuid4()),
        'appId': str(uuid4()),
        'appType': 'WEBHOOK_SMART_APP',
        'classifications': [CLASSIFICATION_AUTOMATION],
        'displayName': 'Home Assistant',
        'description': "Home Assistant at " + hass.config.api.base_url,
        'singleInstance': True,
        'webhookSmartApp': {
            'targetUrl': webhook.async_generate_url(
                hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]),
            'publicKey': ''}
    })
    app.refresh = Mock()
    app.refresh.return_value = mock_coro()
    app.save = Mock()
    app.save.return_value = mock_coro()
    settings = AppSettings(app.app_id)
    settings.settings[SETTINGS_INSTANCE_ID] = config_file[CONF_INSTANCE_ID]
    app.settings = Mock()
    app.settings.return_value = mock_coro(return_value=settings)
    return app
async def test_remove_entry_handles_callback_error(hass, manager):
    """Test that exceptions in the remove callback are handled."""
    mock_setup_entry = MagicMock(return_value=mock_coro(True))
    mock_unload_entry = MagicMock(return_value=mock_coro(True))
    mock_remove_entry = MagicMock(
        side_effect=lambda *args, **kwargs: mock_coro())
    loader.set_component(hass, 'test', MockModule(
        'test',
        async_setup_entry=mock_setup_entry,
        async_unload_entry=mock_unload_entry,
        async_remove_entry=mock_remove_entry
    ))
    entry = MockConfigEntry(
        domain='test',
        entry_id='test1',
    )
    entry.add_to_manager(manager)
    # Check all config entries exist
    assert [item.entry_id for item in manager.async_entries()] == \
        ['test1']
    # Setup entry
    await entry.async_setup(hass)
    await hass.async_block_till_done()

    # Remove entry
    result = await manager.async_remove('test1')
    await hass.async_block_till_done()
    # Check that unload went well and so no need to restart
    assert result == {
        'require_restart': False
    }
    # Check the remove callback was invoked.
    assert mock_remove_entry.call_count == 1
    # Check that config entry was removed.
    assert [item.entry_id for item in manager.async_entries()] == []
def test_cloud_calling_handler(mock_client, mock_handle_message, mock_cloud):
    """Test we call handle message with correct info."""
    conn = iot.CloudIoT(mock_cloud)
    mock_client.receive.return_value = mock_coro(MagicMock(
        type=WSMsgType.text,
        json=MagicMock(return_value={
            'msgid': 'test-msg-id',
            'handler': 'test-handler',
            'payload': 'test-payload'
        })
    ))
    mock_handle_message.return_value = mock_coro('response')
    mock_client.send_json.return_value = mock_coro(None)

    yield from conn.connect()

    # Check that we sent message to handler correctly
    assert len(mock_handle_message.mock_calls) == 1
    p_hass, p_cloud, handler_name, payload = \
        mock_handle_message.mock_calls[0][1]

    assert p_hass is mock_cloud.hass
    assert p_cloud is mock_cloud
    assert handler_name == 'test-handler'
    assert payload == 'test-payload'

    # Check that we forwarded response from handler to cloud
    assert len(mock_client.send_json.mock_calls) == 1
    assert mock_client.send_json.mock_calls[0][1][0] == {
        'msgid': 'test-msg-id',
        'payload': 'response'
    }
Beispiel #22
0
def test_validate_config_ok(hass, hass_client):
    """Test checking config."""
    with patch.object(config, 'SECTIONS', ['core']):
        yield from async_setup_component(hass, 'config', {})

    yield from asyncio.sleep(0.1, loop=hass.loop)

    client = yield from hass_client()

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro()):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'valid'
    assert result['errors'] is None

    with patch(
        'homeassistant.components.config.core.async_check_ha_config_file',
            return_value=mock_coro('beer')):
        resp = yield from client.post('/api/config/core/check_config')

    assert resp.status == 200
    result = yield from resp.json()
    assert result['result'] == 'invalid'
    assert result['errors'] == 'beer'
async def test_cloudhook_app_created_then_show_wait_form(
        hass, app, app_oauth_client, smartthings_mock):
    """Test SmartApp is created with a cloudhoko and shows wait form."""
    # Unload the endpoint so we can reload it under the cloud.
    await smartapp.unload_smartapp_endpoint(hass)

    mock_async_active_subscription = Mock(return_value=True)
    mock_create_cloudhook = Mock(return_value=mock_coro(
        return_value="http://cloud.test"))
    with patch.object(cloud, 'async_active_subscription',
                      new=mock_async_active_subscription), \
        patch.object(cloud, 'async_create_cloudhook',
                     new=mock_create_cloudhook):

        await smartapp.setup_smartapp_endpoint(hass)

        flow = SmartThingsFlowHandler()
        flow.hass = hass
        smartthings = smartthings_mock.return_value
        smartthings.apps.return_value = mock_coro(return_value=[])
        smartthings.create_app.return_value = \
            mock_coro(return_value=(app, app_oauth_client))
        smartthings.update_app_settings.return_value = mock_coro()
        smartthings.update_app_oauth.return_value = mock_coro()

        result = await flow.async_step_user({'access_token': str(uuid4())})

        assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
        assert result['step_id'] == 'wait_install'
        assert mock_create_cloudhook.call_count == 1
def mock_cloudhooks(hass):
    """Mock cloudhooks class."""
    cloud = Mock()
    cloud.hass = hass
    cloud.hass.async_add_executor_job = Mock(return_value=mock_coro())
    cloud.iot = Mock(async_send_message=Mock(return_value=mock_coro()))
    cloud.cloudhook_create_url = 'https://webhook-create.url'
    cloud.prefs = prefs.CloudPreferences(hass)
    hass.loop.run_until_complete(cloud.prefs.async_initialize())
    return cloudhooks.Cloudhooks(cloud)
Beispiel #25
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',
    }
Beispiel #26
0
def test_setup_embedded_with_embedded(hass):
    """Test setting up embedded server with no config."""
    client_config = ('localhost', 1883, 'user', 'pass', None, '3.1.1')

    with mock.patch('homeassistant.components.mqtt.server.async_start',
                    return_value=mock_coro(
                        return_value=(True, client_config))
                    ) as _start:
        _start.return_value = mock_coro(return_value=(True, client_config))
        yield from mock_mqtt_client(hass, {'embedded': None})
        assert _start.call_count == 1
Beispiel #27
0
async def test_scenes_api_errors_raise_not_ready(
        hass, config_entry, app, installed_app, smartthings_mock):
    """Test if scenes are unauthorized we continue to load platforms."""
    setattr(hass.config_entries, '_entries', [config_entry])
    api = smartthings_mock.return_value
    api.app.return_value = mock_coro(return_value=app)
    api.installed_app.return_value = mock_coro(return_value=installed_app)
    api.scenes.return_value = mock_coro(
        exception=ClientResponseError(None, None, status=500))
    with pytest.raises(ConfigEntryNotReady):
        await smartthings.async_setup_entry(hass, config_entry)
Beispiel #28
0
def hassio_env():
    """Fixture to inject hassio env."""
    with patch.dict(os.environ, {'HASSIO': "127.0.0.1"}), \
            patch('homeassistant.components.hassio.HassIO.is_connected',
                  Mock(return_value=mock_coro(
                    {"result": "ok", "data": {}}))), \
            patch.dict(os.environ, {'HASSIO_TOKEN': "123456"}), \
            patch('homeassistant.components.hassio.HassIO.'
                  'get_homeassistant_info',
                  Mock(return_value=mock_coro(None))):
        yield
async def test_remove_entry(hass, config_entry, smartthings_mock):
    """Test that the installed app and app are removed up."""
    # Arrange
    api = smartthings_mock.return_value
    api.delete_installed_app.side_effect = lambda _: mock_coro()
    api.delete_app.side_effect = lambda _: mock_coro()
    # Act
    await smartthings.async_remove_entry(hass, config_entry)
    # Assert
    assert api.delete_installed_app.call_count == 1
    assert api.delete_app.call_count == 1
    def test_check_ha_config_file_correct(self, mock_create):
        """Check that restart propagates to stop."""
        process_mock = mock.MagicMock()
        attrs = {
            'communicate.return_value': mock_coro((b'output', None)),
            'wait.return_value': mock_coro(0)}
        process_mock.configure_mock(**attrs)
        mock_create.return_value = mock_coro(process_mock)

        assert run_coroutine_threadsafe(
            config_util.async_check_ha_config_file(self.hass), self.hass.loop
        ).result() is None
async def test_unload_entry_resets_platform(hass):
    """Test unloading an entry removes all entities."""
    mock_setup_entry = Mock(return_value=mock_coro(True))
    mock_entity_platform(
        hass,
        "test_domain.entry_domain",
        MockPlatform(async_setup_entry=mock_setup_entry),
    )

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

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

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

    assert await component.async_unload_entry(entry)
    assert len(hass.states.async_entity_ids()) == 0
Beispiel #32
0
async def setup_bridge(hass, data, allow_deconz_groups=True):
    """Load the deCONZ light platform."""
    from pydeconz import DeconzSession
    loop = Mock()
    session = Mock()
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    bridge = DeconzSession(loop, session, **entry.data)
    with patch('pydeconz.DeconzSession.async_get_state',
               return_value=mock_coro(data)):
        await bridge.async_load_parameters()
    hass.data[deconz.DOMAIN] = bridge
    hass.data[deconz.DATA_DECONZ_UNSUB] = []
    hass.data[deconz.DATA_DECONZ_ID] = {}
    config_entry = config_entries.ConfigEntry(
        1, deconz.DOMAIN, 'Mock Title', {
            'host': 'mock-host',
            'allow_deconz_groups': allow_deconz_groups
        }, 'test')
    await hass.config_entries.async_forward_entry_setup(config_entry, 'light')
    # To flush out the service call to update the group
    await hass.async_block_till_done()
Beispiel #33
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    with patch.object(hass, 'async_create_task') as mock_add_job, \
        patch.object(hass, 'config_entries') as mock_config_entries, \
        patch('pydeconz.DeconzSession.async_load_parameters',
              return_value=mock_coro(True)):
        assert await deconz.async_setup_entry(hass, entry) is True
    assert hass.data[deconz.DOMAIN]
    assert hass.data[deconz.DATA_DECONZ_ID] == {}
    assert len(hass.data[deconz.DATA_DECONZ_UNSUB]) == 1
    assert len(mock_add_job.mock_calls) == 4
    assert len(mock_config_entries.async_forward_entry_setup.mock_calls) == 4
    assert mock_config_entries.async_forward_entry_setup.mock_calls[0][1] == \
        (entry, 'binary_sensor')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[1][1] == \
        (entry, 'light')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[2][1] == \
        (entry, 'scene')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[3][1] == \
        (entry, 'sensor')
Beispiel #34
0
async def test_alexa_config_report_state(hass, cloud_prefs):
    """Test Alexa config should expose using prefs."""
    conf = alexa_config.AlexaConfig(hass, ALEXA_SCHEMA({}), cloud_prefs, None)

    assert cloud_prefs.alexa_report_state is False
    assert conf.should_report_state is False
    assert conf.is_reporting_states is False

    with patch.object(conf, "async_get_access_token", return_value=mock_coro("hello")):
        await cloud_prefs.async_update(alexa_report_state=True)
        await hass.async_block_till_done()

    assert cloud_prefs.alexa_report_state is True
    assert conf.should_report_state is True
    assert conf.is_reporting_states is True

    await cloud_prefs.async_update(alexa_report_state=False)
    await hass.async_block_till_done()

    assert cloud_prefs.alexa_report_state is False
    assert conf.should_report_state is False
    assert conf.is_reporting_states is False
Beispiel #35
0
async def test_record_service(hass, mock_camera, mock_stream):
    """Test record service."""
    data = {
        ATTR_ENTITY_ID: 'camera.demo_camera',
        camera.CONF_FILENAME: '/my/path'
    }

    with patch('homeassistant.components.demo.camera.DemoCamera.stream_source',
               new_callable=PropertyMock) as mock_stream_source, \
            patch(
                'homeassistant.components.stream.async_handle_record_service',
                return_value=mock_coro()) as mock_record_service, \
            patch.object(hass.config, 'is_allowed_path', return_value=True):
        mock_stream_source.return_value = io.BytesIO()
        # Call service
        await hass.services.async_call(camera.DOMAIN,
                                       camera.SERVICE_RECORD,
                                       data,
                                       blocking=True)
        # So long as we call stream.record, the rest should be covered
        # by those tests.
        assert mock_record_service.called
Beispiel #36
0
async def test_dhcp_match_macaddress(hass):
    """Test matching based on macaddress only."""
    dhcp_watcher = dhcp.DHCPWatcher(hass, {}, [{
        "domain": "mock-domain",
        "macaddress": "B8B7F1*"
    }])

    packet = Ether(RAW_DHCP_REQUEST)

    with patch.object(hass.config_entries.flow,
                      "async_init",
                      return_value=mock_coro()) as mock_init:
        dhcp_watcher.handle_dhcp_packet(packet)

    assert len(mock_init.mock_calls) == 1
    assert mock_init.mock_calls[0][1][0] == "mock-domain"
    assert mock_init.mock_calls[0][2]["context"] == {"source": "dhcp"}
    assert mock_init.mock_calls[0][2]["data"] == {
        dhcp.IP_ADDRESS: "192.168.210.56",
        dhcp.HOSTNAME: "connect",
        dhcp.MAC_ADDRESS: "b8b7f16db533",
    }
Beispiel #37
0
async def setup_gateway(hass, data):
    """Load the deCONZ switch platform."""
    from pydeconz import DeconzSession
    loop = Mock()
    session = Mock()

    config_entry = config_entries.ConfigEntry(
        1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG, 'test',
        config_entries.CONN_CLASS_LOCAL_PUSH)
    gateway = deconz.DeconzGateway(hass, config_entry)
    gateway.api = DeconzSession(loop, session, **config_entry.data)
    gateway.api.config = Mock()
    hass.data[deconz.DOMAIN] = {gateway.bridgeid: gateway}

    with patch('pydeconz.DeconzSession.async_get_state',
               return_value=mock_coro(data)):
        await gateway.api.async_load_parameters()

    await hass.config_entries.async_forward_entry_setup(config_entry, 'switch')
    # To flush out the service call to update the group
    await hass.async_block_till_done()
    return gateway
Beispiel #38
0
async def test_throttle_async_update(hass):
    """Ensure we throttle updates."""
    await setup_awair(hass)

    future = NOW + timedelta(minutes=1)
    data_patch = patch(
        "python_awair.AwairClient.air_data_latest",
        return_value=mock_coro(AIR_DATA_FIXTURE_UPDATED),
    )

    with data_patch, alter_time(future):
        async_fire_time_changed(hass, future)
        await hass.async_block_till_done()

    assert hass.states.get("sensor.awair_score").state == "78"

    future = NOW + timedelta(minutes=15)
    with data_patch, alter_time(future):
        async_fire_time_changed(hass, future)
        await hass.async_block_till_done()

    assert hass.states.get("sensor.awair_score").state == "79"
Beispiel #39
0
async def test_async_setup_entry_default(hass):
    """Test async_setup_entry."""
    udn = 'uuid:device_1'
    entry = MockConfigEntry(domain=upnp.DOMAIN, data={
        'ssdp_description': 'http://192.168.1.1/desc.xml',
        'udn': udn,
        'sensors': True,
        'port_mapping': False,
    })

    config = {
        'http': {},
        'discovery': {},
        # no upnp
    }
    with MockDependency('netdisco.discovery'), \
        patch('homeassistant.components.upnp.config_flow.get_local_ip',
              return_value='192.168.1.10'):
        await async_setup_component(hass, 'http', config)
        await async_setup_component(hass, 'upnp', config)
        await hass.async_block_till_done()

    # mock homeassistant.components.upnp.device.Device
    mock_device = MockDevice(udn)
    with patch.object(Device, 'async_create_device') as create_device:
        create_device.return_value = mock_coro(return_value=mock_device)
        with patch('homeassistant.components.upnp.config_flow.get_local_ip',
                   return_value='192.168.1.10'):
            assert await upnp.async_setup_entry(hass, entry) is True

            # ensure device is stored/used
            assert hass.data[upnp.DOMAIN]['devices'][udn] == mock_device

            hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
            await hass.async_block_till_done()

    # ensure no port-mappings created or removed
    assert not mock_device.added_port_mappings
    assert not mock_device.removed_port_mappings
async def test_creating_entry_tries_discover(hass):
    """Test setting up does discovery."""
    with patch(
            "homeassistant.components.tplink.async_setup_entry",
            return_value=mock_coro(True),
    ) as mock_setup, patch(
            "homeassistant.components.tplink.common.Discover.discover",
            return_value={"host": 1234},
    ):
        result = await hass.config_entries.flow.async_init(
            tplink.DOMAIN, context={"source": config_entries.SOURCE_USER})

        # Confirmation form
        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM

        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {})
        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY

        await hass.async_block_till_done()

    assert len(mock_setup.mock_calls) == 1
Beispiel #41
0
async def test_async_update(hass):
    """Ensure we can update sensors."""
    await setup_awair(hass)

    future = NOW + timedelta(minutes=10)
    data_patch = patch(
        "python_awair.AwairClient.air_data_latest",
        return_value=mock_coro(AIR_DATA_FIXTURE_UPDATED),
    )

    with data_patch, alter_time(future):
        async_fire_time_changed(hass, future)
        await hass.async_block_till_done()

    score_sensor = hass.states.get("sensor.awair_score")
    assert score_sensor.state == "79"

    assert hass.states.get("sensor.awair_temperature").state == "23.4"
    assert hass.states.get("sensor.awair_humidity").state == "33.7"
    assert hass.states.get("sensor.awair_co2").state == "613"
    assert hass.states.get("sensor.awair_voc").state == "1013"
    assert hass.states.get("sensor.awair_pm2_5").state == "7.2"
Beispiel #42
0
async def mock_discovery(hass, discoveries, config=BASE_CONFIG):
    """Mock discoveries."""
    with patch("homeassistant.components.zeroconf.async_get_instance"), patch(
            "homeassistant.components.zeroconf.async_setup",
            return_value=True), patch.object(
                discovery, "_discover", discoveries), patch(
                    "homeassistant.components.discovery.async_discover"
                ) as mock_discover, patch(
                    "homeassistant.components.discovery.async_load_platform",
                    return_value=mock_coro(),
                ) as mock_platform:
        assert await async_setup_component(hass, "discovery", config)
        await hass.async_block_till_done()
        await hass.async_start()
        hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
        await hass.async_block_till_done()
        async_fire_time_changed(hass, utcnow())
        # Work around an issue where our loop.call_soon not get caught
        await hass.async_block_till_done()
        await hass.async_block_till_done()

    return mock_discover, mock_platform
Beispiel #43
0
async def test_is_dimmable(hass):
    """Test that is_dimmable switches are correctly added as lights."""
    with patch(
        "homeassistant.components.tplink.common.Discover.discover"
    ) as discover, patch(
        "homeassistant.components.tplink.light.async_setup_entry",
        return_value=mock_coro(True),
    ) as setup, patch(
        "homeassistant.components.tplink.common.SmartDevice._query_helper"
    ), patch(
        "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True
    ):
        dimmable_switch = SmartPlug("123.123.123.123")
        discover.return_value = {"host": dimmable_switch}

        await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
        await hass.async_block_till_done()

    assert len(discover.mock_calls) == 1
    assert len(setup.mock_calls) == 1
    assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1
    assert not hass.data[tplink.DOMAIN][CONF_SWITCH]
Beispiel #44
0
async def test_detect_location_info_ip_api(aioclient_mock, session):
    """Test detect location info using ip-api.com."""
    aioclient_mock.get(location_util.IP_API,
                       text=load_fixture("ip-api.com.json"))

    with patch("homeassistant.util.location._get_ipapi",
               return_value=mock_coro(None)):
        info = await location_util.async_detect_location_info(session,
                                                              _test_real=True)

    assert info is not None
    assert info.ip == "1.2.3.4"
    assert info.country_code == "US"
    assert info.country_name == "United States"
    assert info.region_code == "CA"
    assert info.region_name == "California"
    assert info.city == "San Diego"
    assert info.zip_code == "92122"
    assert info.time_zone == "America/Los_Angeles"
    assert info.latitude == 32.8594
    assert info.longitude == -117.2073
    assert not info.use_metric
Beispiel #45
0
async def get_mock_hap(
    hass: HomeAssistantType,
    mock_connection,
    hmip_config_entry: config_entries.ConfigEntry,
) -> hmip_hap.HomematicipHAP:
    """Create a mocked homematic access point."""
    hass.config.components.add(HMIPC_DOMAIN)
    hap = hmip_hap.HomematicipHAP(hass, hmip_config_entry)
    home_name = hmip_config_entry.data["name"]
    mock_home = (HomeTemplate(
        connection=mock_connection,
        home_name=home_name).init_home().get_async_home_mock())
    with patch.object(hap, "get_hap", return_value=mock_coro(mock_home)):
        assert await hap.async_setup()
    mock_home.on_update(hap.async_update)
    mock_home.on_create(hap.async_create_entity)

    hass.data[HMIPC_DOMAIN] = {HAPID: hap}

    await hass.async_block_till_done()

    return hap
Beispiel #46
0
async def test_constructor_loads_info_from_config(hass):
    """Test non-dev mode loads info from SERVERS constant."""
    with patch("hass_nabucasa.Cloud.start", return_value=mock_coro()):
        result = await async_setup_component(
            hass, 'cloud', {
                'http': {},
                'cloud': {
                    cloud.CONF_MODE: cloud.MODE_DEV,
                    'cognito_client_id': 'test-cognito_client_id',
                    'user_pool_id': 'test-user_pool_id',
                    'region': 'test-region',
                    'relayer': 'test-relayer',
                }
            })
        assert result

    cl = hass.data['cloud']
    assert cl.mode == cloud.MODE_DEV
    assert cl.cognito_client_id == 'test-cognito_client_id'
    assert cl.user_pool_id == 'test-user_pool_id'
    assert cl.region == 'test-region'
    assert cl.relayer == 'test-relayer'
Beispiel #47
0
async def test_initialize_loads_info(mock_os, hass):
    """Test initialize will load info from config file."""
    mock_os.path.isfile.return_value = True
    mopen = mock_open(
        read_data=json.dumps({
            'id_token': 'test-id-token',
            'access_token': 'test-access-token',
            'refresh_token': 'test-refresh-token',
        }))

    cl = cloud.Cloud(hass, cloud.MODE_DEV, None, None)
    cl.iot = MagicMock()
    cl.iot.connect.return_value = mock_coro()

    with patch('homeassistant.components.cloud.open', mopen, create=True), \
            patch('homeassistant.components.cloud.Cloud._decode_claims'):
        await cl.async_start(None)

    assert cl.id_token == 'test-id-token'
    assert cl.access_token == 'test-access-token'
    assert cl.refresh_token == 'test-refresh-token'
    assert len(cl.iot.connect.mock_calls) == 1
Beispiel #48
0
async def test_disabling_webhook(hass, hass_ws_client, setup_api):
    """Test we call right code to disable webhooks."""
    hass.data[DOMAIN].id_token = jwt.encode(
        {
            'email': '*****@*****.**',
            'custom:sub-exp': '2018-01-03'
        }, 'test')
    client = await hass_ws_client(hass)
    with patch(
            'homeassistant.components.cloud.cloudhooks.Cloudhooks'
            '.async_delete',
            return_value=mock_coro()) as mock_disable:
        await client.send_json({
            'id': 5,
            'type': 'cloud/cloudhook/delete',
            'webhook_id': 'mock-webhook-id',
        })
        response = await client.receive_json()
    assert response['success']

    assert len(mock_disable.mock_calls) == 1
    assert mock_disable.mock_calls[0][1][0] == 'mock-webhook-id'
Beispiel #49
0
async def test_device_tracker_hostname_and_macaddress_exists_before_start(
        hass):
    """Test matching based on hostname and macaddress before start."""
    hass.states.async_set(
        "device_tracker.august_connect",
        STATE_HOME,
        {
            ATTR_HOST_NAME: "connect",
            ATTR_IP: "192.168.210.56",
            ATTR_SOURCE_TYPE: SOURCE_TYPE_ROUTER,
            ATTR_MAC: "B8:B7:F1:6D:B5:33",
        },
    )

    with patch.object(hass.config_entries.flow,
                      "async_init",
                      return_value=mock_coro()) as mock_init:
        device_tracker_watcher = dhcp.DeviceTrackerWatcher(
            hass,
            {},
            [{
                "domain": "mock-domain",
                "hostname": "connect",
                "macaddress": "B8B7F1*"
            }],
        )
        device_tracker_watcher.async_start()
        await hass.async_block_till_done()
        device_tracker_watcher.async_stop()
        await hass.async_block_till_done()

    assert len(mock_init.mock_calls) == 1
    assert mock_init.mock_calls[0][1][0] == "mock-domain"
    assert mock_init.mock_calls[0][2]["context"] == {"source": "dhcp"}
    assert mock_init.mock_calls[0][2]["data"] == {
        dhcp.IP_ADDRESS: "192.168.210.56",
        dhcp.HOSTNAME: "connect",
        dhcp.MAC_ADDRESS: "b8b7f16db533",
    }
Beispiel #50
0
async def test_hassio_addon_panel_startup(hass, aioclient_mock, hassio_env):
    """Test startup and panel setup after event."""
    aioclient_mock.get(
        "http://127.0.0.1/ingress/panels", json={
            'result': 'ok', 'data': {'panels': {
                "test1": {
                    "enable": True,
                    "title": "Test",
                    "icon": "mdi:test",
                    "admin": False
                },
                "test2": {
                    "enable": False,
                    "title": "Test 2",
                    "icon": "mdi:test2",
                    "admin": True
                },
            }}})

    assert aioclient_mock.call_count == 0

    with patch(
            'homeassistant.components.hassio.addon_panel._register_panel',
            Mock(return_value=mock_coro())
    ) as mock_panel:
        await async_setup_component(hass, 'hassio', {
            'http': {
                'api_password': API_PASSWORD
            }
        })
        await hass.async_block_till_done()

        assert aioclient_mock.call_count == 2
        assert mock_panel.called
        mock_panel.assert_called_with(
            hass, 'test1', {
                'enable': True, 'title': 'Test',
                'icon': 'mdi:test', 'admin': False
            })
async def test_scan_not_all_match(hass, aioclient_mock):
    """Test match fails if some specified attribute values differ."""
    aioclient_mock.get(
        "http://1.1.1.1",
        text="""
<root>
  <device>
    <deviceType>Paulus</deviceType>
    <manufacturer>Paulus</manufacturer>
  </device>
</root>
    """,
    )
    scanner = ssdp.Scanner(
        hass,
        {
            "mock-domain": [
                {
                    ssdp.ATTR_UPNP_DEVICE_TYPE: "Paulus",
                    ssdp.ATTR_UPNP_MANUFACTURER: "Not-Paulus",
                }
            ]
        },
    )

    async def _inject_entry(*args, **kwargs):
        scanner.async_store_entry(
            Mock(st="mock-st", location="http://1.1.1.1", values={})
        )

    with patch(
        "homeassistant.components.ssdp.async_search",
        side_effect=_inject_entry,
    ), patch.object(
        hass.config_entries.flow, "async_init", return_value=mock_coro()
    ) as mock_init:
        await scanner.async_scan(None)

    assert not mock_init.mock_calls
Beispiel #52
0
async def test_controller_fail_setup(hass):
    """Test that a failed setup still stores controller."""
    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_cntrlr:
        mock_cntrlr.return_value.async_setup.return_value = mock_coro(False)
        assert await unifi.async_setup_entry(hass, entry) is False

    controller_id = unifi.CONTROLLER_ID.format(host='0.0.0.0', site='default')
    assert controller_id in hass.data[unifi.DOMAIN]
Beispiel #53
0
async def test_discovery_connection(hass, mock_auth, mock_entry_setup):
    """Test a connection via discovery."""
    mock_auth.side_effect = lambda hass, host, code: mock_coro(
        {"host": host, "gateway_id": "bla"}
    )

    flow = await hass.config_entries.flow.async_init(
        "tradfri", context={"source": "zeroconf"}, data={"host": "123.123.123.123"}
    )

    result = await hass.config_entries.flow.async_configure(
        flow["flow_id"], {"security_code": "abcd"}
    )

    assert len(mock_entry_setup.mock_calls) == 1

    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["result"].data == {
        "host": "123.123.123.123",
        "gateway_id": "bla",
        "import_groups": False,
    }
async def test_device_unavailable(hass):
    """Successful setup."""
    entry = MockConfigEntry(domain=device.DOMAIN,
                            data=ENTRY_CONFIG,
                            options=ENTRY_OPTIONS)

    api = Mock()
    api.vapix.get_param.return_value = "1234"

    axis_device = device.AxisNetworkDevice(hass, entry)
    hass.data[device.DOMAIN] = {axis_device.serial: axis_device}

    with patch.object(device, "get_device",
                      return_value=mock_coro(api)), patch.object(
                          device, "async_dispatcher_send") as mock_dispatcher:
        await axis_device.async_setup()
        await hass.async_block_till_done()

        axis_device.async_connection_status_callback(status=False)

    assert not axis_device.available
    assert len(mock_dispatcher.mock_calls) == 1
Beispiel #55
0
async def test_setup_setup_cloud_user(hass, hass_storage):
    """Test setup with API push default data."""
    hass_storage[STORAGE_KEY] = {'version': 1, 'data': {'cloud_user': None}}
    with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
        result = await async_setup_component(
            hass, 'cloud', {
                'http': {},
                'cloud': {
                    cloud.CONF_MODE: cloud.MODE_DEV,
                    'cognito_client_id': 'test-cognito_client_id',
                    'user_pool_id': 'test-user_pool_id',
                    'region': 'test-region',
                    'relayer': 'test-relayer',
                }
            })
        assert result

    cloud_user = await hass.auth.async_get_user(
        hass_storage[STORAGE_KEY]['data']['cloud_user'])

    assert cloud_user
    assert cloud_user.groups[0].id == GROUP_ID_ADMIN
Beispiel #56
0
async def test_setup_existing_cloud_user(hass, hass_storage):
    """Test setup with API push default data."""
    user = await hass.auth.async_create_system_user("Cloud test")
    hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": user.id}}
    with patch("hass_nabucasa.Cloud.start", return_value=mock_coro()):
        result = await async_setup_component(
            hass,
            "cloud",
            {
                "http": {},
                "cloud": {
                    cloud.CONF_MODE: cloud.MODE_DEV,
                    "cognito_client_id": "test-cognito_client_id",
                    "user_pool_id": "test-user_pool_id",
                    "region": "test-region",
                    "relayer": "test-relayer",
                },
            },
        )
        assert result

    assert hass_storage[STORAGE_KEY]["data"]["cloud_user"] == user.id
Beispiel #57
0
async def test_update_alarm_device(hass):
    """Test that alarm panel state changes on incoming websocket data."""
    import pyspcwebgw
    from pyspcwebgw.const import AreaMode

    config = {
        'spc': {
            'api_url': 'http://localhost/',
            'ws_url': 'ws://localhost/'
        }
    }

    area_mock = Mock(spec=pyspcwebgw.area.Area,
                     id='1',
                     mode=AreaMode.FULL_SET,
                     last_changed_by='Sven')
    area_mock.name = 'House'
    area_mock.verified_alarm = False

    with patch('pyspcwebgw.SpcWebGateway.areas',
               new_callable=PropertyMock) as mock_areas:
        mock_areas.return_value = {'1': area_mock}
        with patch('pyspcwebgw.SpcWebGateway.async_load_parameters',
                   return_value=mock_coro(True)):
            assert await async_setup_component(hass, 'spc', config) is True

    await hass.async_block_till_done()
    entity_id = 'alarm_control_panel.house'

    assert hass.states.get(entity_id).state == STATE_ALARM_ARMED_AWAY
    assert hass.states.get(entity_id).attributes['changed_by'] == 'Sven'

    area_mock.mode = AreaMode.UNSET
    area_mock.last_changed_by = 'Anna'
    await hass.data[DATA_API]._async_callback(area_mock)
    await hass.async_block_till_done()

    assert hass.states.get(entity_id).state == STATE_ALARM_DISARMED
    assert hass.states.get(entity_id).attributes['changed_by'] == 'Anna'
Beispiel #58
0
async def test_user_login_connection_error(hass, mock_api_connection_error,
                                           mock_client):
    """Test user step with connection error during login phase."""
    flow = config_flow.EsphomeFlowHandler()
    flow.hass = hass
    await flow.async_step_user(user_input=None)

    mock_client.device_info.return_value = mock_coro(
        MockDeviceInfo(True, "test"))

    await flow.async_step_user(user_input={
        'host': '127.0.0.1',
        'port': 6053,
    })

    mock_client.connect.side_effect = mock_api_connection_error
    result = await flow.async_step_authenticate(
        user_input={'password': '******'})

    assert result['type'] == 'form'
    assert result['step_id'] == 'authenticate'
    assert result['errors'] == {'base': 'connection_error'}
Beispiel #59
0
async def test_invalid_characters(hass, aioclient_mock):
    """Test that we replace bad characters with placeholders."""
    aioclient_mock.get(
        "http://1.1.1.1",
        text="""
<root>
  <device>
    <deviceType>ABC</deviceType>
    <serialNumber>\xff\xff\xff\xff</serialNumber>
  </device>
</root>
    """,
    )
    scanner = ssdp.Scanner(
        hass,
        {"mock-domain": [{
            ssdp.ATTR_UPNP_DEVICE_TYPE: "ABC",
        }]},
    )

    with patch(
            "netdisco.ssdp.scan",
            return_value=[
                Mock(st="mock-st", location="http://1.1.1.1", values={})
            ],
    ), patch.object(hass.config_entries.flow,
                    "async_init",
                    return_value=mock_coro()) as mock_init:
        await scanner.async_scan(None)

    assert len(mock_init.mock_calls) == 1
    assert mock_init.mock_calls[0][1][0] == "mock-domain"
    assert mock_init.mock_calls[0][2]["context"] == {"source": "ssdp"}
    assert mock_init.mock_calls[0][2]["data"] == {
        "ssdp_location": "http://1.1.1.1",
        "ssdp_st": "mock-st",
        "deviceType": "ABC",
        "serialNumber": "ÿÿÿÿ",
    }
Beispiel #60
0
async def test_sending_mqtt_commands_and_optimistic(hass, mock_publish):
    """Test the sending MQTT commands in optimistic mode."""
    fake_state = ha.State('switch.test', 'on')

    with patch('homeassistant.helpers.restore_state.RestoreEntity'
               '.async_get_last_state',
               return_value=mock_coro(fake_state)):
        assert await async_setup_component(hass, switch.DOMAIN, {
            switch.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'command_topic': 'command-topic',
                'payload_on': 'beer on',
                'payload_off': 'beer off',
                'qos': '2'
            }
        })

    state = hass.states.get('switch.test')
    assert STATE_ON == state.state
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    common.turn_on(hass, 'switch.test')
    await hass.async_block_till_done()

    mock_publish.async_publish.assert_called_once_with(
        'command-topic', 'beer on', 2, False)
    mock_publish.async_publish.reset_mock()
    state = hass.states.get('switch.test')
    assert STATE_ON == state.state

    common.turn_off(hass, 'switch.test')
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    mock_publish.async_publish.assert_called_once_with(
        'command-topic', 'beer off', 2, False)
    state = hass.states.get('switch.test')
    assert STATE_OFF == state.state