async def test_homekit_start(hass, hk_driver, debounce_patcher):
    """Test HomeKit start method."""
    pin = b'123-45-678'
    homekit = HomeKit(hass, None, None, {}, {'cover.demo': {}})
    homekit.bridge = 'bridge'
    homekit.driver = hk_driver

    hass.states.async_set('light.demo', 'on')
    state = hass.states.async_all()[0]

    with patch(PATH_HOMEKIT + '.HomeKit.add_bridge_accessory') as \
        mock_add_acc, \
        patch(PATH_HOMEKIT + '.show_setup_message') as mock_setup_msg, \
        patch('pyhap.accessory_driver.AccessoryDriver.add_accessory') as \
        hk_driver_add_acc, \
        patch('pyhap.accessory_driver.AccessoryDriver.start') as \
            hk_driver_start:
        await hass.async_add_job(homekit.start)

    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, pin)
    hk_driver_add_acc.assert_called_with('bridge')
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await hass.async_add_job(homekit.start)
    assert not hk_driver_start.called
Example #2
0
async def test_homekit_start(hass, hk_driver, debounce_patcher):
    """Test HomeKit start method."""
    pin = b'123-45-678'
    homekit = HomeKit(hass, None, None, None, {}, {'cover.demo': {}}, None)
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver

    hass.states.async_set('light.demo', 'on')
    state = hass.states.async_all()[0]

    with patch(PATH_HOMEKIT + '.HomeKit.add_bridge_accessory') as \
        mock_add_acc, \
        patch(PATH_HOMEKIT + '.show_setup_message') as mock_setup_msg, \
        patch('pyhap.accessory_driver.AccessoryDriver.add_accessory') as \
        hk_driver_add_acc, \
        patch('pyhap.accessory_driver.AccessoryDriver.start') as \
            hk_driver_start:
        await hass.async_add_job(homekit.start)

    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, pin)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await hass.async_add_job(homekit.start)
    assert not hk_driver_start.called
Example #3
0
async def test_homekit_warn_add_accessory_bridge(hass, acc_category,
                                                 mock_zeroconf, caplog):
    """Test we warn when adding cameras or tvs to a bridge."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        lambda entity_id: True,
        {},
        HOMEKIT_MODE_BRIDGE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()
    homekit.bridge.accessories = range(10)

    mock_camera_acc = Mock(category=acc_category)

    await async_init_integration(hass)

    with patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc:
        mock_get_acc.side_effect = [None, mock_camera_acc, None]
        homekit.add_bridge_accessory(State("light.demo", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 1403373688, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("camera.test", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 1508819236, {})
        assert mock_bridge.add_accessory.called

    assert "accessory mode" in caplog.text
Example #4
0
async def test_homekit_start_with_a_broken_accessory(hass, hk_driver,
                                                     debounce_patcher):
    """Test HomeKit start method."""
    pin = b"123-45-678"
    entity_filter = generate_filter(["cover", "light"], ["demo.test"], [], [])

    assert await setup.async_setup_component(hass, DOMAIN, {DOMAIN: {}})

    homekit = HomeKit(hass, None, None, None, entity_filter, {}, None, None)
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver

    hass.states.async_set("light.demo", "on")
    hass.states.async_set("light.broken", "on")

    with patch(
            f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception
    ), patch(f"{PATH_HOMEKIT}.show_setup_message") as mock_setup_msg, patch(
            "pyhap.accessory_driver.AccessoryDriver.add_accessory",
    ) as hk_driver_add_acc, patch(
            "pyhap.accessory_driver.AccessoryDriver.start") as hk_driver_start:
        await homekit.async_start()

    mock_setup_msg.assert_called_with(hass, pin, ANY)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await homekit.async_start()
    assert not hk_driver_start.called
Example #5
0
async def test_homekit_add_accessory(hass):
    """Add accessory if config exists and get_acc returns an accessory."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        lambda entity_id: True,
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()
    homekit.bridge.accessories = range(10)

    await async_init_integration(hass)

    with patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc:
        mock_get_acc.side_effect = [None, "acc", None]
        homekit.add_bridge_accessory(State("light.demo", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 1403373688, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 600325356, {})
        assert mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test_2", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 1467253281, {})
        mock_bridge.add_accessory.assert_called_with("acc")
Example #6
0
async def test_homekit_start(hass, hk_driver, debounce_patcher):
    """Test HomeKit start method."""
    pin = b"123-45-678"
    homekit = HomeKit(hass, None, None, None, {}, {"cover.demo": {}}, None,
                      None)
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver
    homekit._filter = Mock(return_value=True)

    hass.states.async_set("light.demo", "on")
    state = hass.states.async_all()[0]

    with patch(
            f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory"
    ) as mock_add_acc, patch(
            f"{PATH_HOMEKIT}.show_setup_message") as mock_setup_msg, patch(
                "pyhap.accessory_driver.AccessoryDriver.add_accessory"
            ) as hk_driver_add_acc, patch(
                "pyhap.accessory_driver.AccessoryDriver.start"
            ) as hk_driver_start:
        await homekit.async_start()

    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, pin, ANY)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await homekit.async_start()
    assert not hk_driver_start.called
Example #7
0
async def test_homekit_stop(hass):
    """Test HomeKit stop method."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = Mock()

    await async_init_integration(hass)

    assert homekit.status == STATUS_READY
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_WAIT
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_STOPPED
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.stop.called is False

    # Test if driver is started
    homekit.status = STATUS_RUNNING
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.stop.called is True
Example #8
0
async def test_homekit_too_many_accessories(hass, hk_driver):
    """Test adding too many accessories to HomeKit."""
    entry = await async_init_integration(hass)

    entity_filter = generate_filter(["cover", "light"], ["demo.test"], [], [])

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        entity_filter,
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.bridge = Mock()
    # The bridge itself counts as an accessory
    homekit.bridge.accessories = range(MAX_DEVICES)
    homekit.driver = hk_driver

    hass.states.async_set("light.demo", "on")

    with patch("pyhap.accessory_driver.AccessoryDriver.start"), patch(
        "pyhap.accessory_driver.AccessoryDriver.add_accessory"
    ), patch("homeassistant.components.homekit._LOGGER.warning") as mock_warn, patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ):
        await homekit.async_start()
        await hass.async_block_till_done()
        assert mock_warn.called is True
async def test_homekit_remove_accessory():
    """Remove accessory from bridge."""
    homekit = HomeKit("hass", None, None, None, lambda entity_id: True, {},
                      None)
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()
    mock_bridge.accessories = {"light.demo": "acc"}

    acc = homekit.remove_bridge_accessory("light.demo")
    assert acc == "acc"
    assert len(mock_bridge.accessories) == 0
async def test_homekit_too_many_accessories(hass, hk_driver):
    """Test adding too many accessories to HomeKit."""
    homekit = HomeKit(hass, None, None, None, None, None, None)
    homekit.bridge = Mock()
    homekit.bridge.accessories = range(MAX_DEVICES + 1)
    homekit.driver = hk_driver

    with patch("pyhap.accessory_driver.AccessoryDriver.start"), patch(
            "pyhap.accessory_driver.AccessoryDriver.add_accessory"
    ), patch("homeassistant.components.homekit._LOGGER.warning") as mock_warn:
        await hass.async_add_job(homekit.start)
        assert mock_warn.called is True
Example #11
0
async def test_homekit_start_with_a_broken_accessory(hass, hk_driver,
                                                     debounce_patcher):
    """Test HomeKit start method."""
    pin = b"123-45-678"
    entry = MockConfigEntry(domain=DOMAIN,
                            data={
                                CONF_NAME: "mock_name",
                                CONF_PORT: 12345
                            })
    entity_filter = generate_filter(["cover", "light"], ["demo.test"], [], [])

    await async_init_entry(hass, entry)
    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        entity_filter,
        {},
        DEFAULT_SAFE_MODE,
        HOMEKIT_MODE_BRIDGE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )

    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver
    homekit.driver.accessory = Accessory(hk_driver, "any")

    hass.states.async_set("light.demo", "on")
    hass.states.async_set("light.broken", "on")

    with patch(f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception), patch(
            f"{PATH_HOMEKIT}.show_setup_message") as mock_setup_msg, patch(
                "pyhap.accessory_driver.AccessoryDriver.add_accessory",
            ) as hk_driver_add_acc, patch(
                "pyhap.accessory_driver.AccessoryDriver.start_service"
            ) as hk_driver_start:
        await homekit.async_start()

    await hass.async_block_till_done()
    mock_setup_msg.assert_called_with(hass, entry.entry_id, None, pin, ANY)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await homekit.async_start()
    await hass.async_block_till_done()
    assert not hk_driver_start.called
Example #12
0
async def test_homekit_too_many_accessories(hass, hk_driver):
    """Test adding too many accessories to HomeKit."""
    homekit = HomeKit(hass, None, None, None, None, None, None)
    homekit.bridge = Mock()
    homekit.bridge.accessories = range(MAX_DEVICES + 1)
    homekit.driver = hk_driver

    with patch('pyhap.accessory_driver.AccessoryDriver.start'), \
            patch('pyhap.accessory_driver.AccessoryDriver.add_accessory'), \
            patch('homeassistant.components.homekit._LOGGER.warning') \
            as mock_warn:
        await hass.async_add_job(homekit.start)
        assert mock_warn.called is True
Example #13
0
async def test_homekit_start(hass, hk_driver, debounce_patcher):
    """Test HomeKit start method."""
    entry = await async_init_integration(hass)

    pin = b"123-45-678"
    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        interface_choice=None,
        entry_id=entry.entry_id,
    )
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver
    homekit._filter = Mock(return_value=True)

    hass.states.async_set("light.demo", "on")
    state = hass.states.async_all()[0]

    with patch(
            f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory"
    ) as mock_add_acc, patch(
            f"{PATH_HOMEKIT}.show_setup_message") as mock_setup_msg, patch(
                "pyhap.accessory_driver.AccessoryDriver.add_accessory"
            ) as hk_driver_add_acc, patch(
                "pyhap.accessory_driver.AccessoryDriver.start"
            ) as hk_driver_start:
        await homekit.async_start()

    await hass.async_block_till_done()
    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, entry.entry_id, None, pin, ANY)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await homekit.async_start()
    await hass.async_block_till_done()
    assert not hk_driver_start.called
async def test_homekit_stop(hass):
    """Test HomeKit stop method."""
    homekit = HomeKit(hass, None, None, None, None)
    homekit.driver = Mock()

    assert homekit.status == STATUS_READY
    await hass.async_add_job(homekit.stop)
    homekit.status = STATUS_WAIT
    await hass.async_add_job(homekit.stop)
    homekit.status = STATUS_STOPPED
    await hass.async_add_job(homekit.stop)
    assert homekit.driver.stop.called is False

    # Test if driver is started
    homekit.status = STATUS_RUNNING
    await hass.async_add_job(homekit.stop)
    assert homekit.driver.stop.called is True
Example #15
0
async def test_homekit_stop(hass):
    """Test HomeKit stop method."""
    homekit = HomeKit(hass, None, None, None, None, None, None)
    homekit.driver = Mock()

    assert homekit.status == STATUS_READY
    await hass.async_add_job(homekit.stop)
    homekit.status = STATUS_WAIT
    await hass.async_add_job(homekit.stop)
    homekit.status = STATUS_STOPPED
    await hass.async_add_job(homekit.stop)
    assert homekit.driver.stop.called is False

    # Test if driver is started
    homekit.status = STATUS_RUNNING
    await hass.async_add_job(homekit.stop)
    assert homekit.driver.stop.called is True
Example #16
0
    def test_homekit_stop(self):
        """Test HomeKit stop method."""
        homekit = HomeKit(None, None, None, None, None)
        homekit.driver = Mock()

        # Test if started = False
        homekit.stop()
        self.assertFalse(homekit.driver.stop.called)

        # Test if driver not started
        homekit.started = True
        homekit.driver.configure_mock(**{'run_sentinel': None})
        homekit.stop()
        self.assertFalse(homekit.driver.stop.called)

        # Test if driver is started
        homekit.driver.configure_mock(**{'run_sentinel': 'sentinel'})
        homekit.stop()
        self.assertTrue(homekit.driver.stop.called)
Example #17
0
    def test_homekit_stop(self):
        """Test HomeKit stop method."""
        homekit = HomeKit(None, None, None, None)
        homekit.driver = Mock()

        # Test if started = False
        homekit.stop()
        self.assertFalse(homekit.driver.stop.called)

        # Test if driver not started
        homekit.started = True
        homekit.driver.configure_mock(**{'run_sentinel': None})
        homekit.stop()
        self.assertFalse(homekit.driver.stop.called)

        # Test if driver is started
        homekit.driver.configure_mock(**{'run_sentinel': 'sentinel'})
        homekit.stop()
        self.assertTrue(homekit.driver.stop.called)
Example #18
0
async def test_homekit_add_accessory():
    """Add accessory if config exists and get_acc returns an accessory."""
    homekit = HomeKit('hass', None, None, None, lambda entity_id: True, {})
    homekit.driver = 'driver'
    homekit.bridge = mock_bridge = Mock()

    with patch(PATH_HOMEKIT + '.get_accessory') as mock_get_acc:

        mock_get_acc.side_effect = [None, 'acc', None]
        homekit.add_bridge_accessory(State('light.demo', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 363398124, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State('demo.test', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 294192020, {})
        assert mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State('demo.test_2', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 429982757, {})
        mock_bridge.add_accessory.assert_called_with('acc')
async def test_homekit_add_accessory():
    """Add accessory if config exists and get_acc returns an accessory."""
    homekit = HomeKit('hass', None, None, lambda entity_id: True, {})
    homekit.driver = 'driver'
    homekit.bridge = mock_bridge = Mock()

    with patch(PATH_HOMEKIT + '.get_accessory') as mock_get_acc:

        mock_get_acc.side_effect = [None, 'acc', None]
        homekit.add_bridge_accessory(State('light.demo', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 363398124, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State('demo.test', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 294192020, {})
        assert mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State('demo.test_2', 'on'))
        mock_get_acc.assert_called_with('hass', 'driver', ANY, 429982757, {})
        mock_bridge.add_accessory.assert_called_with('acc')
Example #20
0
async def test_homekit_start_in_accessory_mode(hass, hk_driver, device_reg,
                                               debounce_patcher):
    """Test HomeKit start method in accessory mode."""
    entry = await async_init_integration(hass)

    pin = b"123-45-678"
    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {},
        DEFAULT_SAFE_MODE,
        HOMEKIT_MODE_ACCESSORY,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver
    # pylint: disable=protected-access
    homekit._filter = Mock(return_value=True)
    homekit.driver.accessory = Accessory(hk_driver, "any")

    hass.states.async_set("light.demo", "on")

    with patch(
            f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory"
    ) as mock_add_acc, patch(
            "pyhap.accessory_driver.AccessoryDriver.add_accessory"), patch(
                f"{PATH_HOMEKIT}.show_setup_message") as mock_setup_msg, patch(
                    "pyhap.accessory_driver.AccessoryDriver.start_service"
                ) as hk_driver_start:
        await homekit.async_start()

    await hass.async_block_till_done()
    mock_add_acc.assert_not_called()
    mock_setup_msg.assert_called_with(hass, entry.entry_id, None, pin, ANY)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING
Example #21
0
    def test_homekit_stop(self):
        """Test HomeKit stop method."""
        homekit = HomeKit(self.hass, None, None, None, None)
        homekit.driver = Mock()

        self.assertEqual(homekit.status, STATUS_READY)
        homekit.stop()
        self.hass.block_till_done()
        homekit.status = STATUS_WAIT
        homekit.stop()
        self.hass.block_till_done()
        homekit.status = STATUS_STOPPED
        homekit.stop()
        self.hass.block_till_done()
        self.assertFalse(homekit.driver.stop.called)

        # Test if driver is started
        homekit.status = STATUS_RUNNING
        homekit.stop()
        self.hass.block_till_done()
        self.assertTrue(homekit.driver.stop.called)
async def test_homekit_add_accessory():
    """Add accessory if config exists and get_acc returns an accessory."""
    homekit = HomeKit("hass", None, None, None, lambda entity_id: True, {},
                      None)
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()

    with patch(PATH_HOMEKIT + ".get_accessory") as mock_get_acc:

        mock_get_acc.side_effect = [None, "acc", None]
        homekit.add_bridge_accessory(State("light.demo", "on"))
        mock_get_acc.assert_called_with("hass", "driver", ANY, 363398124, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test", "on"))
        mock_get_acc.assert_called_with("hass", "driver", ANY, 294192020, {})
        assert mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test_2", "on"))
        mock_get_acc.assert_called_with("hass", "driver", ANY, 429982757, {})
        mock_bridge.add_accessory.assert_called_with("acc")
Example #23
0
    def test_homekit_start(self, mock_add_bridge_acc, mock_show_setup_msg):
        """Test HomeKit start method."""
        homekit = HomeKit(self.hass, None, None, {}, {'cover.demo': {}})
        homekit.bridge = HomeBridge(self.hass)
        homekit.driver = Mock()

        self.hass.states.set('light.demo', 'on')
        state = self.hass.states.all()[0]

        homekit.start()

        self.assertEqual(mock_add_bridge_acc.mock_calls, [call(state)])
        self.assertEqual(mock_show_setup_msg.mock_calls,
                         [call(self.hass, homekit.bridge)])
        self.assertEqual(homekit.driver.mock_calls, [call.start()])
        self.assertTrue(homekit.started)

        # Test start() if already started
        homekit.driver.reset_mock()
        homekit.start()
        self.assertEqual(homekit.driver.mock_calls, [])
Example #24
0
    def test_homekit_start(self, mock_add_bridge_acc, mock_show_setup_msg):
        """Test HomeKit start method."""
        homekit = HomeKit(self.hass, None, {}, {'cover.demo': {}})
        homekit.bridge = HomeBridge(self.hass)
        homekit.driver = Mock()

        self.hass.states.set('light.demo', 'on')
        state = self.hass.states.all()[0]

        homekit.start()

        self.assertEqual(mock_add_bridge_acc.mock_calls, [call(state)])
        self.assertEqual(mock_show_setup_msg.mock_calls, [
            call(self.hass, homekit.bridge)])
        self.assertEqual(homekit.driver.mock_calls, [call.start()])
        self.assertTrue(homekit.started)

        # Test start() if already started
        homekit.driver.reset_mock()
        homekit.start()
        self.assertEqual(homekit.driver.mock_calls, [])
Example #25
0
async def test_homekit_too_many_accessories(hass, hk_driver, caplog):
    """Test adding too many accessories to HomeKit."""
    entry = await async_init_integration(hass)

    entity_filter = generate_filter(["cover", "light"], ["demo.test"], [], [])

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        entity_filter,
        {},
        DEFAULT_SAFE_MODE,
        HOMEKIT_MODE_BRIDGE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )

    def _mock_bridge(*_):
        mock_bridge = HomeBridge(hass, hk_driver, "mock_bridge")
        # The bridge itself counts as an accessory
        mock_bridge.accessories = range(MAX_DEVICES)
        return mock_bridge

    homekit.driver = hk_driver
    homekit.driver.accessory = Accessory(hk_driver, "any")

    hass.states.async_set("light.demo", "on")
    hass.states.async_set("light.demo2", "on")
    hass.states.async_set("light.demo3", "on")

    with patch("pyhap.accessory_driver.AccessoryDriver.start_service"), patch(
        "pyhap.accessory_driver.AccessoryDriver.add_accessory"
    ), patch(f"{PATH_HOMEKIT}.show_setup_message"), patch(
        f"{PATH_HOMEKIT}.accessories.HomeBridge", _mock_bridge
    ):
        await homekit.async_start()
        await hass.async_block_till_done()
        assert "would exceeded" in caplog.text
Example #26
0
async def test_homekit_remove_accessory(hass):
    """Remove accessory from bridge."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        lambda entity_id: True,
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()
    mock_bridge.accessories = {"light.demo": "acc"}

    acc = homekit.remove_bridge_accessory("light.demo")
    assert acc == "acc"
    assert len(mock_bridge.accessories) == 0
Example #27
0
async def test_homekit_add_accessory(hass):
    """Add accessory if config exists and get_acc returns an accessory."""
    homekit = HomeKit(hass, None, None, None, lambda entity_id: True, {}, None,
                      None)
    homekit.driver = "driver"
    homekit.bridge = mock_bridge = Mock()
    homekit.bridge.accessories = range(10)

    assert await setup.async_setup_component(hass, DOMAIN, {DOMAIN: {}})

    with patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc:
        mock_get_acc.side_effect = [None, "acc", None]
        homekit.add_bridge_accessory(State("light.demo", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 363398124, {})
        assert not mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 294192020, {})
        assert mock_bridge.add_accessory.called

        homekit.add_bridge_accessory(State("demo.test_2", "on"))
        mock_get_acc.assert_called_with(hass, "driver", ANY, 429982757, {})
        mock_bridge.add_accessory.assert_called_with("acc")
Example #28
0
async def test_homekit_stop(hass):
    """Test HomeKit stop method."""
    homekit = HomeKit(hass, None, None, None, None, None, None)
    homekit.driver = Mock()

    assert await setup.async_setup_component(hass, DOMAIN, {DOMAIN: {}})

    assert homekit.status == STATUS_READY
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_WAIT
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_STOPPED
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.stop.called is False

    # Test if driver is started
    homekit.status = STATUS_RUNNING
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.stop.called is True
Example #29
0
async def test_homekit_stop(hass):
    """Test HomeKit stop method."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {},
        HOMEKIT_MODE_BRIDGE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = Mock()
    homekit.driver.async_stop = AsyncMock()
    homekit.bridge = Mock()
    homekit.bridge.accessories = {}

    assert homekit.status == STATUS_READY
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_WAIT
    await homekit.async_stop()
    await hass.async_block_till_done()
    homekit.status = STATUS_STOPPED
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.async_stop.called is False

    # Test if driver is started
    homekit.status = STATUS_RUNNING
    await homekit.async_stop()
    await hass.async_block_till_done()
    assert homekit.driver.async_stop.called is True
Example #30
0
async def test_homekit_start(hass, debounce_patcher):
    """Test HomeKit start method."""
    pin = b'123-45-678'
    homekit = HomeKit(hass, None, None, {}, {'cover.demo': {}})
    homekit.bridge = HomeBridge(hass)
    homekit.driver = Mock(state=Mock(paired=False, pincode=pin))

    hass.states.async_set('light.demo', 'on')
    state = hass.states.async_all()[0]

    with patch(PATH_HOMEKIT + '.HomeKit.add_bridge_accessory') as \
        mock_add_acc, \
            patch(PATH_HOMEKIT + '.show_setup_message') as mock_setup_msg:
        await hass.async_add_job(homekit.start)

    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, pin)
    assert homekit.driver.start.called is True
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    homekit.driver.reset_mock()
    await hass.async_add_job(homekit.start)
    assert homekit.driver.start.called is False
Example #31
0
async def test_homekit_start(hass, hk_driver, device_reg, debounce_patcher):
    """Test HomeKit start method."""
    entry = await async_init_integration(hass)

    pin = b"123-45-678"
    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.bridge = Mock()
    homekit.bridge.accessories = []
    homekit.driver = hk_driver
    # pylint: disable=protected-access
    homekit._filter = Mock(return_value=True)

    connection = (device_registry.CONNECTION_NETWORK_MAC, "AA:BB:CC:DD:EE:FF")
    bridge_with_wrong_mac = device_reg.async_get_or_create(
        config_entry_id=entry.entry_id,
        connections={connection},
        manufacturer="Any",
        name="Any",
        model="Home Assistant HomeKit Bridge",
    )

    hass.states.async_set("light.demo", "on")
    state = hass.states.async_all()[0]

    with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ) as mock_setup_msg, patch(
        "pyhap.accessory_driver.AccessoryDriver.add_accessory"
    ) as hk_driver_add_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start"
    ) as hk_driver_start:
        await homekit.async_start()

    await hass.async_block_till_done()
    mock_add_acc.assert_called_with(state)
    mock_setup_msg.assert_called_with(hass, entry.entry_id, None, pin, ANY)
    hk_driver_add_acc.assert_called_with(homekit.bridge)
    assert hk_driver_start.called
    assert homekit.status == STATUS_RUNNING

    # Test start() if already started
    hk_driver_start.reset_mock()
    await homekit.async_start()
    await hass.async_block_till_done()
    assert not hk_driver_start.called

    assert device_reg.async_get(bridge_with_wrong_mac.id) is None

    device = device_reg.async_get_device(
        {(DOMAIN, entry.entry_id, BRIDGE_SERIAL_NUMBER)}, {}
    )
    assert device
    formatted_mac = device_registry.format_mac(homekit.driver.state.mac)
    assert (device_registry.CONNECTION_NETWORK_MAC, formatted_mac) in device.connections

    # Start again to make sure the registry entry is kept
    homekit.status = STATUS_READY
    with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ) as mock_setup_msg, patch(
        "pyhap.accessory_driver.AccessoryDriver.add_accessory"
    ) as hk_driver_add_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start"
    ) as hk_driver_start:
        await homekit.async_start()

    device = device_reg.async_get_device(
        {(DOMAIN, entry.entry_id, BRIDGE_SERIAL_NUMBER)}, {}
    )
    assert device
    formatted_mac = device_registry.format_mac(homekit.driver.state.mac)
    assert (device_registry.CONNECTION_NETWORK_MAC, formatted_mac) in device.connections

    assert len(device_reg.devices) == 1
Example #32
0
async def test_homekit_finds_linked_motion_sensors(
    hass, hk_driver, debounce_patcher, device_reg, entity_reg
):
    """Test HomeKit start method."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {"camera.camera_demo": {}},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = hk_driver
    # pylint: disable=protected-access
    homekit._filter = Mock(return_value=True)
    homekit.bridge = HomeBridge(hass, hk_driver, "mock_bridge")

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        sw_version="0.16.0",
        model="Camera Server",
        manufacturer="Ubq",
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )

    binary_motion_sensor = entity_reg.async_get_or_create(
        "binary_sensor",
        "camera",
        "motion_sensor",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_MOTION,
    )
    camera = entity_reg.async_get_or_create(
        "camera", "camera", "demo", device_id=device_entry.id
    )

    hass.states.async_set(
        binary_motion_sensor.entity_id,
        STATE_ON,
        {ATTR_DEVICE_CLASS: DEVICE_CLASS_MOTION},
    )
    hass.states.async_set(camera.entity_id, STATE_ON)

    def _mock_get_accessory(*args, **kwargs):
        return [None, "acc", None]

    with patch.object(homekit.bridge, "add_accessory"), patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start"
    ):
        await homekit.async_start()
    await hass.async_block_till_done()

    mock_get_acc.assert_called_with(
        hass,
        hk_driver,
        ANY,
        ANY,
        {
            "manufacturer": "Ubq",
            "model": "Camera Server",
            "sw_version": "0.16.0",
            "linked_motion_sensor": "binary_sensor.camera_motion_sensor",
        },
    )
Example #33
0
async def test_homekit_async_get_integration_fails(
    hass, hk_driver, debounce_patcher, device_reg, entity_reg
):
    """Test that we continue if async_get_integration fails."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {"light.demo": {}},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = hk_driver
    # pylint: disable=protected-access
    homekit._filter = Mock(return_value=True)
    homekit.bridge = HomeBridge(hass, hk_driver, "mock_bridge")

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        sw_version="0.16.0",
        model="Powerwall 2",
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )

    binary_charging_sensor = entity_reg.async_get_or_create(
        "binary_sensor",
        "invalid_integration_does_not_exist",
        "battery_charging",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY_CHARGING,
    )
    battery_sensor = entity_reg.async_get_or_create(
        "sensor",
        "invalid_integration_does_not_exist",
        "battery",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY,
    )
    light = entity_reg.async_get_or_create(
        "light", "invalid_integration_does_not_exist", "demo", device_id=device_entry.id
    )

    hass.states.async_set(
        binary_charging_sensor.entity_id,
        STATE_ON,
        {ATTR_DEVICE_CLASS: DEVICE_CLASS_BATTERY_CHARGING},
    )
    hass.states.async_set(
        battery_sensor.entity_id, 30, {ATTR_DEVICE_CLASS: DEVICE_CLASS_BATTERY}
    )
    hass.states.async_set(light.entity_id, STATE_ON)

    def _mock_get_accessory(*args, **kwargs):
        return [None, "acc", None]

    with patch.object(homekit.bridge, "add_accessory"), patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start_service"
    ):
        await homekit.async_start()
    await hass.async_block_till_done()

    mock_get_acc.assert_called_with(
        hass,
        hk_driver,
        ANY,
        ANY,
        {
            "model": "Powerwall 2",
            "sw_version": "0.16.0",
            "platform": "invalid_integration_does_not_exist",
            "linked_battery_charging_sensor": "binary_sensor.invalid_integration_does_not_exist_battery_charging",
            "linked_battery_sensor": "sensor.invalid_integration_does_not_exist_battery",
        },
    )
Example #34
0
async def test_homekit_finds_linked_batteries(hass, hk_driver,
                                              debounce_patcher, device_reg,
                                              entity_reg):
    """Test HomeKit start method."""
    assert await setup.async_setup_component(hass, DOMAIN, {DOMAIN: {}})

    homekit = HomeKit(hass, None, None, None, {}, {"light.demo": {}}, None,
                      None)
    homekit.driver = hk_driver
    homekit._filter = Mock(return_value=True)
    homekit.bridge = HomeBridge(hass, hk_driver, "mock_bridge")

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(device_registry.CONNECTION_NETWORK_MAC,
                      "12:34:56:AB:CD:EF")},
    )

    binary_charging_sensor = entity_reg.async_get_or_create(
        "binary_sensor",
        "light",
        "battery_charging",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY_CHARGING,
    )
    battery_sensor = entity_reg.async_get_or_create(
        "sensor",
        "light",
        "battery",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY,
    )
    light = entity_reg.async_get_or_create("light",
                                           "light",
                                           "demo",
                                           device_id=device_entry.id)

    hass.states.async_set(
        binary_charging_sensor.entity_id,
        STATE_ON,
        {ATTR_DEVICE_CLASS: DEVICE_CLASS_BATTERY_CHARGING},
    )
    hass.states.async_set(battery_sensor.entity_id, 30,
                          {ATTR_DEVICE_CLASS: DEVICE_CLASS_BATTERY})
    hass.states.async_set(light.entity_id, STATE_ON)

    def _mock_get_accessory(*args, **kwargs):
        return [None, "acc", None]

    with patch.object(homekit.bridge, "add_accessory"), patch(
            f"{PATH_HOMEKIT}.show_setup_message"), patch(
                f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
                    "pyhap.accessory_driver.AccessoryDriver.start"):
        await homekit.async_start()

    mock_get_acc.assert_called_with(
        hass,
        hk_driver,
        ANY,
        ANY,
        {
            "linked_battery_charging_sensor":
            "binary_sensor.light_battery_charging",
            "linked_battery_sensor": "sensor.light_battery",
        },
    )
Example #35
0
async def test_homekit_ignored_missing_devices(
    hass, hk_driver, debounce_patcher, device_reg, entity_reg
):
    """Test HomeKit handles a device in the entity registry but missing from the device registry."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {"light.demo": {}},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = hk_driver
    # pylint: disable=protected-access
    homekit._filter = Mock(return_value=True)
    homekit.bridge = HomeBridge(hass, hk_driver, "mock_bridge")

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        sw_version="0.16.0",
        model="Powerwall 2",
        manufacturer="Tesla",
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )

    entity_reg.async_get_or_create(
        "binary_sensor",
        "powerwall",
        "battery_charging",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY_CHARGING,
    )
    entity_reg.async_get_or_create(
        "sensor",
        "powerwall",
        "battery",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_BATTERY,
    )
    light = entity_reg.async_get_or_create(
        "light", "powerwall", "demo", device_id=device_entry.id
    )

    # Delete the device to make sure we fallback
    # to using the platform
    device_reg.async_remove_device(device_entry.id)

    hass.states.async_set(light.entity_id, STATE_ON)

    def _mock_get_accessory(*args, **kwargs):
        return [None, "acc", None]

    with patch.object(homekit.bridge, "add_accessory"), patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start"
    ):
        await homekit.async_start()
    await hass.async_block_till_done()

    mock_get_acc.assert_called_with(
        hass,
        hk_driver,
        ANY,
        ANY,
        {
            "platform": "Tesla Powerwall",
            "linked_battery_charging_sensor": "binary_sensor.powerwall_battery_charging",
            "linked_battery_sensor": "sensor.powerwall_battery",
        },
    )
Example #36
0
async def test_homekit_finds_linked_humidity_sensors(
    hass, hk_driver, debounce_patcher, device_reg, entity_reg
):
    """Test HomeKit start method."""
    entry = await async_init_integration(hass)

    homekit = HomeKit(
        hass,
        None,
        None,
        None,
        {},
        {"humidifier.humidifier": {}},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )
    homekit.driver = hk_driver
    homekit._filter = Mock(return_value=True)
    homekit.bridge = HomeBridge(hass, hk_driver, "mock_bridge")

    config_entry = MockConfigEntry(domain="test", data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        sw_version="0.16.1",
        model="Smart Brainy Clever Humidifier",
        manufacturer="Home Assistant",
        connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
    )

    humidity_sensor = entity_reg.async_get_or_create(
        "sensor",
        "humidifier",
        "humidity_sensor",
        device_id=device_entry.id,
        device_class=DEVICE_CLASS_HUMIDITY,
    )
    humidifier = entity_reg.async_get_or_create(
        "humidifier", "humidifier", "demo", device_id=device_entry.id
    )

    hass.states.async_set(
        humidity_sensor.entity_id,
        "42",
        {
            ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY,
            ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE,
        },
    )
    hass.states.async_set(humidifier.entity_id, STATE_ON)

    def _mock_get_accessory(*args, **kwargs):
        return [None, "acc", None]

    with patch.object(homekit.bridge, "add_accessory"), patch(
        f"{PATH_HOMEKIT}.show_setup_message"
    ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
        "pyhap.accessory_driver.AccessoryDriver.start_service"
    ):
        await homekit.async_start()
    await hass.async_block_till_done()

    mock_get_acc.assert_called_with(
        hass,
        hk_driver,
        ANY,
        ANY,
        {
            "manufacturer": "Home Assistant",
            "model": "Smart Brainy Clever Humidifier",
            "sw_version": "0.16.1",
            "linked_humidity_sensor": "sensor.humidifier_humidity_sensor",
        },
    )