Esempio n. 1
0
    async def test_process_group_value_response(self):
        """Test precess of GroupValueResponse telegrams."""
        xknx = XKNX()
        switch = BinarySensor(
            xknx,
            "TestInput",
            group_address_state="1/2/3",
            ignore_internal_state=True,
        )
        async_after_update_callback = AsyncMock()

        switch.register_device_updated_cb(async_after_update_callback)

        write_telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueWrite(DPTBinary(1)),
        )
        response_telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            payload=GroupValueResponse(DPTBinary(1), ),
        )
        assert switch.state is None
        # initial GroupValueResponse changes state and runs callback
        await switch.process(response_telegram)
        assert switch.state
        async_after_update_callback.assert_called_once_with(switch)
        # GroupValueWrite with same payload runs callback because of `ignore_internal_state`
        async_after_update_callback.reset_mock()
        await switch.process(write_telegram)
        assert switch.state
        async_after_update_callback.assert_called_once_with(switch)
        # GroupValueResponse should not run callback when state has not changed
        async_after_update_callback.reset_mock()
        await switch.process(response_telegram)
        async_after_update_callback.assert_not_called()
async def test_check(coresys: CoreSys, dns_query: AsyncMock):
    """Test check for DNS server failures."""
    dns_server_failures = CheckDNSServerFailures(coresys)
    coresys.core.state = CoreState.RUNNING

    coresys.plugins.dns.servers = ["dns://1.1.1.1"]
    assert dns_server_failures.dns_servers == [
        "dns://1.1.1.1",
        "dns://192.168.30.1",
    ]
    assert len(coresys.resolution.issues) == 0

    await dns_server_failures.run_check.__wrapped__(dns_server_failures)
    assert dns_query.call_args_list == [
        call("_checkdns.home-assistant.io", "A"),
        call("_checkdns.home-assistant.io", "A"),
    ]
    assert len(coresys.resolution.issues) == 0

    dns_query.reset_mock()
    coresys.plugins.dns.servers = []
    assert dns_server_failures.dns_servers == ["dns://192.168.30.1"]

    dns_query.side_effect = DNSError()
    await dns_server_failures.run_check.__wrapped__(dns_server_failures)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "A")

    assert len(coresys.resolution.issues) == 1
    assert coresys.resolution.issues[0].type is IssueType.DNS_SERVER_FAILED
    assert coresys.resolution.issues[0].context is ContextType.DNS_SERVER
    assert coresys.resolution.issues[0].reference == "dns://192.168.30.1"
Esempio n. 3
0
async def test_consumer_with_key_parameter(mocker: MockFixture,
                                           kafka_data_type, topic):
    msg = SampleMessage(value=b"5678", key=b"1234")
    f = AsyncMock()
    topic._add(f, {"key"})
    await topic.message_handlers(msg)
    f.assert_called_once_with(key=b"1234")
Esempio n. 4
0
    async def test_process_callback_ignore_internal_state_no_counter(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,
        )
        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)),
        )
        await switch.process(telegram)
        # no _context_task started because context_timeout is False
        assert switch._context_task is None
        async_after_update_callback.assert_called_once_with(switch)

        async_after_update_callback.reset_mock()
        # send same telegram again
        await switch.process(telegram)
        async_after_update_callback.assert_called_once_with(switch)
async def test_slash_command_on_activity_calls_callback(message_sent):
    listener_callback = AsyncMock()
    slash_command = SlashCommandActivity("/command", False, listener_callback)
    context = create_command_context(message_sent)

    await slash_command.on_activity(context)
    listener_callback.assert_called_once_with(context)
Esempio n. 6
0
    async def test_callback_group_addresses(self):
        """Test telegram_received_callback after state of switch was changed."""
        xknx = XKNX()
        async_telegram_received_cb_one = AsyncMock()
        async_telegram_received_cb_two = AsyncMock()

        callback_one = xknx.telegram_queue.register_telegram_received_cb(
            async_telegram_received_cb_one,
            address_filters=[],
            group_addresses=[GroupAddress("1/2/3")],
        )
        callback_two = xknx.telegram_queue.register_telegram_received_cb(
            async_telegram_received_cb_two,
            address_filters=[],
            group_addresses=[])

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            direction=TelegramDirection.INCOMING,
            payload=GroupValueWrite(DPTBinary(1)),
        )
        await xknx.telegram_queue.process_telegram_incoming(telegram)
        async_telegram_received_cb_one.assert_called_once_with(telegram)
        async_telegram_received_cb_two.assert_not_called()

        async_telegram_received_cb_one.reset_mock()
        # modify the filters - add/remove a GroupAddress
        callback_one.group_addresses.remove(GroupAddress("1/2/3"))
        callback_two.group_addresses.append(GroupAddress("1/2/3"))
        await xknx.telegram_queue.process_telegram_incoming(telegram)
        async_telegram_received_cb_one.assert_not_called()
        async_telegram_received_cb_two.assert_called_once_with(telegram)
 async def test_collect(self):
     """Test the collect method."""
     mock_async_get_request = AsyncMock()
     mock_async_get_request.json.side_effect = [self.data_model, self.metrics]
     mocked_post = AsyncMock()
     mocked_post.return_value.close = Mock()
     with self.patched_get(mock_async_get_request):
         with patch("aiohttp.ClientSession.post", mocked_post):
             with self.assertRaises(RuntimeError):
                 await quality_time_collector.collect()
     mocked_post.assert_called_once_with(
         self.measurement_api_url,
         json=dict(
             sources=[
                 dict(
                     api_url=self.url,
                     landing_url=self.url,
                     value="42",
                     total="84",
                     entities=[],
                     connection_error=None,
                     parse_error=None,
                     source_uuid="source_id",
                 )
             ],
             metric_uuid="metric_uuid",
         ),
     )
Esempio n. 8
0
 async def test_create_spelltable_link(self, bot: SpellBot,
                                       monkeypatch: pytest.MonkeyPatch):
     bot.mock_games = False
     generate_link_mock = AsyncMock(return_value="http://mock")
     monkeypatch.setattr(client, "generate_link", generate_link_mock)
     link = await bot.create_spelltable_link()
     assert link == "http://mock"
     generate_link_mock.assert_called_once_with()
Esempio n. 9
0
 async def test_on_message_no_guild(self, bot: SpellBot,
                                    monkeypatch: pytest.MonkeyPatch):
     super_on_message_mock = AsyncMock()
     monkeypatch.setattr(Bot, "on_message", super_on_message_mock)
     message = MagicMock()
     message.guild = None
     await bot.on_message(message)
     super_on_message_mock.assert_called_once_with(message)
Esempio n. 10
0
    def test_initial_tick(self):
        f = AsyncMock()

        timer = Timer(100, f)
        timer.start()
        self.assertFalse(timer.stopped)
        f.assert_called_once_with()
        timer.stop()
        self.assertTrue(timer.stopped)
Esempio n. 11
0
async def test_multiple_message_handlers(mocker: MockFixture, kafka_data_type,
                                         topic):
    msg = SampleMessage(value=b"1234")
    mock_one = AsyncMock()
    mock_two = AsyncMock()
    topic._add(mock_one, {"value"})
    topic._add(mock_two, {"value"})
    await topic.message_handlers(msg)
    mock_one.assert_called_once_with(value=b"1234")
    mock_two.assert_called_once_with(value=b"1234")
Esempio n. 12
0
    async def test_register(self):
        """Test connection_state_changed after register."""

        xknx = XKNX()
        async_connection_state_changed_cb = AsyncMock()
        xknx.connection_manager.register_connection_state_changed_cb(
            async_connection_state_changed_cb)
        await xknx.connection_manager.connection_state_changed(
            XknxConnectionState.CONNECTED)
        async_connection_state_changed_cb.assert_called_once_with(
            XknxConnectionState.CONNECTED)
Esempio n. 13
0
    def test_send_announcement(self):
        """Tests that Player.send_announcement() calls websocket send()
        """
        websocket = MagicMock()
        send = AsyncMock()
        websocket.attach_mock(send, 'send')

        player = Player(None, websocket)
        asyncio.run(player.send_announcement("Breaking News!!!"))

        send.assert_called_once_with(
            '{"id": 1, "method": "announcement", "params": {"message": "Breaking News!!!"}}'
        )
Esempio n. 14
0
    async def test_register(self):
        """Test telegram_received_callback after state of switch was changed."""

        xknx = XKNX()
        async_telegram_received_cb = AsyncMock()
        xknx.telegram_queue.register_telegram_received_cb(async_telegram_received_cb)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            direction=TelegramDirection.INCOMING,
            payload=GroupValueWrite(DPTBinary(1)),
        )
        await xknx.telegram_queue.process_telegram_incoming(telegram)
        async_telegram_received_cb.assert_called_once_with(telegram)
Esempio n. 15
0
async def test_update_device_config(hass, hass_client):
    """Test updating device config."""
    with patch.object(config, "SECTIONS", ["group"]):
        await async_setup_component(hass, "config", {})

    client = await hass_client()

    orig_data = {
        "hello.beer": {
            "ignored": True
        },
        "other.entity": {
            "polling_intensity": 2
        },
    }

    def mock_read(path):
        """Mock reading data."""
        return orig_data

    written = []

    def mock_write(path, data):
        """Mock writing data."""
        written.append(data)

    mock_call = AsyncMock()

    with patch("homeassistant.components.config._read", mock_read), patch(
            "homeassistant.components.config._write",
            mock_write), patch.object(hass.services, "async_call", mock_call):
        resp = await client.post(
            "/api/config/group/config/hello_beer",
            data=json.dumps({
                "name": "Beer",
                "entities": ["light.top", "light.bottom"]
            }),
        )
        await hass.async_block_till_done()

    assert resp.status == 200
    result = await resp.json()
    assert result == {"result": "ok"}

    orig_data["hello_beer"]["name"] = "Beer"
    orig_data["hello_beer"]["entities"] = ["light.top", "light.bottom"]

    assert written[0] == orig_data
    mock_call.assert_called_once_with("group", "reload")
Esempio n. 16
0
    def test_abort_game(self):
        """Tests that abort_game() method calls handle_eliminated_players() once
        """
        player = MagicMock()
        send_announcement = AsyncMock()
        player.attach_mock(send_announcement, 'send_announcement')

        game = GameSession(0, [player])
        game.handle_eliminated_players = MagicMock()

        asyncio.run(game.abort_game())

        game.handle_eliminated_players.assert_called_once()
        send_announcement.assert_called_once_with(
            MESSAGE_NETWORK_ERROR_OCCURRED)
Esempio n. 17
0
    def test_send_question(self):
        """Tests that Player.send_question() calls websocket send()
        """
        question = Question('Question 1', ['A', 'B', 'C', 'D'], 'C')

        websocket = MagicMock()
        send = AsyncMock()
        websocket.attach_mock(send, 'send')

        player = Player(None, websocket)
        asyncio.run(player.send_question(question))

        send.assert_called_once_with(
            '{"id": 1, "method": "ask_question", "params": {"question": "Question 1", "choices": ["A", "B", "C", "D"]}}'
        )
Esempio n. 18
0
    def test_ws_handler_impl_throws_exception(self):
        """Tests when ws_handler_impl() encounters exception thrown from the callback. It is expected to eat up the exception.
        """

        callback = MagicMock()
        wss = WebsocketServer(64823, callback)
        handle_new_websocket = AsyncMock(
            side_effect=Exception("Error Occurred"))
        wss.callback.attach_mock(handle_new_websocket, 'handle_new_websocket')

        ws = MagicMock()

        asyncio.run(wss.ws_handler_impl(ws, None))

        handle_new_websocket.assert_called_once_with(ws)
Esempio n. 19
0
    async def test_connected_event(self):
        """Test connected event callback."""

        xknx = XKNX()
        async_connection_state_changed_cb = AsyncMock()
        xknx.connection_manager.register_connection_state_changed_cb(
            async_connection_state_changed_cb)

        assert not xknx.connection_manager.connected.is_set()

        await xknx.connection_manager.connection_state_changed(
            XknxConnectionState.CONNECTED)
        async_connection_state_changed_cb.assert_called_once_with(
            XknxConnectionState.CONNECTED)

        assert xknx.connection_manager.connected.is_set()
Esempio n. 20
0
    def test_player_send_json_rpc_request(self):
        """Tests that Player.send_json_rpc_request() calls websocket send()
        """
        websocket = MagicMock()
        send = AsyncMock()
        websocket.attach_mock(send, 'send')

        player = Player(None, websocket)
        string = "Player is " + str([player])

        params = dict()
        params['a'] = 'x'
        asyncio.run(player.send_json_rpc_request("general_request", params))

        send.assert_called_once_with(
            '{"id": 1, "method": "general_request", "params": {"a": "x"}}')
Esempio n. 21
0
    def test_send_answers(self):
        """Tests that Player.send_answers() calls websocket send()
        """
        question = Question('Question 1', ['A', 'B', 'C', 'D'], 'C')

        websocket = MagicMock()
        send = AsyncMock()
        websocket.attach_mock(send, 'send')

        player = Player(None, websocket)
        counts = [1, 0, 1, 0]
        asyncio.run(player.send_answers(question, counts))

        send.assert_called_once_with(
            '{"id": 1, "method": "answers", "params": {"question": {"question": "Question 1", "choices": ["A", "B", "C", "D"], "answer": "C"}, "choice_counts": [1, 0, 1, 0]}}'
        )
Esempio n. 22
0
async def test_git_clone(coresys: CoreSys, tmp_path: Path,
                         clone_from: AsyncMock, branch: str | None):
    """Test git clone."""
    fragment = f"#{branch}" if branch else ""
    repo = GitRepo(coresys, tmp_path, f"{REPO_URL}{fragment}")

    await repo.clone.__wrapped__(repo)

    kwargs = {"recursive": True, "depth": 1, "shallow-submodules": True}
    if branch:
        kwargs["branch"] = branch

    clone_from.assert_called_once_with(
        REPO_URL,
        str(tmp_path),
        **kwargs,
    )
Esempio n. 23
0
    async def test_process_to_callback(self, devices_process):
        """Test process_telegram_incoming with callback."""

        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)),
        )
        await xknx.telegram_queue.process_telegram_incoming(telegram)
        async_telegram_received_callback.assert_called_once_with(telegram)
        devices_process.assert_called_once_with(telegram)
Esempio n. 24
0
    async def test_register_with_outgoing_telegrams(self):
        """Test telegram_received_callback with outgoing telegrams."""

        xknx = XKNX()
        xknx.knxip_interface = AsyncMock()
        async_telegram_received_cb = AsyncMock()
        xknx.telegram_queue.register_telegram_received_cb(
            async_telegram_received_cb, None, None, True)

        telegram = Telegram(
            destination_address=GroupAddress("1/2/3"),
            direction=TelegramDirection.OUTGOING,
            payload=GroupValueWrite(DPTBinary(1)),
        )

        await xknx.telegram_queue.process_telegram_outgoing(telegram)
        async_telegram_received_cb.assert_called_once_with(telegram)
async def test_update_config_write_to_temp_file(hass, hass_client, tmpdir):
    """Test config with a temp file."""
    test_dir = await hass.async_add_executor_job(tmpdir.mkdir, "files")
    group_yaml = Path(test_dir / "group.yaml")

    with patch.object(group, "GROUP_CONFIG_PATH", group_yaml), patch.object(
        config, "SECTIONS", ["group"]
    ):
        await async_setup_component(hass, "config", {})

    client = await hass_client()

    orig_data = {
        "hello.beer": {"ignored": True},
        "other.entity": {"polling_intensity": 2},
    }
    contents = dump(orig_data)
    await hass.async_add_executor_job(write_utf8_file, group_yaml, contents)

    mock_call = AsyncMock()

    with patch.object(hass.services, "async_call", mock_call):
        resp = await client.post(
            "/api/config/group/config/hello_beer",
            data=json.dumps(
                {"name": "Beer", "entities": ["light.top", "light.bottom"]}
            ),
        )
        await hass.async_block_till_done()

    assert resp.status == HTTPStatus.OK
    result = await resp.json()
    assert result == {"result": "ok"}

    new_data = await hass.async_add_executor_job(load_yaml, group_yaml)

    assert new_data == {
        **orig_data,
        "hello_beer": {
            "name": "Beer",
            "entities": ["light.top", "light.bottom"],
        },
    }
    mock_call.assert_called_once_with("group", "reload")
Esempio n. 26
0
    def test_ws_handler_impl(self):
        """Tests whether ws_handler_impl() calls callback with correct arguments
        """

        callback = MagicMock()
        wss = WebsocketServer(64823, callback)
        handle_new_websocket = AsyncMock()
        wss.callback.attach_mock(handle_new_websocket, 'handle_new_websocket')

        ws = MagicMock()

        asyncio.run(wss.ws_handler_impl(ws, None))

        handle_new_websocket.assert_called_once_with(ws)

        # Sanity check the WebsocketCallbackInterface as well.
        wsci = WebsocketCallbackInterface()
        wsci.handle_new_websocket(None)
        wss = WebsocketServer(64823, wsci)
        asyncio.run(wss.ws_handler_impl(ws, None))
Esempio n. 27
0
    async def _async_test_service(
        service,
        data,
        method,
        payload=None,
        domain=DOMAIN,
        failure_side_effect=BulbException,
    ):
        err_count = len(
            [x for x in caplog.records if x.levelno == logging.ERROR])

        # success
        if method.startswith("async_"):
            mocked_method = AsyncMock()
        else:
            mocked_method = MagicMock()
        setattr(mocked_bulb, method, mocked_method)
        await hass.services.async_call(domain, service, data, blocking=True)
        if payload is None:
            mocked_method.assert_called_once()
        elif type(payload) == list:
            mocked_method.assert_called_once_with(*payload)
        else:
            mocked_method.assert_called_once_with(**payload)
        assert (len([x for x in caplog.records
                     if x.levelno == logging.ERROR]) == err_count)

        # failure
        if failure_side_effect:
            if method.startswith("async_"):
                mocked_method = AsyncMock(side_effect=failure_side_effect)
            else:
                mocked_method = MagicMock(side_effect=failure_side_effect)
            setattr(mocked_bulb, method, mocked_method)
            await hass.services.async_call(domain,
                                           service,
                                           data,
                                           blocking=True)
            assert (len([
                x for x in caplog.records if x.levelno == logging.ERROR
            ]) == err_count + 1)
async def test_approve(coresys: CoreSys, dns_query: AsyncMock):
    """Test approve existing DNS Server failure issues."""
    dns_server_failures = CheckDNSServerFailures(coresys)
    coresys.core.state = CoreState.RUNNING

    assert dns_server_failures.dns_servers == ["dns://192.168.30.1"]
    dns_query.side_effect = DNSError()

    assert await dns_server_failures.approve_check(reference="dns://1.1.1.1"
                                                   ) is False
    dns_query.assert_not_called()

    assert (await dns_server_failures.approve_check(
        reference="dns://192.168.30.1") is True)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "A")

    dns_query.reset_mock()
    dns_query.side_effect = None
    assert (await dns_server_failures.approve_check(
        reference="dns://192.168.30.1") is False)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "A")
Esempio n. 29
0
async def test_approve(coresys: CoreSys, dns_query: AsyncMock):
    """Test approve existing DNS Server IPv6 error issues."""
    dns_server_ipv6_errors = CheckDNSServerIPv6Errors(coresys)
    coresys.core.state = CoreState.RUNNING

    assert dns_server_ipv6_errors.dns_servers == ["dns://192.168.30.1"]
    dns_query.side_effect = DNSError(4, "Domain name not found")

    assert (await dns_server_ipv6_errors.approve_check(
        reference="dns://1.1.1.1") is False)
    dns_query.assert_not_called()

    assert (await dns_server_ipv6_errors.approve_check(
        reference="dns://192.168.30.1") is True)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA")

    dns_query.reset_mock()
    dns_query.side_effect = DNSError(
        1, "DNS server returned answer with no data")
    assert (await dns_server_ipv6_errors.approve_check(
        reference="dns://192.168.30.1") is False)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA")

    dns_query.reset_mock()
    dns_query.side_effect = None
    assert (await dns_server_ipv6_errors.approve_check(
        reference="dns://192.168.30.1") is False)
    dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA")
Esempio n. 30
0
    async def test_callback_raising(self, logging_exception_mock):
        """Test telegram_received_callback raising an exception."""
        xknx = XKNX()
        good_callback_1 = AsyncMock()
        bad_callback = AsyncMock(side_effect=Exception("Boom"))
        good_callback_2 = AsyncMock()

        xknx.telegram_queue.register_telegram_received_cb(good_callback_1)
        xknx.telegram_queue.register_telegram_received_cb(bad_callback)
        xknx.telegram_queue.register_telegram_received_cb(good_callback_2)

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

        good_callback_1.assert_called_once_with(telegram)
        bad_callback.assert_called_once_with(telegram)
        good_callback_2.assert_called_once_with(telegram)

        logging_exception_mock.assert_called_once_with(
            "Unexpected error while processing telegram_received_cb for %s",
            telegram,
        )