Example #1
0
    async def test_process_callback_always(self):
        """Test process / reading telegrams from telegram queue. Test if callback is called."""

        xknx = XKNX()
        sensor = NumericValue(
            xknx,
            "TestSensor",
            group_address="1/2/3",
            value_type="temperature",
            always_callback=True,
        )
        after_update_callback = AsyncMock()
        sensor.register_device_updated_cb(after_update_callback)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueWrite(DPTArray((0x01, 0x02))),
        )
        await sensor.process(telegram)
        after_update_callback.assert_called_with(sensor)
        assert sensor.last_telegram == telegram
        # every telegram shall trigger callback
        after_update_callback.reset_mock()
        await sensor.process(telegram)
        after_update_callback.assert_called_with(sensor)
async def test_auto_pull_tag_when_missing(agent, mocker):
    behavior = AutoPullBehavior.TAG
    inspect_mock = AsyncMock(side_effect=DockerError(
        status=404, data={'message': 'Simulated missing image'}))
    mocker.patch.object(agent.docker.images, 'inspect', new=inspect_mock)
    pull = await agent.check_image(imgref, query_digest, behavior)
    assert pull
    inspect_mock.assert_called_with(imgref.canonical)
Example #3
0
    def test_scraper(self, mock_save, mock_read: AsyncMock, mock_update_cache,
                     mock_delete):
        asyncio.run(check_new_posts())

        mock_read.assert_called_with("https://news.ycombinator.com/")
        mock_delete.assert_called_once()
        mock_update_cache.assert_called_once()
        assert mock_save.call_count == 30
async def test_sync_setup_entry_multiple_discoveries(hass: HomeAssistant):
    """Test async_setup_entry."""
    udn_0 = "uuid:device_1"
    location_0 = "http://192.168.1.1/desc.xml"
    mock_device_0 = MockDevice(udn_0)
    udn_1 = "uuid:device_2"
    location_1 = "http://192.168.1.2/desc.xml"
    mock_device_1 = MockDevice(udn_1)
    discoveries = [
        {
            DISCOVERY_LOCATION: location_0,
            DISCOVERY_NAME: mock_device_0.name,
            DISCOVERY_ST: mock_device_0.device_type,
            DISCOVERY_UDN: mock_device_0.udn,
            DISCOVERY_UNIQUE_ID: mock_device_0.unique_id,
            DISCOVERY_USN: mock_device_0.usn,
            DISCOVERY_HOSTNAME: mock_device_0.hostname,
        },
        {
            DISCOVERY_LOCATION: location_1,
            DISCOVERY_NAME: mock_device_1.name,
            DISCOVERY_ST: mock_device_1.device_type,
            DISCOVERY_UDN: mock_device_1.udn,
            DISCOVERY_UNIQUE_ID: mock_device_1.unique_id,
            DISCOVERY_USN: mock_device_1.usn,
            DISCOVERY_HOSTNAME: mock_device_1.hostname,
        },
    ]
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONFIG_ENTRY_UDN: mock_device_1.udn,
            CONFIG_ENTRY_ST: mock_device_1.device_type,
        },
    )

    config = {
        # no upnp
    }
    async_create_device = AsyncMock(return_value=mock_device_1)
    async_discover = AsyncMock()
    with patch.object(Device, "async_create_device",
                      async_create_device), patch.object(
                          Device, "async_discover", async_discover):
        # initialisation of component, no device discovered
        async_discover.return_value = []
        await async_setup_component(hass, "upnp", config)
        await hass.async_block_till_done()

        # loading of config_entry, device discovered
        async_discover.return_value = discoveries
        entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(entry.entry_id) is True

        # ensure device is stored/used
        async_create_device.assert_called_with(
            hass, discoveries[1][DISCOVERY_LOCATION])
Example #5
0
 async def test_emit(self):
     probe = AsyncMock()
     sub = SubscriptionConsumer(
         Application(),
         Subscription("foo", lambda record: 1, "group"),
         event_handlers={"event": [probe]},
     )
     await sub.emit("event", "foo", "bar")
     probe.assert_called_with("foo", "bar")
async def test_auto_pull_none_when_missing(agent, mocker):
    behavior = AutoPullBehavior.NONE
    inspect_mock = AsyncMock(side_effect=DockerError(
        status=404, data={'message': 'Simulated missing image'}))
    mocker.patch.object(agent.docker.images, 'inspect', new=inspect_mock)
    with pytest.raises(ImageNotAvailable) as e:
        await agent.check_image(imgref, query_digest, behavior)
    assert e.value.args[0] is imgref
    inspect_mock.assert_called_with(imgref.canonical)
Example #7
0
async def test_ports():
    """Test that different types of ports work."""
    mock_requests = AsyncMock(return_value=Future())
    mock_requests.return_value.set_result("")
    wlans = Wlans(WLANS, mock_requests)

    assert len(wlans.values()) == 2

    wlan = wlans["SSID 1"]
    assert wlan.id == "012345678910111213141516"
    assert wlan.bc_filter_enabled == False
    assert wlan.bc_filter_list == []
    assert wlan.dtim_mode == "default"
    assert wlan.dtim_na == 1
    assert wlan.dtim_ng == 1
    assert wlan.enabled is True
    assert wlan.group_rekey == 3600
    assert wlan.is_guest is False
    assert wlan.mac_filter_enabled is False
    assert wlan.mac_filter_list == []
    assert wlan.mac_filter_policy == "allow"
    assert wlan.minrate_na_advertising_rates is False
    assert wlan.minrate_na_beacon_rate_kbps == 6000
    assert wlan.minrate_na_data_rate_kbps == 6000
    assert wlan.minrate_na_enabled is False
    assert wlan.minrate_na_mgmt_rate_kbps == 6000
    assert wlan.minrate_ng_advertising_rates is False
    assert wlan.minrate_ng_beacon_rate_kbps == 1000
    assert wlan.minrate_ng_cck_rates_enabled is False
    assert wlan.minrate_ng_data_rate_kbps == 1000
    assert wlan.minrate_ng_enabled is False
    assert wlan.minrate_ng_mgmt_rate_kbps == 1000
    assert wlan.name == "SSID 1"
    assert wlan.name_combine_enabled is True
    assert wlan.name_combine_suffix == ""
    assert wlan.no2ghz_oui is False
    assert wlan.schedule == []
    assert wlan.security == "wpapsk"
    assert wlan.site_id == "5a32aa4ee4b0412345678910"
    assert wlan.usergroup_id == "012345678910111213141518"
    assert wlan.wep_idx == 1
    assert wlan.wlangroup_id == "012345678910111213141519"
    assert wlan.wpa_enc == "ccmp"
    assert wlan.wpa_mode == "wpa2"
    assert wlan.x_iapp_key == "01234567891011121314151617181920"
    assert wlan.x_passphrase == "password in clear text"

    await wlans.async_enable(wlan)
    mock_requests.assert_called_with("put",
                                     "/rest/wlanconf/012345678910111213141516",
                                     json={"enabled": True})

    await wlans.async_disable(wlan)
    mock_requests.assert_called_with("put",
                                     "/rest/wlanconf/012345678910111213141516",
                                     json={"enabled": False})
Example #8
0
    async def test_emit(self, subscription_conf):
        probe = AsyncMock()

        sub = BatchConsumer(
            subscription=subscription_conf,
            app=Application(kafka_servers=["foobar"]),
            event_handlers={"event": [probe]},
        )
        await sub.emit("event", "foo", "bar")
        probe.assert_called_with("foo", "bar")
Example #9
0
    async def test_device_updated_cb(self):
        """Test device updated cb is added to the device."""
        xknx = XKNX()
        after_update_callback = AsyncMock()
        device = Device(xknx,
                        "TestDevice",
                        device_updated_cb=after_update_callback)

        await device.after_update()
        after_update_callback.assert_called_with(device)
Example #10
0
async def test_call_response_handlers(monkeypatch):
    monkeypatch.setattr("chitanda.bot.config", {"webserver": {"enable": True}})
    handler1 = AsyncMock(return_value=True)
    handler2 = AsyncMock(return_value=True)
    chitanda = Chitanda()
    with patch.object(chitanda, "response_handlers") as handlers:
        handlers.__iter__.return_value = [handler1, handler2]
        await chitanda.call_response_handlers("abc")
        handler1.assert_called_with("abc")
        handler2.assert_called_with("abc")
    async def test_process_rpc_query_no_tags(
            self, mocked_get_entries_threaded: AsyncMock):
        # test that in case of missed tags, the remote search works like normal remote search
        parameters = {'first': 0, 'infohash_set': None, 'last': 100}
        json = dumps(parameters).encode('utf-8')

        await self.rqc.process_rpc_query(json)

        expected_parameters = {'infohash_set': None}
        expected_parameters.update(parameters)
        mocked_get_entries_threaded.assert_called_with(**expected_parameters)
Example #12
0
 async def test_run_adhoc_job(self):
     job = http_job()
     handler = AsyncMock()
     await adhoc.run_adhoc_job(
         mock_adhoc_job_model,
         handler,
         job
     )
     handler.assert_called_with(job)
     mock_adhoc_job_model.set_job_completed \
         .assert_called_with(job.job_id)
     return
Example #13
0
    async def test_run_task(self, runner, db):

        task_func = AsyncMock()
        task = Mock()
        task.name = "test"
        task.data = pickle.dumps(FooType(foo="foo"))

        with patch.dict(
            taskrunner._registered, {"test": (task_func, FooType)}, clear=True
        ):
            await runner.run_task(task)
            task_func.assert_called_with(runner, ANY)
Example #14
0
    async def test_process_callback_set(self):
        """Test setting value. Test if callback is called."""

        xknx = XKNX()
        after_update_callback = AsyncMock()
        num_value = NumericValue(
            xknx, "TestSensor", group_address="1/2/3", value_type="temperature"
        )
        num_value.register_device_updated_cb(after_update_callback)

        await num_value.set(21.0)
        await xknx.devices.process(xknx.telegrams.get_nowait())
        after_update_callback.assert_called_with(num_value)
Example #15
0
    async def test_process_callback(self):
        """Test process / reading telegrams from telegram queue. Test if callback was called."""

        xknx = XKNX()
        notification = Notification(xknx, "Warning", group_address="1/2/3")
        after_update_callback = AsyncMock()
        notification.register_device_updated_cb(after_update_callback)

        telegram_set = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueWrite(DPTArray(
                DPTString().to_knx("Ein Prosit!"))),
        )
        await notification.process(telegram_set)
        after_update_callback.assert_called_with(notification)
Example #16
0
    async def test_device_updated_callback(self):
        """Test if device updated callback is called correctly if device was updated."""
        xknx = XKNX()
        device1 = Device(xknx, "TestDevice1")
        device2 = Device(xknx, "TestDevice2")

        async_after_update_callback1 = AsyncMock()
        async_after_update_callback2 = AsyncMock()

        # Registering both callbacks
        xknx.devices.register_device_updated_cb(async_after_update_callback1)
        xknx.devices.register_device_updated_cb(async_after_update_callback2)

        # Triggering first device. Both callbacks to be called
        await device1.after_update()
        async_after_update_callback1.assert_called_with(device1)
        async_after_update_callback2.assert_called_with(device1)
        async_after_update_callback1.reset_mock()
        async_after_update_callback2.reset_mock()

        # Triggering 2nd device. Both callbacks have to be called
        await device2.after_update()
        async_after_update_callback1.assert_called_with(device2)
        async_after_update_callback2.assert_called_with(device2)
        async_after_update_callback1.reset_mock()
        async_after_update_callback2.reset_mock()

        # Unregistering first callback
        xknx.devices.unregister_device_updated_cb(async_after_update_callback1)

        # Triggering first device. Only second callback has to be called
        await device1.after_update()
        async_after_update_callback1.assert_not_called()
        async_after_update_callback2.assert_called_with(device1)
        async_after_update_callback1.reset_mock()
        async_after_update_callback2.reset_mock()

        # Unregistering second callback
        xknx.devices.unregister_device_updated_cb(async_after_update_callback2)

        # Triggering second device. No callback should be called
        await device2.after_update()
        async_after_update_callback1.assert_not_called()
        async_after_update_callback2.assert_not_called()
        async_after_update_callback1.reset_mock()
        async_after_update_callback2.reset_mock()
Example #17
0
    async def test_callback_no_filters(self):
        """Test telegram_received_callback after state of switch was changed."""
        xknx = XKNX()
        async_telegram_received_callback = AsyncMock()

        xknx.telegram_queue.register_telegram_received_cb(
            async_telegram_received_callback)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            direction=TelegramDirection.INCOMING,
            payload=GroupValueWrite(DPTBinary(1)),
        )
        xknx.telegrams.put_nowait(telegram)
        await xknx.telegram_queue._process_all_telegrams()

        async_telegram_received_callback.assert_called_with(telegram)
Example #18
0
async def test_websocket_accept_connection(scope: dict, headers: Headers,
                                           subprotocol: Optional[str],
                                           has_headers: bool) -> None:
    connection = ASGIWebsocketConnection(Quart(__name__), scope)
    mock_send = AsyncMock()
    await connection.accept_connection(mock_send, headers, subprotocol)

    if has_headers:
        mock_send.assert_called_with({
            "subprotocol": subprotocol,
            "type": "websocket.accept",
            "headers": encode_headers(headers),
        })
    else:
        mock_send.assert_called_with({
            "subprotocol": subprotocol,
            "type": "websocket.accept"
        })
Example #19
0
    async def test_process_callback(self):
        """Test process / reading telegrams from telegram queue. Test if callback is executed."""

        xknx = XKNX()
        cover = Cover(
            xknx,
            "TestCoverProcessCallback",
            group_address_long="1/2/1",
            group_address_short="1/2/2",
            group_address_stop="1/2/3",
            group_address_position="1/2/4",
            group_address_position_state="1/2/5",
            group_address_angle="1/2/6",
            group_address_angle_state="1/2/7",
        )

        after_update_callback = AsyncMock()

        cover.register_device_updated_cb(after_update_callback)
        for address, payload, _feature in [
            ("1/2/1", DPTBinary(1), "long"),
            ("1/2/2", DPTBinary(1), "short"),
            ("1/2/4", DPTArray(42), "position"),
            ("1/2/5", DPTArray(42), "position state"),
            ("1/2/6", DPTArray(42), "angle"),
            ("1/2/7", DPTArray(51), "angle state"),
        ]:
            telegram = Telegram(
                destination_address=GroupAddress(address),
                payload=GroupValueWrite(payload),
            )
            await cover.process(telegram)
            after_update_callback.assert_called_with(cover)
            after_update_callback.reset_mock()
        # Stop only when cover is travelling
        telegram = Telegram(GroupAddress("1/2/3"),
                            payload=GroupValueWrite(DPTBinary(1)))
        await cover.process(telegram)
        after_update_callback.assert_not_called()
        await cover.set_down()
        await cover.process(telegram)
        after_update_callback.assert_called_with(cover)

        await cover.stop()  # clean up tasks
Example #20
0
async def test_clients():
    """Test clients class."""
    mock_requests = AsyncMock(return_value=Future())
    mock_requests.return_value.set_result("")
    clients = Clients([WIRELESS_CLIENT], mock_requests)

    assert len(clients.values()) == 1

    client = clients[WIRELESS_CLIENT["mac"]]
    assert client.blocked is False
    assert client.essid == "SSID"
    assert client.hostname == "client"
    assert client.ip == "10.0.0.1"
    assert client.is_guest is False
    assert client.is_wired is False
    assert client.last_seen == 1587765360
    assert client.mac == WIRELESS_CLIENT["mac"]
    assert client.name == "Client 1"
    assert client.oui == "Apple"
    assert client.site_id == "5a32aa4ee4b0412345678910"
    assert client.sw_depth == -1
    assert client.sw_mac == "fc:ec:da:11:22:33"
    assert client.sw_port == 1
    assert client.rx_bytes == 12867114
    assert client.tx_bytes == 52852089
    assert client.uptime == 11904
    assert client.wired_rx_bytes == 0
    assert client.wired_tx_bytes == 0
    assert (
        client.__repr__() == f"<Client Client 1: 00:00:00:00:00:01 {WIRELESS_CLIENT}>"
    )

    await clients.async_block(WIRELESS_CLIENT["mac"])
    mock_requests.assert_called_with(
        "post", "/cmd/stamgr", json={"mac": WIRELESS_CLIENT["mac"], "cmd": "block-sta"}
    )

    await clients.async_unblock(WIRELESS_CLIENT["mac"])
    mock_requests.assert_called_with(
        "post",
        "/cmd/stamgr",
        json={"mac": WIRELESS_CLIENT["mac"], "cmd": "unblock-sta"},
    )
Example #21
0
async def test_load_unload_config_entry(
    hass: HomeAssistant,
    mock_connection_create: AsyncMock,
    mock_anthemav: AsyncMock,
    init_integration: MockConfigEntry,
) -> None:
    """Test load and unload AnthemAv component."""
    # assert avr is created
    mock_connection_create.assert_called_with(host="1.1.1.1",
                                              port=14999,
                                              update_callback=ANY)
    assert init_integration.state == config_entries.ConfigEntryState.LOADED

    # unload
    await hass.config_entries.async_unload(init_integration.entry_id)
    await hass.async_block_till_done()
    # assert unload and avr is closed
    assert init_integration.state == config_entries.ConfigEntryState.NOT_LOADED
    mock_anthemav.close.assert_called_once()
Example #22
0
async def test_async_setup_entry_default(opp: OpenPeerPower):
    """Test async_setup_entry."""
    udn = "uuid:device_1"
    location = "http://192.168.1.1/desc.xml"
    mock_device = MockDevice(udn)
    discoveries = [{
        DISCOVERY_LOCATION: location,
        DISCOVERY_NAME: mock_device.name,
        DISCOVERY_ST: mock_device.device_type,
        DISCOVERY_UDN: mock_device.udn,
        DISCOVERY_UNIQUE_ID: mock_device.unique_id,
        DISCOVERY_USN: mock_device.usn,
        DISCOVERY_HOSTNAME: mock_device.hostname,
    }]
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONFIG_ENTRY_UDN: mock_device.udn,
            CONFIG_ENTRY_ST: mock_device.device_type,
        },
    )

    config = {
        # no upnp
    }
    async_create_device = AsyncMock(return_value=mock_device)
    async_discover = AsyncMock()
    with patch.object(Device, "async_create_device",
                      async_create_device), patch.object(
                          Device, "async_discover", async_discover):
        # initialisation of component, no device discovered
        async_discover.return_value = []
        await async_setup_component(opp, "upnp", config)
        await opp.async_block_till_done()

        # loading of config_entry, device discovered
        async_discover.return_value = discoveries
        entry.add_to_opp(opp)
        assert await opp.config_entries.async_setup(entry.entry_id) is True

        # ensure device is stored/used
        async_create_device.assert_called_with(
            opp, discoveries[0][DISCOVERY_LOCATION])
Example #23
0
async def test_async_setup_entry_default(hass: HomeAssistant):
    """Test async_setup_entry."""
    udn = "uuid:device_1"
    location = "http://192.168.1.1/desc.xml"
    mock_device = MockDevice(udn)
    discovery = {
        ssdp.ATTR_SSDP_LOCATION: location,
        ssdp.ATTR_SSDP_ST: mock_device.device_type,
        ssdp.ATTR_UPNP_UDN: mock_device.udn,
        ssdp.ATTR_SSDP_USN: mock_device.usn,
    }
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONFIG_ENTRY_UDN: mock_device.udn,
            CONFIG_ENTRY_ST: mock_device.device_type,
        },
    )

    config = {
        # no upnp
    }
    async_create_device = AsyncMock(return_value=mock_device)
    mock_get_discovery = Mock()
    with patch.object(Device, "async_create_device",
                      async_create_device), patch.object(
                          ssdp, "async_get_discovery_info_by_udn_st",
                          mock_get_discovery):
        # initialisation of component, no device discovered
        mock_get_discovery.return_value = None
        await async_setup_component(hass, "upnp", config)
        await hass.async_block_till_done()

        # loading of config_entry, device discovered
        mock_get_discovery.return_value = discovery
        entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(entry.entry_id) is True

        # ensure device is stored/used
        async_create_device.assert_called_with(
            hass, discovery[ssdp.ATTR_SSDP_LOCATION])
Example #24
0
    async def test_process_callback_ignore_internal_state(self):
        """Test after_update_callback after state of switch was changed."""
        xknx = XKNX()
        switch = BinarySensor(
            xknx,
            "TestInput",
            group_address_state="1/2/3",
            ignore_internal_state=True,
            context_timeout=0.001,
        )
        async_after_update_callback = AsyncMock()

        switch.register_device_updated_cb(async_after_update_callback)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueWrite(DPTBinary(1)),
        )
        assert switch.counter == 0

        await switch.process(telegram)
        async_after_update_callback.assert_not_called()
        assert switch.counter == 1
        await switch._context_task
        async_after_update_callback.assert_called_with(switch)
        # once with counter 1 and once with counter 0
        assert async_after_update_callback.call_count == 2

        async_after_update_callback.reset_mock()
        # send same telegram again
        await switch.process(telegram)
        assert switch.counter == 1
        await switch.process(telegram)
        assert switch.counter == 2
        async_after_update_callback.assert_not_called()

        await switch._context_task
        async_after_update_callback.assert_called_with(switch)
        # once with counter 2 and once with counter 0
        assert async_after_update_callback.call_count == 2
        assert switch.counter == 0
Example #25
0
 async def test_schedule_adhoc_jobs(self):
     loop = asyncio.get_event_loop()
     scheduler_state = await mock_adhoc_scheduler()
     now = time.time()
     handler = AsyncMock()
     spacing = 0.01
     jobs = [
         adhoc_job(
             "job" + str(now + (i * spacing)),
             now + (i * spacing)
         )
         for i in range(1, 5)
     ]
     adhoc.schedule_adhoc_jobs(
         scheduler_state,
         loop,
         jobs,
         handler,
     )
     for i in range(1, 5):
         await asyncio.sleep(spacing)
         handler.assert_called_with(jobs[i - 1])
     return
Example #26
0
    async def test_process_callback(self):
        """Test process / reading telegrams from telegram queue. Test if callback was called."""
        xknx = XKNX()
        device = Device(xknx, "TestDevice")
        after_update_callback1 = AsyncMock()
        after_update_callback2 = AsyncMock()
        device.register_device_updated_cb(after_update_callback1)
        device.register_device_updated_cb(after_update_callback2)

        # Triggering first time. Both have to be called
        await device.after_update()
        after_update_callback1.assert_called_with(device)
        after_update_callback2.assert_called_with(device)
        after_update_callback1.reset_mock()
        after_update_callback2.reset_mock()

        # Triggering 2nd time. Both have to be called
        await device.after_update()
        after_update_callback1.assert_called_with(device)
        after_update_callback2.assert_called_with(device)
        after_update_callback1.reset_mock()
        after_update_callback2.reset_mock()

        # Unregistering first callback
        device.unregister_device_updated_cb(after_update_callback1)
        await device.after_update()
        after_update_callback1.assert_not_called()
        after_update_callback2.assert_called_with(device)
        after_update_callback1.reset_mock()
        after_update_callback2.reset_mock()

        # Unregistering second callback
        device.unregister_device_updated_cb(after_update_callback2)
        await device.after_update()
        after_update_callback1.assert_not_called()
        after_update_callback2.assert_not_called()
Example #27
0
    async def test_process_callback(self):
        """Test process / reading telegrams from telegram queue. Test if callback is called."""

        xknx = XKNX()
        sensor = RawValue(
            xknx,
            "TestSensor",
            2,
            group_address="1/2/3",
        )
        after_update_callback = AsyncMock()
        sensor.register_device_updated_cb(after_update_callback)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueWrite(DPTArray((0x01, 0x02))),
        )
        await sensor.process(telegram)
        after_update_callback.assert_called_with(sensor)
        assert sensor.last_telegram == telegram
        # consecutive telegrams with same payload shall only trigger one callback
        after_update_callback.reset_mock()
        await sensor.process(telegram)
        after_update_callback.assert_not_called()
Example #28
0
async def test_dpi_groups():
    """Test that different types of ports work."""
    mock_requests = AsyncMock(return_value=Future())
    mock_requests.return_value.set_result("")
    dpi_apps = DPIRestrictionApps(DPI_APPS, mock_requests)
    dpi_groups = DPIRestrictionGroups(DPI_GROUPS, mock_requests, dpi_apps)

    assert len(dpi_apps.values()) == 1
    assert len(dpi_groups.values()) == 2

    app: DPIRestrictionApp = dpi_apps["5f976f62e3c58f018ec7e17d"]
    assert app.id == "5f976f62e3c58f018ec7e17d"
    assert app.apps == []
    assert app.blocked
    assert app.cats == ["4"]
    assert app.enabled
    assert app.log
    assert app.site_id == "5ba29dd4e3c58f026e9d7c38"

    group: DPIRestrictionGroup = dpi_groups["5f976f4ae3c58f018ec7dff6"]
    assert group.id == "5f976f4ae3c58f018ec7dff6"
    assert not group.attr_no_delete
    assert group.attr_hidden_id == ""
    assert group.name == "No Media"
    assert group.site_id == "5ba29dd4e3c58f026e9d7c38"
    assert group.dpiapp_ids == ["5f976f62e3c58f018ec7e17d"]

    await dpi_groups.async_enable(group)
    mock_requests.assert_called_with("put",
                                     "/rest/dpiapp/5f976f62e3c58f018ec7e17d",
                                     json={"enabled": True})

    await dpi_groups.async_disable(group)
    mock_requests.assert_called_with("put",
                                     "/rest/dpiapp/5f976f62e3c58f018ec7e17d",
                                     json={"enabled": False})
Example #29
0
    async def test_bad_callback(self, logging_exception_mock):
        """Test handling callback raising an exception"""
        xknx = XKNX()
        device = Device(xknx, "TestDevice")
        good_callback_1 = AsyncMock()
        bad_callback = AsyncMock(side_effect=Exception("Boom"))
        good_callback_2 = AsyncMock()

        device.register_device_updated_cb(good_callback_1)
        device.register_device_updated_cb(bad_callback)
        device.register_device_updated_cb(good_callback_2)

        await device.after_update()
        good_callback_1.assert_called_with(device)
        bad_callback.assert_called_with(device)
        good_callback_2.assert_called_with(device)

        logging_exception_mock.assert_called_once_with(
            "Unexpected error while processing device_updated_cb for %s",
            device,
        )
Example #30
0
    async def test_add_device_to_scene(self):
        """Test the add_device_to_scene command of the tools function."""
        device_01 = create_device(DimmableLightingControl, random_address(),
                                  0x01, 0x01)
        device_02 = create_device(SwitchedLightingControl, random_address(),
                                  0x02, 0x02)
        device_05 = create_device(ClimateControl_Thermostat, random_address(),
                                  0x05, 0x04)
        device_07 = create_device(SensorsActuators_IOLink, random_address(),
                                  0x07, 0x03)
        devices[device_01.address] = device_01
        devices[device_02.address] = device_02
        devices[device_05.address] = device_05
        devices[device_07.address] = device_07

        mock_add_device_to_scene = AsyncMock()
        async with self.test_lock:
            with patch.object(pyinsteon.tools.aldb, "devices",
                              devices), patch.object(
                                  pyinsteon.tools.tools_base, "devices",
                                  devices), patch.object(
                                      pyinsteon.tools.aldb,
                                      "async_add_device_to_scene",
                                      mock_add_device_to_scene,
                                  ):
                # Add default links with input mode and default values for data1, data2, data3
                for device in [device_01, device_02, device_05, device_07]:
                    scene = random.randint(0, 255)
                    cmd_mgr, _, stdout = self.setup_cmd_tool(
                        ToolsAldb,
                        [
                            "add_device_to_scene",
                            str(device.address),
                            str(scene),
                            "",
                            "",
                            "",
                            "exit",
                        ],
                    )
                    mock_add_device_to_scene.call_count = 0
                    await cmd_mgr.async_cmdloop("")
                    assert mock_add_device_to_scene.call_count == 1
                    if device.cat == DeviceCategory.DIMMABLE_LIGHTING_CONTROL:
                        mock_add_device_to_scene.assert_called_with(
                            device, scene, 255, 28, 1)
                    else:
                        mock_add_device_to_scene.assert_called_with(
                            device, scene, 255, 0, 1)

                # Add default links with command line and background mode and default values for data1, data2, data3
                for device in [device_01, device_02, device_05, device_07]:
                    for command in [
                            "add_device_to_scene", "add_device_to_scene -b"
                    ]:
                        scene = random.randint(0, 255)
                        cmd_mgr, _, stdout = self.setup_cmd_tool(
                            ToolsAldb,
                            [
                                f"{command} {str(device.address)} {scene}",
                                "exit",
                            ],
                        )
                        mock_add_device_to_scene.call_count = 0
                        await cmd_mgr.async_cmdloop("")
                        assert mock_add_device_to_scene.call_count == 1
                        if device.cat == DeviceCategory.DIMMABLE_LIGHTING_CONTROL:
                            mock_add_device_to_scene.assert_called_with(
                                device, scene, 255, 28, 1)
                        else:
                            mock_add_device_to_scene.assert_called_with(
                                device, scene, 255, 0, 1)

                # Add default links with input mode with inputs for data1, data2, data3
                for device in [device_01, device_02, device_05, device_07]:
                    scene = random.randint(0, 255)
                    if device.cat == 0x02:
                        vals = [0, 255]
                        data1 = vals[random.randint(0, 1)]
                    else:
                        data1 = random.randint(0, 255)
                    if device.cat == 0x01:
                        data2 = random.randint(0, 2400) / 10
                    else:
                        data2 = random.randint(0, 255)
                    data3 = random.randint(0, 255)
                    cmd_mgr, _, stdout = self.setup_cmd_tool(
                        ToolsAldb,
                        [
                            "add_device_to_scene",
                            str(device.address),
                            str(scene),
                            str(data1),
                            str(data2),
                            str(data3),
                            "exit",
                        ],
                    )
                    mock_add_device_to_scene.call_count = 0
                    await cmd_mgr.async_cmdloop("")
                    assert mock_add_device_to_scene.call_count == 1
                    if device.cat == DeviceCategory.DIMMABLE_LIGHTING_CONTROL:
                        mock_add_device_to_scene.assert_called_with(
                            device, scene, data1, seconds_to_ramp_rate(data2),
                            data3)
                    else:
                        mock_add_device_to_scene.assert_called_with(
                            device, scene, data1, data2, data3)

                # Add default links with command line and background mode with inputs for data1, data2, data3
                for device in [device_01, device_02, device_05, device_07]:
                    for command in [
                            "add_device_to_scene", "add_device_to_scene -b"
                    ]:
                        scene = random.randint(0, 255)
                        if device.cat == 0x02:
                            vals = [0, 255]
                            data1 = vals[random.randint(0, 1)]
                        else:
                            data1 = random.randint(0, 255)
                        if device.cat == 0x01:
                            data2 = random.randint(0, 2400) / 10
                        else:
                            data2 = random.randint(0, 255)
                        data3 = random.randint(0, 255)
                        cmd_mgr, _, stdout = self.setup_cmd_tool(
                            ToolsAldb,
                            [
                                f"{command} {device.address} {scene} {data1}  {data2} {data3}",
                                "exit",
                            ],
                        )
                        mock_add_device_to_scene.call_count = 0
                        await cmd_mgr.async_cmdloop("")
                        assert mock_add_device_to_scene.call_count == 1
                        if device.cat == DeviceCategory.DIMMABLE_LIGHTING_CONTROL:
                            mock_add_device_to_scene.assert_called_with(
                                device, scene, data1,
                                seconds_to_ramp_rate(data2), data3)
                        else:
                            mock_add_device_to_scene.assert_called_with(
                                device, scene, data1, data2, data3)

                # Add default links with background mode with bad data for data1, data2, data3
                for device in [device_01, device_02, device_05, device_07]:
                    scene = random.randint(0, 255)
                    data1 = ["x", 255, 255]
                    data2 = [255, "x", 255]
                    data3 = [255, 200, "x"]
                    data4 = [300, 255, 255]
                    data5 = [255, 3000, 255]
                    data6 = [255, 255, 300]
                    for data in [data1, data2, data3, data4, data5, data6]:
                        cmd_mgr, _, stdout = self.setup_cmd_tool(
                            ToolsAldb,
                            [
                                f"add_device_to_scene -b {device.address} {scene} {data[0]}  {data[1]} {data[2]}",
                                "exit",
                            ],
                        )
                        mock_add_device_to_scene.call_count = 0
                        await cmd_mgr.async_cmdloop("")
                        assert mock_add_device_to_scene.call_count == 0

                # Add device to scene with no address
                cmd_mgr, _, _ = self.setup_cmd_tool(
                    ToolsAldb,
                    [
                        "add_device_to_scene",
                        "",
                        "exit",
                    ],
                )
                mock_add_device_to_scene.call_count = 0
                await cmd_mgr.async_cmdloop("")
                assert mock_add_device_to_scene.call_count == 0

                # Add device to scene in background mode with bad address
                cmd_mgr, _, _ = self.setup_cmd_tool(
                    ToolsAldb,
                    [
                        f"add_device_to_scene -b {bad_address}",
                        "exit",
                    ],
                )
                mock_add_device_to_scene.call_count = 0
                await cmd_mgr.async_cmdloop("")
                assert mock_add_device_to_scene.call_count == 0

                # Add device to scene in background mode with invalid address
                cmd_mgr, _, _ = self.setup_cmd_tool(
                    ToolsAldb,
                    [
                        "add_device_to_scene -b not.an.address 100",
                        "exit",
                    ],
                )
                mock_add_device_to_scene.call_count = 0
                await cmd_mgr.async_cmdloop("")
                assert mock_add_device_to_scene.call_count == 0

                # Add device to scene in background mode with invalid scene
                cmd_mgr, _, _ = self.setup_cmd_tool(
                    ToolsAldb,
                    [
                        f"add_device_to_scene -b {good_address} x",
                        "exit",
                    ],
                )
                mock_add_device_to_scene.call_count = 0
                await cmd_mgr.async_cmdloop("")
                assert mock_add_device_to_scene.call_count == 0