示例#1
0
def melissa_mock():
    """Use this to mock the melissa api."""
    api = Mock()
    api.async_fetch_devices = mock_coro_func(
        return_value=json.loads(load_fixture('melissa_fetch_devices.json')))
    api.async_status = mock_coro_func(return_value=json.loads(load_fixture(
        'melissa_status.json')))
    api.async_cur_settings = mock_coro_func(
        return_value=json.loads(load_fixture('melissa_cur_settings.json')))

    api.async_send = mock_coro_func(return_value=True)

    api.STATE_OFF = 0
    api.STATE_ON = 1
    api.STATE_IDLE = 2

    api.MODE_AUTO = 0
    api.MODE_FAN = 1
    api.MODE_HEAT = 2
    api.MODE_COOL = 3
    api.MODE_DRY = 4

    api.FAN_AUTO = 0
    api.FAN_LOW = 1
    api.FAN_MEDIUM = 2
    api.FAN_HIGH = 3

    api.STATE = 'state'
    api.MODE = 'mode'
    api.FAN = 'fan'
    api.TEMP = 'temp'
    return api
示例#2
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = Mock()
    entry.data = {
        emulated_roku.CONF_NAME: 'Emulated Roku Test',
        emulated_roku.CONF_LISTEN_PORT: 8060,
        emulated_roku.CONF_HOST_IP: '1.2.3.5',
        emulated_roku.CONF_ADVERTISE_IP: '1.2.3.4',
        emulated_roku.CONF_ADVERTISE_PORT: 8071,
        emulated_roku.CONF_UPNP_BIND_MULTICAST: False
    }

    with patch('emulated_roku.EmulatedRokuServer',
               return_value=Mock(start=mock_coro_func(),
                                 close=mock_coro_func())) as instantiate:
        assert await emulated_roku.async_setup_entry(hass, entry) is True

    assert len(instantiate.mock_calls) == 1
    assert hass.data[emulated_roku.DOMAIN]

    roku_instance = hass.data[emulated_roku.DOMAIN]['Emulated Roku Test']

    assert roku_instance.roku_usn == 'Emulated Roku Test'
    assert roku_instance.host_ip == '1.2.3.5'
    assert roku_instance.listen_port == 8060
    assert roku_instance.advertise_ip == '1.2.3.4'
    assert roku_instance.advertise_port == 8071
    assert roku_instance.bind_multicast is False
示例#3
0
    def instantiate(loop, handler,
                    roku_usn, host_ip, listen_port,
                    advertise_ip=None, advertise_port=None,
                    bind_multicast=None):
        nonlocal roku_event_handler
        roku_event_handler = handler

        return Mock(start=mock_coro_func(), close=mock_coro_func())
示例#4
0
def melissa_mock():
    """Use this to mock the melissa api."""
    api = Mock()
    api.async_fetch_devices = mock_coro_func(
        return_value=json.loads(load_fixture('melissa_fetch_devices.json')))
    api.async_status = mock_coro_func(return_value=json.loads(load_fixture(
        'melissa_status.json'
    )))

    api.TEMP = 'temp'
    api.HUMIDITY = 'humidity'
    return api
示例#5
0
async def test_config_required_fields(hass):
    """Test that configuration is successful with required fields."""
    with patch.object(emulated_roku, 'configured_servers', return_value=[]), \
            patch('emulated_roku.EmulatedRokuServer',
                  return_value=Mock(start=mock_coro_func(),
                                    close=mock_coro_func())):
        assert await async_setup_component(hass, emulated_roku.DOMAIN, {
            emulated_roku.DOMAIN: {
                emulated_roku.CONF_SERVERS: [{
                    emulated_roku.CONF_NAME: 'Emulated Roku Test',
                    emulated_roku.CONF_LISTEN_PORT: 8060
                }]
            }
        }) is True
示例#6
0
async def test_get_scanner_with_password_no_pubkey(hass):
    """Test creating an AsusWRT scanner with a password and no pubkey."""
    with MockDependency('aioasuswrt.asuswrt')as mocked_asus:
        mocked_asus.AsusWrt().connection.async_connect = mock_coro_func()
        mocked_asus.AsusWrt(
        ).connection.async_get_connected_devices = mock_coro_func(
            return_value={})
        result = await async_setup_component(
            hass, DOMAIN, {DOMAIN: {
                CONF_HOST: 'fake_host',
                CONF_USERNAME: '******',
                CONF_PASSWORD: '******'
            }})
        assert result
        assert hass.data[DATA_ASUSWRT] is not None
示例#7
0
async def test_handling_service_not_found(mock_request):
    """Test handling unauth exceptions."""
    with pytest.raises(HTTPInternalServerError):
        await request_handler_factory(
            Mock(requires_auth=False),
            mock_coro_func(exception=ServiceNotFound('test', 'test'))
        )(mock_request)
def test_create_account(hass, client):
    """Test a flow that creates an account."""
    set_component(
        hass, 'test',
        MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_create_entry(
                title='Test Entry',
                data={'secret': 'account_token'}
            )

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post('/api/config/config_entries/flow',
                                      json={'handler': 'test'})

    assert resp.status == 200
    data = yield from resp.json()
    data.pop('flow_id')
    assert data == {
        'handler': 'test',
        'title': 'Test Entry',
        'type': 'create_entry',
        'version': 1,
        'description': None,
        'description_placeholders': None,
    }
示例#9
0
async def test_handling_unauthorized(mock_request):
    """Test handling unauth exceptions."""
    with pytest.raises(HTTPUnauthorized):
        await request_handler_factory(
            Mock(requires_auth=False),
            mock_coro_func(exception=Unauthorized)
        )(mock_request)
示例#10
0
async def test_handling_invalid_data(mock_request):
    """Test handling unauth exceptions."""
    with pytest.raises(HTTPBadRequest):
        await request_handler_factory(
            Mock(requires_auth=False),
            mock_coro_func(exception=vol.Invalid('yo'))
        )(mock_request)
def test_two_step_flow(hass, client):
    """Test we can finish a two step flow."""
    set_component(
        hass, 'test',
        MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_show_form(
                step_id='account',
                data_schema=vol.Schema({
                    'user_title': str
                }))

        @asyncio.coroutine
        def async_step_account(self, user_input=None):
            return self.async_create_entry(
                title=user_input['user_title'],
                data={'secret': 'account_token'}
            )

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post('/api/config/config_entries/flow',
                                      json={'handler': 'test'})
        assert resp.status == 200
        data = yield from resp.json()
        flow_id = data.pop('flow_id')
        assert data == {
            'type': 'form',
            'handler': 'test',
            'step_id': 'account',
            'data_schema': [
                {
                    'name': 'user_title',
                    'type': 'string'
                }
            ],
            'description_placeholders': None,
            'errors': None
        }

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post(
            '/api/config/config_entries/flow/{}'.format(flow_id),
            json={'user_title': 'user-title'})
        assert resp.status == 200
        data = yield from resp.json()
        data.pop('flow_id')
        assert data == {
            'handler': 'test',
            'type': 'create_entry',
            'title': 'user-title',
            'version': 1,
            'description': None,
            'description_placeholders': None,
        }
示例#12
0
def mock_bridge():
    """Mock the HueBridge from initializing."""
    with patch('homeassistant.components.hue._find_username_from_config',
               return_value=None), \
            patch('homeassistant.components.hue.HueBridge') as mock_bridge:
        mock_bridge().async_setup = mock_coro_func()
        mock_bridge.reset_mock()
        yield mock_bridge
示例#13
0
async def test_unload_entry(hass):
    """Test being able to unload an entry."""
    entry = Mock()
    entry.data = {'name': 'Emulated Roku Test', 'listen_port': 8060}

    with patch('emulated_roku.EmulatedRokuServer',
               return_value=Mock(start=mock_coro_func(),
                                 close=mock_coro_func())):
        assert await emulated_roku.async_setup_entry(hass, entry) is True

    assert emulated_roku.DOMAIN in hass.data

    await hass.async_block_till_done()

    assert await emulated_roku.async_unload_entry(hass, entry)

    assert len(hass.data[emulated_roku.DOMAIN]) == 0
示例#14
0
async def test_config_already_registered_not_configured(hass):
    """Test that an already registered name causes the entry to be ignored."""
    with patch('emulated_roku.EmulatedRokuServer',
               return_value=Mock(start=mock_coro_func(),
                                 close=mock_coro_func())) as instantiate, \
            patch.object(emulated_roku, 'configured_servers',
                         return_value=['Emulated Roku Test']):
        assert await async_setup_component(hass, emulated_roku.DOMAIN, {
            emulated_roku.DOMAIN: {
                emulated_roku.CONF_SERVERS: [{
                    emulated_roku.CONF_NAME: 'Emulated Roku Test',
                    emulated_roku.CONF_LISTEN_PORT: 8060
                }]
            }
        }) is True

    assert len(instantiate.mock_calls) == 0
示例#15
0
async def test_setup_platform(hass):
    """Test setup_platform."""
    with patch('homeassistant.components.melissa'):
        hass.data[DATA_MELISSA] = melissa_mock()

        config = {}
        async_add_entities = mock_coro_func()
        discovery_info = {}

        await melissa.async_setup_platform(
            hass, config, async_add_entities, discovery_info)
示例#16
0
async def test_password_or_pub_key_required(hass):
    """Test creating an AsusWRT scanner without a pass or pubkey."""
    with MockDependency('aioasuswrt.asuswrt')as mocked_asus:
        mocked_asus.AsusWrt().connection.async_connect = mock_coro_func()
        mocked_asus.AsusWrt().is_connected = False
        result = await async_setup_component(
            hass, DOMAIN, {DOMAIN: {
                CONF_HOST: 'fake_host',
                CONF_USERNAME: '******'
            }})
        assert not result
示例#17
0
async def test_update_keyerror(hass):
    """Test for faulty update."""
    with patch('homeassistant.components.melissa'):
        mocked_melissa = melissa_mock()
        device = (await mocked_melissa.async_fetch_devices())[_SERIAL]
        temp = MelissaTemperatureSensor(device, mocked_melissa)
        hum = MelissaHumiditySensor(device, mocked_melissa)
        mocked_melissa.async_status = mock_coro_func(return_value={})
        await temp.async_update()
        assert temp.state is None
        await hum.async_update()
        assert hum.state is None
示例#18
0
def test_two_step_flow(hass, client):
    """Test we can finish a two step flow."""
    set_component(hass, 'test',
                  MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_show_form(step_id='account',
                                        data_schema=vol.Schema(
                                            {'user_title': str}))

        @asyncio.coroutine
        def async_step_account(self, user_input=None):
            return self.async_create_entry(title=user_input['user_title'],
                                           data={'secret': 'account_token'})

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post('/api/config/config_entries/flow',
                                      json={'handler': 'test'})
        assert resp.status == 200
        data = yield from resp.json()
        flow_id = data.pop('flow_id')
        assert data == {
            'type': 'form',
            'handler': 'test',
            'step_id': 'account',
            'data_schema': [{
                'name': 'user_title',
                'type': 'string'
            }],
            'description_placeholders': None,
            'errors': None
        }

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post(
            '/api/config/config_entries/flow/{}'.format(flow_id),
            json={'user_title': 'user-title'})
        assert resp.status == 200
        data = yield from resp.json()
        data.pop('flow_id')
        assert data == {
            'handler': 'test',
            'type': 'create_entry',
            'title': 'user-title',
            'version': 1,
            'description': None,
            'description_placeholders': None,
        }
示例#19
0
async def test_setup(hass):
    """Test setting up the Melissa component."""
    with MockDependency("melissa") as mocked_melissa:
        melissa.melissa = mocked_melissa
        mocked_melissa.AsyncMelissa().async_connect = mock_coro_func()
        await melissa.async_setup(hass, VALID_CONFIG)

        mocked_melissa.AsyncMelissa.assert_called_with(username="******",
                                                       password="******")

        assert melissa.DATA_MELISSA in hass.data
        assert isinstance(hass.data[melissa.DATA_MELISSA],
                          type(mocked_melissa.AsyncMelissa()))
示例#20
0
async def test_network_unreachable(hass):
    """Test creating an AsusWRT scanner without a pass or pubkey."""
    with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt:
        AsusWrt().connection.async_connect = mock_coro_func(exception=OSError)
        AsusWrt().is_connected = False
        result = await async_setup_component(
            hass, DOMAIN,
            {DOMAIN: {
                CONF_HOST: "fake_host",
                CONF_USERNAME: "******"
            }})
        assert result
        assert hass.data.get(DATA_ASUSWRT) is None
async def test_continue_flow_unauth(hass, client, hass_admin_user):
    """Test we can't finish a two step flow."""
    mock_integration(
        hass,
        MockModule('test', async_setup_entry=mock_coro_func(True)))
    mock_entity_platform(hass, 'config_flow.test', None)

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_show_form(
                step_id='account',
                data_schema=vol.Schema({
                    'user_title': str
                }))

        @asyncio.coroutine
        def async_step_account(self, user_input=None):
            return self.async_create_entry(
                title=user_input['user_title'],
                data={'secret': 'account_token'},
            )

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = await client.post('/api/config/config_entries/flow',
                                 json={'handler': 'test'})
        assert resp.status == 200
        data = await resp.json()
        flow_id = data.pop('flow_id')
        assert data == {
            'type': 'form',
            'handler': 'test',
            'step_id': 'account',
            'data_schema': [
                {
                    'name': 'user_title',
                    'type': 'string'
                }
            ],
            'description_placeholders': None,
            'errors': None
        }

    hass_admin_user.groups = []

    resp = await client.post(
        '/api/config/config_entries/flow/{}'.format(flow_id),
        json={'user_title': 'user-title'})
    assert resp.status == 401
示例#22
0
async def test_update_person_when_user_removed(hass, hass_read_only_user):
    """Update person when user is removed."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    person = await manager.async_create_person(
        name='Hello',
        user_id=hass_read_only_user.id
    )

    await hass.auth.async_remove_user(hass_read_only_user)
    await hass.async_block_till_done()
    assert person['user_id'] is None
async def test_password_or_pub_key_required(hass):
    """Test creating an AsusWRT scanner without a pass or pubkey."""
    with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt:
        AsusWrt().connection.async_connect = mock_coro_func()
        AsusWrt().is_connected = False
        result = await async_setup_component(
            hass,
            DOMAIN,
            {DOMAIN: {
                CONF_HOST: "fake_host",
                CONF_USERNAME: "******"
            }},
        )
        assert not result
示例#24
0
async def test_update_person_when_user_removed(hass, hass_read_only_user):
    """Update person when user is removed."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    person = await manager.async_create_person(
        name='Hello',
        user_id=hass_read_only_user.id
    )

    await hass.auth.async_remove_user(hass_read_only_user)
    await hass.async_block_till_done()
    assert person['user_id'] is None
示例#25
0
async def test_config_already_registered_not_configured(hass):
    """Test that an already registered name causes the entry to be ignored."""
    with patch(
            "emulated_roku.EmulatedRokuServer",
            return_value=Mock(start=mock_coro_func(), close=mock_coro_func()),
    ) as instantiate, patch.object(emulated_roku,
                                   "configured_servers",
                                   return_value=["Emulated Roku Test"]):
        assert (await async_setup_component(
            hass,
            emulated_roku.DOMAIN,
            {
                emulated_roku.DOMAIN: {
                    emulated_roku.CONF_SERVERS:
                    [{
                        emulated_roku.CONF_NAME: "Emulated Roku Test",
                        emulated_roku.CONF_LISTEN_PORT: 8060,
                    }]
                }
            },
        ) is True)

    assert len(instantiate.mock_calls) == 0
示例#26
0
async def test_update_invalid_user_id(hass):
    """Test updating to invalid user ID."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    person = await manager.async_create_person(
        name='Hello',
    )

    with pytest.raises(ValueError):
        await manager.async_update_person(
            person_id=person['id'],
            user_id='non-existing'
        )
示例#27
0
async def test_update(hass):
    """Test update."""
    with patch("homeassistant.components.melissa.climate._LOGGER.warning"
               ) as mocked_warning:
        with patch("homeassistant.components.melissa"):
            api = melissa_mock()
            device = (await api.async_fetch_devices())[_SERIAL]
            thermostat = MelissaClimate(api, _SERIAL, device)
            await thermostat.async_update()
            assert SPEED_LOW == thermostat.fan_mode
            assert HVAC_MODE_HEAT == thermostat.state
            api.async_status = mock_coro_func(exception=KeyError("boom"))
            await thermostat.async_update()
            mocked_warning.assert_called_once_with(
                "Unable to update entity %s", thermostat.entity_id)
示例#28
0
async def test_update_invalid_user_id(hass):
    """Test updating to invalid user ID."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    person = await manager.async_create_person(
        name='Hello',
    )

    with pytest.raises(ValueError):
        await manager.async_update_person(
            person_id=person['id'],
            user_id='non-existing'
        )
示例#29
0
async def test_update(hass):
    """Test update."""
    with patch('homeassistant.components.melissa'):
        with patch('homeassistant.components.climate.melissa._LOGGER.warning'
                   ) as mocked_warning:
            api = melissa_mock()
            device = (await api.async_fetch_devices())[_SERIAL]
            thermostat = MelissaClimate(api, _SERIAL, device)
            await thermostat.async_update()
            assert SPEED_LOW == thermostat.current_fan_mode
            assert STATE_HEAT == thermostat.current_operation
            api.async_status = mock_coro_func(exception=KeyError('boom'))
            await thermostat.async_update()
            mocked_warning.assert_called_once_with(
                'Unable to update entity %s', thermostat.entity_id)
示例#30
0
async def test_update(hass):
    """Test update."""
    with patch('homeassistant.components.melissa'):
        with patch('homeassistant.components.climate.melissa._LOGGER.warning'
                   ) as mocked_warning:
            api = melissa_mock()
            device = (await api.async_fetch_devices())[_SERIAL]
            thermostat = MelissaClimate(api, _SERIAL, device)
            await thermostat.async_update()
            assert SPEED_LOW == thermostat.current_fan_mode
            assert STATE_HEAT == thermostat.current_operation
            api.async_status = mock_coro_func(exception=KeyError('boom'))
            await thermostat.async_update()
            mocked_warning.assert_called_once_with(
                'Unable to update entity %s', thermostat.entity_id)
示例#31
0
async def test_create_duplicate_user_id(hass, hass_admin_user):
    """Test we do not allow duplicate user ID during creation."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    await manager.async_create_person(
        name='Hello',
        user_id=hass_admin_user.id
    )

    with pytest.raises(ValueError):
        await manager.async_create_person(
            name='Hello',
            user_id=hass_admin_user.id
        )
示例#32
0
async def test_create_duplicate_user_id(hass, hass_admin_user):
    """Test we do not allow duplicate user ID during creation."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    await manager.async_create_person(
        name='Hello',
        user_id=hass_admin_user.id
    )

    with pytest.raises(ValueError):
        await manager.async_create_person(
            name='Hello',
            user_id=hass_admin_user.id
        )
示例#33
0
async def test_send(hass):
    """Test send."""
    with patch('homeassistant.components.melissa'):
        api = melissa_mock()
        device = (await api.async_fetch_devices())[_SERIAL]
        thermostat = MelissaClimate(api, _SERIAL, device)
        await thermostat.async_update()
        await hass.async_block_till_done()
        await thermostat.async_send({'fan': api.FAN_MEDIUM})
        await hass.async_block_till_done()
        assert SPEED_MEDIUM == thermostat.current_fan_mode
        api.async_send.return_value = mock_coro_func(return_value=False)
        thermostat._cur_settings = None
        await thermostat.async_send({'fan': api.FAN_LOW})
        await hass.async_block_till_done()
        assert SPEED_LOW != thermostat.current_fan_mode
        assert thermostat._cur_settings is None
示例#34
0
async def test_send(hass):
    """Test send."""
    with patch('homeassistant.components.melissa'):
        api = melissa_mock()
        device = (await api.async_fetch_devices())[_SERIAL]
        thermostat = MelissaClimate(api, _SERIAL, device)
        await thermostat.async_update()
        await hass.async_block_till_done()
        await thermostat.async_send({'fan': api.FAN_MEDIUM})
        await hass.async_block_till_done()
        assert SPEED_MEDIUM == thermostat.current_fan_mode
        api.async_send.return_value = mock_coro_func(return_value=False)
        thermostat._cur_settings = None
        await thermostat.async_send({'fan': api.FAN_LOW})
        await hass.async_block_till_done()
        assert SPEED_LOW != thermostat.current_fan_mode
        assert thermostat._cur_settings is None
async def test_continue_flow_unauth(hass, client, hass_admin_user):
    """Test we can't finish a two step flow."""
    mock_integration(
        hass, MockModule("test", async_setup_entry=mock_coro_func(True)))
    mock_entity_platform(hass, "config_flow.test", None)

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_show_form(step_id="account",
                                        data_schema=vol.Schema(
                                            {"user_title": str}))

        @asyncio.coroutine
        def async_step_account(self, user_input=None):
            return self.async_create_entry(title=user_input["user_title"],
                                           data={"secret": "account_token"})

    with patch.dict(HANDLERS, {"test": TestFlow}):
        resp = await client.post("/api/config/config_entries/flow",
                                 json={"handler": "test"})
        assert resp.status == 200
        data = await resp.json()
        flow_id = data.pop("flow_id")
        assert data == {
            "type": "form",
            "handler": "test",
            "step_id": "account",
            "data_schema": [{
                "name": "user_title",
                "type": "string"
            }],
            "description_placeholders": None,
            "errors": None,
        }

    hass_admin_user.groups = []

    resp = await client.post(
        "/api/config/config_entries/flow/{}".format(flow_id),
        json={"user_title": "user-title"},
    )
    assert resp.status == 401
async def test_specify_non_directory_path_for_dnsmasq(hass):
    """Test creating an AsusWRT scanner with a dnsmasq location which is not a valid directory."""
    with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt:
        AsusWrt().connection.async_connect = mock_coro_func()
        AsusWrt().is_connected = False
        result = await async_setup_component(
            hass,
            DOMAIN,
            {
                DOMAIN: {
                    CONF_HOST: "fake_host",
                    CONF_USERNAME: "******",
                    CONF_PASSWORD: "******",
                    CONF_DNSMASQ: "?non_directory?",
                }
            },
        )
        assert not result
示例#37
0
async def test_update_double_user_id(hass, hass_admin_user):
    """Test we do not allow double user ID during update."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    await manager.async_create_person(
        name='Hello',
        user_id=hass_admin_user.id
    )
    person = await manager.async_create_person(
        name='Hello',
    )

    with pytest.raises(ValueError):
        await manager.async_update_person(
            person_id=person['id'],
            user_id=hass_admin_user.id
        )
async def test_no_interface(hass):
    """Test creating an AsusWRT scanner using no interface."""
    with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt:
        AsusWrt().connection.async_connect = mock_coro_func()
        AsusWrt().is_connected = False
        result = await async_setup_component(
            hass,
            DOMAIN,
            {
                DOMAIN: {
                    CONF_HOST: "fake_host",
                    CONF_USERNAME: "******",
                    CONF_PASSWORD: "******",
                    CONF_DNSMASQ: "/",
                    CONF_INTERFACE: None,
                }
            },
        )
        assert not result
示例#39
0
async def test_update_double_user_id(hass, hass_admin_user):
    """Test we do not allow double user ID during update."""
    manager = PersonManager(
        hass, Mock(async_add_entities=mock_coro_func()), []
    )
    await manager.async_initialize()
    await manager.async_create_person(
        name='Hello',
        user_id=hass_admin_user.id
    )
    person = await manager.async_create_person(
        name='Hello',
    )

    with pytest.raises(ValueError):
        await manager.async_update_person(
            person_id=person['id'],
            user_id=hass_admin_user.id
        )
def test_create_account(hass, client):
    """Test a flow that creates an account."""
    mock_entity_platform(hass, 'config_flow.test', None)

    mock_integration(
        hass,
        MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        @asyncio.coroutine
        def async_step_user(self, user_input=None):
            return self.async_create_entry(
                title='Test Entry',
                data={'secret': 'account_token'}
            )

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = yield from client.post('/api/config/config_entries/flow',
                                      json={'handler': 'test'})

    assert resp.status == 200

    entries = hass.config_entries.async_entries('test')
    assert len(entries) == 1

    data = yield from resp.json()
    data.pop('flow_id')
    assert data == {
        'handler': 'test',
        'title': 'Test Entry',
        'type': 'create_entry',
        'version': 1,
        'result': entries[0].entry_id,
        'description': None,
        'description_placeholders': None,
    }
示例#41
0
async def test_hap_reset_unloads_entry_if_setup():
    """Test calling reset while the entry has been setup."""
    hass = Mock()
    entry = Mock()
    home = Mock()
    home.disable_events = mock_coro_func()
    entry.data = {
        hmipc.HMIPC_HAPID: "ABC123",
        hmipc.HMIPC_AUTHTOKEN: "123",
        hmipc.HMIPC_NAME: "hmip",
    }
    hap = hmipc.HomematicipHAP(hass, entry)
    with patch.object(hap, "get_hap", return_value=mock_coro(home)):
        assert await hap.async_setup() is True

    assert hap.home is home
    assert len(hass.services.async_register.mock_calls) == 0
    assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 8

    hass.config_entries.async_forward_entry_unload.return_value = mock_coro(True)
    await hap.async_reset()

    assert len(hass.config_entries.async_forward_entry_unload.mock_calls) == 8
示例#42
0
async def test_ignore_flow(hass, hass_ws_client):
    """Test we can ignore a flow."""
    assert await async_setup_component(hass, "config", {})
    mock_integration(hass, MockModule("test", async_setup_entry=mock_coro_func(True)))
    mock_entity_platform(hass, "config_flow.test", None)

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

        async def async_step_user(self, user_input=None):
            await self.async_set_unique_id("mock-unique-id")
            return self.async_show_form(step_id="account", data_schema=vol.Schema({}))

    ws_client = await hass_ws_client(hass)

    with patch.dict(HANDLERS, {"test": TestFlow}):
        result = await hass.config_entries.flow.async_init(
            "test", context={"source": "user"}
        )
        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM

        await ws_client.send_json(
            {
                "id": 5,
                "type": "config_entries/ignore_flow",
                "flow_id": result["flow_id"],
            }
        )
        response = await ws_client.receive_json()

        assert response["success"]

    assert len(hass.config_entries.flow.async_progress()) == 0

    entry = hass.config_entries.async_entries("test")[0]
    assert entry.source == "ignore"
    assert entry.unique_id == "mock-unique-id"
示例#43
0
async def test_hap_reset_unloads_entry_if_setup():
    """Test calling reset while the entry has been setup."""
    hass = Mock()
    entry = Mock()
    home = Mock()
    home.disable_events = mock_coro_func()
    entry.data = {
        hmipc.HMIPC_HAPID: 'ABC123',
        hmipc.HMIPC_AUTHTOKEN: '123',
        hmipc.HMIPC_NAME: 'hmip',
    }
    hap = hmipc.HomematicipHAP(hass, entry)
    with patch.object(hap, 'get_hap', return_value=mock_coro(home)):
        assert await hap.async_setup() is True

    assert hap.home is home
    assert len(hass.services.async_register.mock_calls) == 0
    assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 8

    hass.config_entries.async_forward_entry_unload.return_value = \
        mock_coro(True)
    await hap.async_reset()

    assert len(hass.config_entries.async_forward_entry_unload.mock_calls) == 8
示例#44
0
async def test_handling_unauthorized(mock_request):
    """Test handling unauth exceptions."""
    with pytest.raises(HTTPUnauthorized):
        await request_handler_factory(
            Mock(requires_auth=False),
            mock_coro_func(exception=Unauthorized))(mock_request)
示例#45
0
async def test_handling_invalid_data(mock_request):
    """Test handling unauth exceptions."""
    with pytest.raises(HTTPBadRequest):
        await request_handler_factory(
            Mock(requires_auth=False),
            mock_coro_func(exception=vol.Invalid("yo")))(mock_request)
示例#46
0
async def test_two_step_options_flow(hass, client):
    """Test we can finish a two step options flow."""
    mock_integration(hass, MockModule("test", async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        @staticmethod
        @callback
        def async_get_options_flow(config_entry):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                async def async_step_init(self, user_input=None):
                    return self.async_show_form(
                        step_id="finish", data_schema=vol.Schema({"enabled": bool})
                    )

                async def async_step_finish(self, user_input=None):
                    return self.async_create_entry(
                        title="Enable disable", data=user_input
                    )

            return OptionsFlowHandler()

    MockConfigEntry(
        domain="test",
        entry_id="test1",
        source="bla",
        connection_class=core_ce.CONN_CLASS_LOCAL_POLL,
    ).add_to_hass(hass)
    entry = hass.config_entries._entries[0]

    with patch.dict(HANDLERS, {"test": TestFlow}):
        url = "/api/config/config_entries/options/flow"
        resp = await client.post(url, json={"handler": entry.entry_id})

        assert resp.status == 200
        data = await resp.json()
        flow_id = data.pop("flow_id")
        assert data == {
            "type": "form",
            "handler": "test1",
            "step_id": "finish",
            "data_schema": [{"name": "enabled", "type": "boolean"}],
            "description_placeholders": None,
            "errors": None,
        }

    with patch.dict(HANDLERS, {"test": TestFlow}):
        resp = await client.post(
            f"/api/config/config_entries/options/flow/{flow_id}",
            json={"enabled": True},
        )
        assert resp.status == 200
        data = await resp.json()
        data.pop("flow_id")
        assert data == {
            "handler": "test1",
            "type": "create_entry",
            "title": "Enable disable",
            "version": 1,
            "description": None,
            "description_placeholders": None,
        }
async def test_two_step_options_flow(hass, client):
    """Test we can finish a two step options flow."""
    set_component(
        hass, 'test',
        MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        @staticmethod
        @callback
        def async_get_options_flow(config, options):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                def __init__(self, config, options):
                    self.config = config
                    self.options = options

                async def async_step_init(self, user_input=None):
                    return self.async_show_form(
                        step_id='finish',
                        data_schema=vol.Schema({
                            'enabled': bool
                        })
                    )

                async def async_step_finish(self, user_input=None):
                    return self.async_create_entry(
                        title='Enable disable',
                        data=user_input
                    )
            return OptionsFlowHandler(config, options)

    MockConfigEntry(
        domain='test',
        entry_id='test1',
        source='bla',
        connection_class=core_ce.CONN_CLASS_LOCAL_POLL,
    ).add_to_hass(hass)
    entry = hass.config_entries._entries[0]

    with patch.dict(HANDLERS, {'test': TestFlow}):
        url = '/api/config/config_entries/entry/option/flow'
        resp = await client.post(url, json={'handler': entry.entry_id})

        assert resp.status == 200
        data = await resp.json()
        flow_id = data.pop('flow_id')
        assert data == {
            'type': 'form',
            'handler': 'test1',
            'step_id': 'finish',
            'data_schema': [
                {
                    'name': 'enabled',
                    'type': 'boolean'
                }
            ],
            'description_placeholders': None,
            'errors': None
        }

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = await client.post(
            '/api/config/config_entries/options/flow/{}'.format(flow_id),
            json={'enabled': True})
        assert resp.status == 200
        data = await resp.json()
        data.pop('flow_id')
        assert data == {
            'handler': 'test1',
            'type': 'create_entry',
            'title': 'Enable disable',
            'version': 1,
            'description': None,
            'description_placeholders': None,
        }
示例#48
0
async def test_two_step_options_flow(hass, client):
    """Test we can finish a two step options flow."""
    mock_integration(
        hass, MockModule('test', async_setup_entry=mock_coro_func(True)))

    class TestFlow(core_ce.ConfigFlow):
        @staticmethod
        @callback
        def async_get_options_flow(config, options):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                def __init__(self, config, options):
                    self.config = config
                    self.options = options

                async def async_step_init(self, user_input=None):
                    return self.async_show_form(step_id='finish',
                                                data_schema=vol.Schema(
                                                    {'enabled': bool}))

                async def async_step_finish(self, user_input=None):
                    return self.async_create_entry(title='Enable disable',
                                                   data=user_input)

            return OptionsFlowHandler(config, options)

    MockConfigEntry(
        domain='test',
        entry_id='test1',
        source='bla',
        connection_class=core_ce.CONN_CLASS_LOCAL_POLL,
    ).add_to_hass(hass)
    entry = hass.config_entries._entries[0]

    with patch.dict(HANDLERS, {'test': TestFlow}):
        url = '/api/config/config_entries/entry/option/flow'
        resp = await client.post(url, json={'handler': entry.entry_id})

        assert resp.status == 200
        data = await resp.json()
        flow_id = data.pop('flow_id')
        assert data == {
            'type': 'form',
            'handler': 'test1',
            'step_id': 'finish',
            'data_schema': [{
                'name': 'enabled',
                'type': 'boolean'
            }],
            'description_placeholders': None,
            'errors': None
        }

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = await client.post(
            '/api/config/config_entries/options/flow/{}'.format(flow_id),
            json={'enabled': True})
        assert resp.status == 200
        data = await resp.json()
        data.pop('flow_id')
        assert data == {
            'handler': 'test1',
            'type': 'create_entry',
            'title': 'Enable disable',
            'version': 1,
            'description': None,
            'description_placeholders': None,
        }