Ejemplo n.º 1
0
async def test_additional_device(hass):
    """Test that Flow can configure another device."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    flow.creds = MOCK_CREDS
    manager = hass.config_entries

    # Mock existing entry.
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA)
    entry.add_to_manager(manager)
    # Check that only 1 entry exists
    assert len(manager.async_entries()) == 1

    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{'host-ip': MOCK_HOST},
                             {'host-ip': MOCK_HOST_ADDITIONAL}]), \
            patch('pyps4_homeassistant.Helper.link',
                  return_value=(True, True)):
        result = await flow.async_step_link(MOCK_CONFIG_ADDITIONAL)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert len(result['data']['devices']) == 1
    assert result['title'] == MOCK_TITLE

    # Add New Entry
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA)
    entry.add_to_manager(manager)

    # Check that there are 2 entries
    assert len(manager.async_entries()) == 2
Ejemplo n.º 2
0
async def test_entry_options(hass, manager):
    """Test that we can set options on an entry."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
        options=None
    )
    entry.add_to_manager(manager)

    class TestFlow:
        @staticmethod
        @callback
        def async_get_options_flow(config, options):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                def __init__(self, config, options):
                    pass
            return OptionsFlowHandler(config, options)

    config_entries.HANDLERS['test'] = TestFlow()
    flow = await manager.options._async_create_flow(
        entry.entry_id, context={'source': 'test'}, data=None)

    flow.handler = entry.entry_id  # Used to keep reference to config entry

    await manager.options._async_finish_flow(
        flow, {'data': {'second': True}})

    assert entry.data == {
        'first': True
    }

    assert entry.options == {
        'second': True
    }
Ejemplo n.º 3
0
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()] == []
Ejemplo n.º 4
0
async def test_additional_device(hass):
    """Test that Flow can configure another device."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    flow.creds = MOCK_CREDS
    manager = hass.config_entries

    # Mock existing entry.
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA)
    entry.add_to_manager(manager)
    # Check that only 1 entry exists
    assert len(manager.async_entries()) == 1

    with patch(
            "pyps4_2ndscreen.Helper.has_devices",
            return_value=[{
                "host-ip": MOCK_HOST
            }, {
                "host-ip": MOCK_HOST_ADDITIONAL
            }],
    ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)):
        result = await flow.async_step_link(MOCK_CONFIG_ADDITIONAL)
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["data"][CONF_TOKEN] == MOCK_CREDS
    assert len(result["data"]["devices"]) == 1
    assert result["title"] == MOCK_TITLE

    # Add New Entry
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA)
    entry.add_to_manager(manager)

    # Check that there are 2 entries
    assert len(manager.async_entries()) == 2
Ejemplo n.º 5
0
async def test_entry_options(hass, manager):
    """Test that we can set options on an entry."""
    entry = MockConfigEntry(domain="test", data={"first": True}, options=None)
    entry.add_to_manager(manager)

    class TestFlow:
        @staticmethod
        @callback
        def async_get_options_flow(config_entry):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                pass

            return OptionsFlowHandler()

    config_entries.HANDLERS["test"] = TestFlow()
    flow = await manager.options._async_create_flow(entry.entry_id,
                                                    context={"source": "test"},
                                                    data=None)

    flow.handler = entry.entry_id  # Used to keep reference to config entry

    await manager.options._async_finish_flow(flow, {"data": {"second": True}})

    assert entry.data == {"first": True}

    assert entry.options == {"second": True}
Ejemplo n.º 6
0
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())
    mock_integration(hass, 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()] == []
Ejemplo n.º 7
0
async def test_entry_options(hass, manager):
    """Test that we can set options on an entry."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
        options=None
    )
    entry.add_to_manager(manager)

    class TestFlow:
        @staticmethod
        @callback
        def async_get_options_flow(config, options):
            class OptionsFlowHandler(data_entry_flow.FlowHandler):
                def __init__(self, config, options):
                    pass
            return OptionsFlowHandler(config, options)

    config_entries.HANDLERS['test'] = TestFlow()
    flow = await manager.options._async_create_flow(
        entry.entry_id, context={'source': 'test'}, data=None)

    flow.handler = entry.entry_id  # Used to keep reference to config entry

    await manager.options._async_finish_flow(
        flow, {'data': {'second': True}})

    assert entry.data == {
        'first': True
    }

    assert entry.options == {
        'second': True
    }
Ejemplo n.º 8
0
def test_entries_gets_entries(manager):
    """Test entries are filtered by domain."""
    MockConfigEntry(domain='test').add_to_manager(manager)
    entry1 = MockConfigEntry(domain='test2')
    entry1.add_to_manager(manager)
    entry2 = MockConfigEntry(domain='test2')
    entry2.add_to_manager(manager)

    assert manager.async_entries('test2') == [entry1, entry2]
Ejemplo n.º 9
0
def test_entries_gets_entries(manager):
    """Test entries are filtered by domain."""
    MockConfigEntry(domain='test').add_to_manager(manager)
    entry1 = MockConfigEntry(domain='test2')
    entry1.add_to_manager(manager)
    entry2 = MockConfigEntry(domain='test2')
    entry2.add_to_manager(manager)

    assert manager.async_entries('test2') == [entry1, entry2]
Ejemplo n.º 10
0
async def test_full_flow_implementation(hass):
    """Test registering an implementation and flow works."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    flow.location = MOCK_LOCATION
    manager = hass.config_entries

    # User Step Started, results in Step Creds
    with patch("pyps4_homeassistant.Helper.port_bind", return_value=None):
        result = await flow.async_step_user()
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "creds"

    # Step Creds results with form in Step Mode.
    with patch("pyps4_homeassistant.Helper.get_creds",
               return_value=MOCK_CREDS):
        result = await flow.async_step_creds({})
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "mode"

    # Step Mode with User Input which is not manual, results in Step Link.
    with patch("pyps4_homeassistant.Helper.has_devices",
               return_value=[{
                   "host-ip": MOCK_HOST
               }]):
        result = await flow.async_step_mode(MOCK_AUTO)
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "link"

    # User Input results in created entry.
    with patch("pyps4_homeassistant.Helper.link",
               return_value=(True, True)), patch(
                   "pyps4_homeassistant.Helper.has_devices",
                   return_value=[{
                       "host-ip": MOCK_HOST
                   }]):
        result = await flow.async_step_link(MOCK_CONFIG)
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["data"][CONF_TOKEN] == MOCK_CREDS
    assert result["data"]["devices"] == [MOCK_DEVICE]
    assert result["title"] == MOCK_TITLE

    await hass.async_block_till_done()

    # Add entry using result data.
    mock_data = {
        CONF_TOKEN: result["data"][CONF_TOKEN],
        "devices": result["data"]["devices"],
    }
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)

    # Check if entry exists.
    assert len(manager.async_entries()) == 1
    # Check if there is a device config in entry.
    assert len(entry.data["devices"]) == 1
Ejemplo n.º 11
0
async def test_updating_entry_data(manager):
    """Test that we can update an entry data."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
    )
    entry.add_to_manager(manager)

    manager.async_update_entry(entry, data={'second': True})

    assert entry.data == {'second': True}
Ejemplo n.º 12
0
async def test_full_flow_implementation(hass):
    """Test registering an implementation and flow works."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    manager = hass.config_entries

    # User Step Started, results in Step Creds
    with patch('pyps4_homeassistant.Helper.port_bind',
               return_value=None):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'creds'

    # Step Creds results with form in Step Mode.
    with patch('pyps4_homeassistant.Helper.get_creds',
               return_value=MOCK_CREDS):
        result = await flow.async_step_creds({})
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'mode'

    # Step Mode with User Input which is not manual, results in Step Link.
    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{'host-ip': MOCK_HOST}]):
        result = await flow.async_step_mode(MOCK_AUTO)
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # User Input results in created entry.
    with patch('pyps4_homeassistant.Helper.link',
               return_value=(True, True)), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST}]):
        result = await flow.async_step_link(MOCK_CONFIG)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert result['data']['devices'] == [MOCK_DEVICE]
    assert result['title'] == MOCK_TITLE

    await hass.async_block_till_done()

    # Add entry using result data.
    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']}
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)

    # Check if entry exists.
    assert len(manager.async_entries()) == 1
    # Check if there is a device config in entry.
    assert len(entry.data['devices']) == 1
Ejemplo n.º 13
0
async def test_updating_entry_data(manager):
    """Test that we can update an entry data."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
        state=config_entries.ENTRY_STATE_SETUP_ERROR,
    )
    entry.add_to_manager(manager)

    manager.async_update_entry(entry)
    assert entry.data == {'first': True}

    manager.async_update_entry(entry, data={'second': True})
    assert entry.data == {'second': True}
Ejemplo n.º 14
0
async def test_updating_entry_system_options(manager):
    """Test that we can update an entry data."""
    entry = MockConfigEntry(
        domain="test",
        data={"first": True},
        state=config_entries.ENTRY_STATE_SETUP_ERROR,
        system_options={"disable_new_entities": True},
    )
    entry.add_to_manager(manager)

    assert entry.system_options.disable_new_entities

    entry.system_options.update(disable_new_entities=False)
    assert not entry.system_options.disable_new_entities
async def test_update_entry_options_and_trigger_listener(hass, manager):
    """Test that we can update entry options and trigger listener."""
    entry = MockConfigEntry(domain="test", options={"first": True})
    entry.add_to_manager(manager)

    async def update_listener(hass, entry):
        """Test function."""
        assert entry.options == {"second": True}

    entry.add_update_listener(update_listener)

    manager.async_update_entry(entry, options={"second": True})

    assert entry.options == {"second": True}
Ejemplo n.º 16
0
async def test_updating_entry_data(manager):
    """Test that we can update an entry data."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
    )
    entry.add_to_manager(manager)

    manager.async_update_entry(entry, data={
        'second': True
    })

    assert entry.data == {
        'second': True
    }
async def test_full_flow_implementation(hass):
    """Test registering an implementation and flow works."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    manager = hass.config_entries

    # User Step Started, results in Step Creds
    with patch('pyps4_homeassistant.Helper.port_bind',
               return_value=None):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'creds'

    # Step Creds results with form in Step Link.
    with patch('pyps4_homeassistant.Helper.get_creds',
               return_value=MOCK_CREDS), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST}]):
        result = await flow.async_step_creds({})
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # User Input results in created entry.
    with patch('pyps4_homeassistant.Helper.link',
               return_value=(True, True)), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST}]):
        result = await flow.async_step_link(MOCK_CONFIG)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert result['data']['devices'] == [MOCK_DEVICE]
    assert result['title'] == MOCK_TITLE

    # Add entry using result data.
    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']}
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)

    # Check if entry exists.
    assert len(manager.async_entries()) == 1
    # Check if there is a device config in entry.
    assert len(entry.data['devices']) == 1
Ejemplo n.º 18
0
async def test_updating_entry_data(manager):
    """Test that we can update an entry data."""
    entry = MockConfigEntry(
        domain='test',
        data={'first': True},
        state=config_entries.ENTRY_STATE_SETUP_ERROR,
    )
    entry.add_to_manager(manager)

    manager.async_update_entry(entry)
    assert entry.data == {
        'first': True
    }

    manager.async_update_entry(entry, data={
        'second': True
    })
    assert entry.data == {
        'second': True
    }
Ejemplo n.º 19
0
async def test_update_entry_options_and_trigger_listener(hass, manager):
    """Test that we can update entry options and trigger listener."""
    entry = MockConfigEntry(
        domain='test',
        options={'first': True},
    )
    entry.add_to_manager(manager)

    async def update_listener(hass, entry):
        """Test function."""
        assert entry.options == {
            'second': True
        }

    entry.add_update_listener(update_listener)

    manager.async_update_entry(entry, options={
        'second': True
    })

    assert entry.options == {
        'second': True
    }
Ejemplo n.º 20
0
async def test_remove_entry(hass, manager):
    """Test that we can remove an entry."""
    async def mock_setup_entry(hass, entry):
        """Mock setting up entry."""
        hass.loop.create_task(hass.config_entries.async_forward_entry_setup(
            entry, 'light'))
        return True

    async def mock_unload_entry(hass, entry):
        """Mock unloading an entry."""
        result = await hass.config_entries.async_forward_entry_unload(
            entry, 'light')
        assert result
        return result

    mock_remove_entry = MagicMock(
        side_effect=lambda *args, **kwargs: mock_coro())

    entity = MockEntity(
        unique_id='1234',
        name='Test Entity',
    )

    async def mock_setup_entry_platform(hass, entry, async_add_entities):
        """Mock setting up platform."""
        async_add_entities([entity])

    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
    ))
    loader.set_component(
        hass, 'light.test',
        MockPlatform(async_setup_entry=mock_setup_entry_platform))

    MockConfigEntry(domain='test', entry_id='test1').add_to_manager(manager)
    entry = MockConfigEntry(
        domain='test',
        entry_id='test2',
    )
    entry.add_to_manager(manager)
    MockConfigEntry(domain='test', entry_id='test3').add_to_manager(manager)

    # Check all config entries exist
    assert [item.entry_id for item in manager.async_entries()] == \
        ['test1', 'test2', 'test3']

    # Setup entry
    await entry.async_setup(hass)
    await hass.async_block_till_done()

    # Check entity state got added
    assert hass.states.get('light.test_entity') is not None
    # Group all_lights, light.test_entity
    assert len(hass.states.async_all()) == 2

    # Check entity got added to entity registry
    ent_reg = await hass.helpers.entity_registry.async_get_registry()
    assert len(ent_reg.entities) == 1
    entity_entry = list(ent_reg.entities.values())[0]
    assert entity_entry.config_entry_id == entry.entry_id

    # Remove entry
    result = await manager.async_remove('test2')
    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()] == \
        ['test1', 'test3']

    # Check that entity state has been removed
    assert hass.states.get('light.test_entity') is None
    # Just Group all_lights
    assert len(hass.states.async_all()) == 1

    # Check that entity registry entry no longer references config_entry_id
    entity_entry = list(ent_reg.entities.values())[0]
    assert entity_entry.config_entry_id is None
Ejemplo n.º 21
0
async def test_multiple_flow_implementation(hass):
    """Test multiple device flows."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    manager = hass.config_entries

    # User Step Started, results in Step Creds
    with patch('pyps4_homeassistant.Helper.port_bind',
               return_value=None):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'creds'

    # Step Creds results with form in Step Link.
    with patch('pyps4_homeassistant.Helper.get_creds',
               return_value=MOCK_CREDS), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST},
                                {'host-ip': MOCK_HOST_ADDITIONAL}]):
        result = await flow.async_step_creds({})
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # User Input results in created entry.
    with patch('pyps4_homeassistant.Helper.link',
               return_value=(True, True)), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST},
                                {'host-ip': MOCK_HOST_ADDITIONAL}]):
        result = await flow.async_step_link(MOCK_CONFIG)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert result['data']['devices'] == [MOCK_DEVICE]
    assert result['title'] == MOCK_TITLE

    await hass.async_block_till_done()

    # Add entry using result data.
    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']}
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)

    # Check if entry exists.
    assert len(manager.async_entries()) == 1
    # Check if there is a device config in entry.
    assert len(entry.data['devices']) == 1

    # Test additional flow.

    # User Step Started, results in Step Link:
    with patch('pyps4_homeassistant.Helper.port_bind',
               return_value=None), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST},
                                {'host-ip': MOCK_HOST_ADDITIONAL}]):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # Step Link
    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{'host-ip': MOCK_HOST},
                             {'host-ip': MOCK_HOST_ADDITIONAL}]), \
            patch('pyps4_homeassistant.Helper.link',
                  return_value=(True, True)):
        result = await flow.async_step_link(user_input=MOCK_CONFIG_ADDITIONAL)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert len(result['data']['devices']) == 1
    assert result['title'] == MOCK_TITLE

    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']}

    # Update config entries with result data
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)
    manager.async_update_entry(entry)

    # Check if there are 2 entries.
    assert len(manager.async_entries()) == 2
    # Check if there is device config in entry.
    assert len(entry.data['devices']) == 1
Ejemplo n.º 22
0
async def test_remove_entry(hass, manager):
    """Test that we can remove an entry."""
    async def mock_setup_entry(hass, entry):
        """Mock setting up entry."""
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, "light"))
        return True

    async def mock_unload_entry(hass, entry):
        """Mock unloading an entry."""
        result = await hass.config_entries.async_forward_entry_unload(
            entry, "light")
        assert result
        return result

    mock_remove_entry = MagicMock(
        side_effect=lambda *args, **kwargs: mock_coro())

    entity = MockEntity(unique_id="1234", name="Test Entity")

    async def mock_setup_entry_platform(hass, entry, async_add_entities):
        """Mock setting up platform."""
        async_add_entities([entity])

    mock_integration(
        hass,
        MockModule(
            "test",
            async_setup_entry=mock_setup_entry,
            async_unload_entry=mock_unload_entry,
            async_remove_entry=mock_remove_entry,
        ),
    )
    mock_entity_platform(
        hass, "light.test",
        MockPlatform(async_setup_entry=mock_setup_entry_platform))
    mock_entity_platform(hass, "config_flow.test", None)

    MockConfigEntry(domain="test_other",
                    entry_id="test1").add_to_manager(manager)
    entry = MockConfigEntry(domain="test", entry_id="test2")
    entry.add_to_manager(manager)
    MockConfigEntry(domain="test_other",
                    entry_id="test3").add_to_manager(manager)

    # Check all config entries exist
    assert [item.entry_id for item in manager.async_entries()] == [
        "test1",
        "test2",
        "test3",
    ]

    # Setup entry
    await entry.async_setup(hass)
    await hass.async_block_till_done()

    # Check entity state got added
    assert hass.states.get("light.test_entity") is not None
    assert len(hass.states.async_all()) == 1

    # Check entity got added to entity registry
    ent_reg = await hass.helpers.entity_registry.async_get_registry()
    assert len(ent_reg.entities) == 1
    entity_entry = list(ent_reg.entities.values())[0]
    assert entity_entry.config_entry_id == entry.entry_id

    # Remove entry
    result = await manager.async_remove("test2")
    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()] == ["test1", "test3"]

    # Check that entity state has been removed
    assert hass.states.get("light.test_entity") is None
    assert len(hass.states.async_all()) == 0

    # Check that entity registry entry has been removed
    entity_entry_list = list(ent_reg.entities.values())
    assert not entity_entry_list
Ejemplo n.º 23
0
async def test_remove_entry(hass, manager):
    """Test that we can remove an entry."""
    async def mock_setup_entry(hass, entry):
        """Mock setting up entry."""
        hass.async_create_task(hass.config_entries.async_forward_entry_setup(
            entry, 'light'))
        return True

    async def mock_unload_entry(hass, entry):
        """Mock unloading an entry."""
        result = await hass.config_entries.async_forward_entry_unload(
            entry, 'light')
        assert result
        return result

    mock_remove_entry = MagicMock(
        side_effect=lambda *args, **kwargs: mock_coro())

    entity = MockEntity(
        unique_id='1234',
        name='Test Entity',
    )

    async def mock_setup_entry_platform(hass, entry, async_add_entities):
        """Mock setting up platform."""
        async_add_entities([entity])

    mock_integration(hass, MockModule(
        'test',
        async_setup_entry=mock_setup_entry,
        async_unload_entry=mock_unload_entry,
        async_remove_entry=mock_remove_entry
    ))
    mock_entity_platform(
        hass, 'light.test',
        MockPlatform(async_setup_entry=mock_setup_entry_platform))
    mock_entity_platform(hass, 'config_flow.test', None)

    MockConfigEntry(
        domain='test_other', entry_id='test1'
    ).add_to_manager(manager)
    entry = MockConfigEntry(
        domain='test',
        entry_id='test2',
    )
    entry.add_to_manager(manager)
    MockConfigEntry(
        domain='test_other', entry_id='test3'
    ).add_to_manager(manager)

    # Check all config entries exist
    assert [item.entry_id for item in manager.async_entries()] == \
        ['test1', 'test2', 'test3']

    # Setup entry
    await entry.async_setup(hass)
    await hass.async_block_till_done()

    # Check entity state got added
    assert hass.states.get('light.test_entity') is not None
    # Group all_lights, light.test_entity
    assert len(hass.states.async_all()) == 2

    # Check entity got added to entity registry
    ent_reg = await hass.helpers.entity_registry.async_get_registry()
    assert len(ent_reg.entities) == 1
    entity_entry = list(ent_reg.entities.values())[0]
    assert entity_entry.config_entry_id == entry.entry_id

    # Remove entry
    result = await manager.async_remove('test2')
    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()] == \
        ['test1', 'test3']

    # Check that entity state has been removed
    assert hass.states.get('light.test_entity') is None
    # Just Group all_lights
    assert len(hass.states.async_all()) == 1

    # Check that entity registry entry no longer references config_entry_id
    entity_entry = list(ent_reg.entities.values())[0]
    assert entity_entry.config_entry_id is None
Ejemplo n.º 24
0
async def setup_mock_component(hass):
    """Set up Mock Media Player."""
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA, version=VERSION)
    entry.add_to_manager(hass.config_entries)
    await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
    await hass.async_block_till_done()
Ejemplo n.º 25
0
async def test_multiple_flow_implementation(hass):
    """Test multiple device flows."""
    flow = ps4.PlayStation4FlowHandler()
    flow.hass = hass
    manager = hass.config_entries

    # User Step Started, results in Step Creds
    with patch('pyps4_homeassistant.Helper.port_bind', return_value=None):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'creds'

    # Step Creds results with form in Step Mode.
    with patch('pyps4_homeassistant.Helper.get_creds',
               return_value=MOCK_CREDS):
        result = await flow.async_step_creds({})
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'mode'

    # Step Mode with User Input which is not manual, results in Step Link.
    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{
                   'host-ip': MOCK_HOST
               }, {
                   'host-ip': MOCK_HOST_ADDITIONAL
               }]):
        result = await flow.async_step_mode(MOCK_AUTO)
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # User Input results in created entry.
    with patch('pyps4_homeassistant.Helper.link',
               return_value=(True, True)), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST},
                                {'host-ip': MOCK_HOST_ADDITIONAL}]):
        result = await flow.async_step_link(MOCK_CONFIG)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert result['data']['devices'] == [MOCK_DEVICE]
    assert result['title'] == MOCK_TITLE

    await hass.async_block_till_done()

    # Add entry using result data.
    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']
    }
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)

    # Check if entry exists.
    assert len(manager.async_entries()) == 1
    # Check if there is a device config in entry.
    assert len(entry.data['devices']) == 1

    # Test additional flow.

    # User Step Started, results in Step Mode:
    with patch('pyps4_homeassistant.Helper.port_bind',
               return_value=None), \
            patch('pyps4_homeassistant.Helper.has_devices',
                  return_value=[{'host-ip': MOCK_HOST},
                                {'host-ip': MOCK_HOST_ADDITIONAL}]):
        result = await flow.async_step_user()
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'mode'

    # Step Mode with User Input which is not manual, results in Step Link.
    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{
                   'host-ip': MOCK_HOST
               }, {
                   'host-ip': MOCK_HOST_ADDITIONAL
               }]):
        result = await flow.async_step_mode(MOCK_AUTO)
    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'link'

    # Step Link
    with patch('pyps4_homeassistant.Helper.has_devices',
               return_value=[{'host-ip': MOCK_HOST},
                             {'host-ip': MOCK_HOST_ADDITIONAL}]), \
            patch('pyps4_homeassistant.Helper.link',
                  return_value=(True, True)):
        result = await flow.async_step_link(MOCK_CONFIG_ADDITIONAL)
    assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result['data'][CONF_TOKEN] == MOCK_CREDS
    assert len(result['data']['devices']) == 1
    assert result['title'] == MOCK_TITLE

    await hass.async_block_till_done()

    mock_data = {
        CONF_TOKEN: result['data'][CONF_TOKEN],
        'devices': result['data']['devices']
    }

    # Update config entries with result data
    entry = MockConfigEntry(domain=ps4.DOMAIN, data=mock_data)
    entry.add_to_manager(manager)
    manager.async_update_entry(entry)

    # Check if there are 2 entries.
    assert len(manager.async_entries()) == 2
    # Check if there is device config in entry.
    assert len(entry.data['devices']) == 1