async def test_async():
     with patch(f"{__name__}.async_func", AsyncMock()):
         self.assertIsInstance(async_func, AsyncMock)
     self.assertTrue(inspect.iscoroutinefunction(async_func))
Exemplo n.º 2
0
 def test_fire_registered_event_cancel(self):
     bot = Bot("app_name", "version")
     on_message = AsyncMock()
     on_message.__name__ = "on_message"
     on_message.return_value = False
     bot.register_event(on_message)
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     message = AsyncMock()
     message.content = "hello there"
     self._await(bot.on_message(message))
     on_message.assert_awaited_once_with(message)
     watcher_callback.assert_not_awaited()
Exemplo n.º 3
0
def _mock_account(*_):
    account = MagicMock()
    account.authenticate = AsyncMock()
    account.data = {CONF_EMAIL: TEST_EMAIL, ACCOUNT_HASH: "any"}
    return account
Exemplo n.º 4
0
 def test_mention_no_permission(self):
     bot = Bot("app_name", "version")
     bot.client.user.id = "12345"
     simple_callback = AsyncMock()
     bot.register_command("test", simple_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "<@12345> test hey"
     message.channel.__repr__ = lambda *a: "test_channel"
     message.guild.__repr__ = lambda *a: "test_guild"
     permissions = AsyncMock()
     permissions.send_messages = False
     message.channel.permissions_for = lambda u: permissions
     self._await(bot.on_message(message))
     simple_callback.assert_not_awaited()
     watcher_callback.assert_awaited_once_with(bot.client, message)
     fallback_callback.assert_not_awaited()
     message.author.create_dm.assert_awaited_once()
     message.author.dm_channel.send.assert_awaited_once_with(
         f"Hi, this bot doesn't have the permission to send a message to"
         f" #test_channel in server 'test_guild'")
Exemplo n.º 5
0
 def test_any_mention_off(self):
     bot = Bot("app_name", "version")
     bot.enforce_write_permission = False
     bot.any_mention = False
     bot.client.user.id = "12345"
     simple_callback = AsyncMock()
     bot.register_command("test", simple_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "test <@12345> arg0 arg1"
     message.channel.type == discord.ChannelType.private
     message.mentions = [bot.client.user]
     self._await(bot.on_message(message))
     simple_callback.assert_not_awaited()
     watcher_callback.assert_awaited_once_with(bot.client, message)
     fallback_callback.assert_not_awaited()
Exemplo n.º 6
0
async def test_shade(hass, zha_device_joined_restored, zigpy_shade_device):
    """Test zha cover platform for shade device type."""

    # load up cover domain
    zha_device = await zha_device_joined_restored(zigpy_shade_device)

    cluster_on_off = zigpy_shade_device.endpoints.get(1).on_off
    cluster_level = zigpy_shade_device.endpoints.get(1).level
    entity_id = await find_entity_id(Platform.COVER, zha_device, hass)
    assert entity_id is not None

    await async_enable_traffic(hass, [zha_device], enabled=False)
    # test that the cover was created and that it is unavailable
    assert hass.states.get(entity_id).state == STATE_UNAVAILABLE

    # allow traffic to flow through the gateway and device
    await async_enable_traffic(hass, [zha_device])
    await hass.async_block_till_done()

    # test that the state has changed from unavailable to off
    await send_attributes_report(hass, cluster_on_off, {8: 0, 0: False, 1: 1})
    assert hass.states.get(entity_id).state == STATE_CLOSED

    # test to see if it opens
    await send_attributes_report(hass, cluster_on_off, {8: 0, 0: True, 1: 1})
    assert hass.states.get(entity_id).state == STATE_OPEN

    # close from UI command fails
    with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
        await hass.services.async_call(Platform.COVER,
                                       SERVICE_CLOSE_COVER,
                                       {"entity_id": entity_id},
                                       blocking=True)
        assert cluster_on_off.request.call_count == 1
        assert cluster_on_off.request.call_args[0][0] is False
        assert cluster_on_off.request.call_args[0][1] == 0x0000
        assert hass.states.get(entity_id).state == STATE_OPEN

    with patch("zigpy.zcl.Cluster.request",
               AsyncMock(return_value=[0x1, zcl_f.Status.SUCCESS])):
        await hass.services.async_call(Platform.COVER,
                                       SERVICE_CLOSE_COVER,
                                       {"entity_id": entity_id},
                                       blocking=True)
        assert cluster_on_off.request.call_count == 1
        assert cluster_on_off.request.call_args[0][0] is False
        assert cluster_on_off.request.call_args[0][1] == 0x0000
        assert hass.states.get(entity_id).state == STATE_CLOSED

    # open from UI command fails
    assert ATTR_CURRENT_POSITION not in hass.states.get(entity_id).attributes
    await send_attributes_report(hass, cluster_level, {0: 0})
    with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
        await hass.services.async_call(Platform.COVER,
                                       SERVICE_OPEN_COVER,
                                       {"entity_id": entity_id},
                                       blocking=True)
        assert cluster_on_off.request.call_count == 1
        assert cluster_on_off.request.call_args[0][0] is False
        assert cluster_on_off.request.call_args[0][1] == 0x0001
        assert hass.states.get(entity_id).state == STATE_CLOSED

    # open from UI succeeds
    with patch("zigpy.zcl.Cluster.request",
               AsyncMock(return_value=[0x0, zcl_f.Status.SUCCESS])):
        await hass.services.async_call(Platform.COVER,
                                       SERVICE_OPEN_COVER,
                                       {"entity_id": entity_id},
                                       blocking=True)
        assert cluster_on_off.request.call_count == 1
        assert cluster_on_off.request.call_args[0][0] is False
        assert cluster_on_off.request.call_args[0][1] == 0x0001
        assert hass.states.get(entity_id).state == STATE_OPEN

    # set position UI command fails
    with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
        await hass.services.async_call(
            Platform.COVER,
            SERVICE_SET_COVER_POSITION,
            {
                "entity_id": entity_id,
                "position": 47
            },
            blocking=True,
        )
        assert cluster_level.request.call_count == 1
        assert cluster_level.request.call_args[0][0] is False
        assert cluster_level.request.call_args[0][1] == 0x0004
        assert int(cluster_level.request.call_args[0][3] * 100 / 255) == 47
        assert hass.states.get(
            entity_id).attributes[ATTR_CURRENT_POSITION] == 0

    # set position UI success
    with patch("zigpy.zcl.Cluster.request",
               AsyncMock(return_value=[0x5, zcl_f.Status.SUCCESS])):
        await hass.services.async_call(
            Platform.COVER,
            SERVICE_SET_COVER_POSITION,
            {
                "entity_id": entity_id,
                "position": 47
            },
            blocking=True,
        )
        assert cluster_level.request.call_count == 1
        assert cluster_level.request.call_args[0][0] is False
        assert cluster_level.request.call_args[0][1] == 0x0004
        assert int(cluster_level.request.call_args[0][3] * 100 / 255) == 47
        assert hass.states.get(
            entity_id).attributes[ATTR_CURRENT_POSITION] == 47

    # report position change
    await send_attributes_report(hass, cluster_level, {8: 0, 0: 100, 1: 1})
    assert hass.states.get(entity_id).attributes[ATTR_CURRENT_POSITION] == int(
        100 * 100 / 255)

    # test rejoin
    await async_test_rejoin(hass, zigpy_shade_device,
                            [cluster_level, cluster_on_off], (1, ))
    assert hass.states.get(entity_id).state == STATE_OPEN

    # test cover stop
    with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError):
        await hass.services.async_call(
            Platform.COVER,
            SERVICE_STOP_COVER,
            {"entity_id": entity_id},
            blocking=True,
        )
        assert cluster_level.request.call_count == 1
        assert cluster_level.request.call_args[0][0] is False
        assert cluster_level.request.call_args[0][1] in (0x0003, 0x0007)
Exemplo n.º 7
0
 def test_mention_command_regex(self):
     bot = Bot("app_name", "version")
     bot.enforce_write_permission = False
     bot.client.user.id = "12345"
     regex_callback = AsyncMock()
     bot.register_command("^t[eo]a?st$", regex_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "<@12345> toast hey"
     self._await(bot.on_message(message))
     regex_callback.assert_awaited_once_with(bot.client, message, "toast",
                                             "hey")
     watcher_callback.assert_awaited_once_with(bot.client, message)
     fallback_callback.assert_not_awaited()
 async def test_return_value_awaitable(self):
     fut = asyncio.Future()
     fut.set_result(None)
     mock = AsyncMock(return_value=fut)
     result = await mock()
     self.assertIsInstance(result, asyncio.Future)
    async def test_side_effect_is_AsyncMock(self):
        effect = AsyncMock(return_value=10)
        mock = AsyncMock(side_effect=effect)

        result = await mock()
        self.assertEqual(result, 10)
Exemplo n.º 10
0
 def test_is_async_AsyncMock(self):
     mock = AsyncMock(spec_set=AsyncClass.async_method)
     self.assertTrue(asyncio.iscoroutinefunction(mock))
     self.assertIsInstance(mock, AsyncMock)
Exemplo n.º 11
0
 async def test_return_value_AsyncMock(self):
     value = AsyncMock(return_value=10)
     mock = AsyncMock(return_value=value)
     result = await mock()
     self.assertIs(result, value)
Exemplo n.º 12
0
 def test_spec_as_normal_positional_AsyncMock(self):
     mock = AsyncMock(normal_func)
     self.assertIsInstance(mock, AsyncMock)
     m = mock()
     self.assertTrue(inspect.isawaitable(m))
     asyncio.run(m)
Exemplo n.º 13
0
 def test_isawaitable(self):
     mock = AsyncMock()
     m = mock()
     self.assertTrue(inspect.isawaitable(m))
     asyncio.run(m)
     self.assertIn('assert_awaited', dir(mock))
Exemplo n.º 14
0
 def test_iscoroutinefunction_default(self):
     mock = AsyncMock()
     self.assertTrue(asyncio.iscoroutinefunction(mock))
Exemplo n.º 15
0
 async def request(self, *args, **kwargs):
     mock_response = AsyncMock()
     mock_response.json = self.json
     mock_response.read = self.read
     return mock_response
Exemplo n.º 16
0
 def test_sync_magic_methods_return_magic_mocks(self):
     a_mock = AsyncMock()
     self.assertIsInstance(a_mock.__enter__, MagicMock)
     self.assertIsInstance(a_mock.__exit__, MagicMock)
     self.assertIsInstance(a_mock.__next__, MagicMock)
     self.assertIsInstance(a_mock.__len__, MagicMock)
Exemplo n.º 17
0
            check_experimental_feature_value, clear_rootcheck_database,
            clear_syscheck_database, get_cis_cat_results, get_hardware_info,
            get_hotfixes_info, get_network_address_info,
            get_network_interface_info, get_network_protocol_info, get_os_info,
            get_packages_info, get_ports_info, get_processes_info)
        from wazuh import ciscat, rootcheck, syscheck, syscollector
        from wazuh.tests.util import RBAC_bypasser
        wazuh.rbac.decorators.expose_resources = RBAC_bypasser
        del sys.modules['wazuh.rbac.orm']


@pytest.mark.asyncio
@patch('api.configuration.api_conf')
@patch(
    'api.controllers.experimental_controller.DistributedAPI.distribute_function',
    return_value=AsyncMock())
@patch('api.controllers.experimental_controller.remove_nones_to_dict')
@patch('api.controllers.experimental_controller.DistributedAPI.__init__',
       return_value=None)
@patch('api.controllers.experimental_controller.raise_if_exc',
       return_value=CustomAffectedItems())
@pytest.mark.parametrize('mock_alist', ['001', 'all'])
async def test_clear_rootcheck_database(mock_exc,
                                        mock_dapi,
                                        mock_remove,
                                        mock_dfunc,
                                        mock_exp,
                                        mock_alist,
                                        mock_request=MagicMock()):
    """Verify 'clear_rootcheck_database' endpoint is working as expected."""
    result = await clear_rootcheck_database(request=mock_request,
Exemplo n.º 18
0
 def test_asyncmock_has_sync_magic_methods(self):
     a_mock = AsyncMock()
     self.assertTrue(hasattr(a_mock, "__enter__"))
     self.assertTrue(hasattr(a_mock, "__exit__"))
     self.assertTrue(hasattr(a_mock, "__next__"))
     self.assertTrue(hasattr(a_mock, "__len__"))
Exemplo n.º 19
0
 def test_no_mention_minial(self):
     bot = Bot("app_name", "version")
     message = AsyncMock()
     message.content = "hello there"
     self._await(bot.on_message(message))
Exemplo n.º 20
0
class AsyncMockAssert(unittest.TestCase):
    def setUp(self):
        self.mock = AsyncMock()

    async def _runnable_test(self, *args, **kwargs):
        await self.mock(*args, **kwargs)

    async def _await_coroutine(self, coroutine):
        return await coroutine

    def test_assert_called_but_not_awaited(self):
        mock = AsyncMock(AsyncClass)
        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            mock.async_method()
        self.assertTrue(asyncio.iscoroutinefunction(mock.async_method))
        mock.async_method.assert_called()
        mock.async_method.assert_called_once()
        mock.async_method.assert_called_once_with()
        with self.assertRaises(AssertionError):
            mock.assert_awaited()
        with self.assertRaises(AssertionError):
            mock.async_method.assert_awaited()

    def test_assert_called_then_awaited(self):
        mock = AsyncMock(AsyncClass)
        mock_coroutine = mock.async_method()
        mock.async_method.assert_called()
        mock.async_method.assert_called_once()
        mock.async_method.assert_called_once_with()
        with self.assertRaises(AssertionError):
            mock.async_method.assert_awaited()

        asyncio.run(self._await_coroutine(mock_coroutine))
        # Assert we haven't re-called the function
        mock.async_method.assert_called_once()
        mock.async_method.assert_awaited()
        mock.async_method.assert_awaited_once()
        mock.async_method.assert_awaited_once_with()

    def test_assert_called_and_awaited_at_same_time(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited()

        with self.assertRaises(AssertionError):
            self.mock.assert_called()

        asyncio.run(self._runnable_test())
        self.mock.assert_called_once()
        self.mock.assert_awaited_once()

    def test_assert_called_twice_and_awaited_once(self):
        mock = AsyncMock(AsyncClass)
        coroutine = mock.async_method()
        with self.assertWarns(RuntimeWarning):
            # The first call will be awaited so no warning there
            # But this call will never get awaited, so it will warn here
            mock.async_method()
        with self.assertRaises(AssertionError):
            mock.async_method.assert_awaited()
        mock.async_method.assert_called()
        asyncio.run(self._await_coroutine(coroutine))
        mock.async_method.assert_awaited()
        mock.async_method.assert_awaited_once()

    def test_assert_called_once_and_awaited_twice(self):
        mock = AsyncMock(AsyncClass)
        coroutine = mock.async_method()
        mock.async_method.assert_called_once()
        asyncio.run(self._await_coroutine(coroutine))
        with self.assertRaises(RuntimeError):
            # Cannot reuse already awaited coroutine
            asyncio.run(self._await_coroutine(coroutine))
        mock.async_method.assert_awaited()

    def test_assert_awaited_but_not_called(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited()
        with self.assertRaises(AssertionError):
            self.mock.assert_called()
        with self.assertRaises(TypeError):
            # You cannot await an AsyncMock, it must be a coroutine
            asyncio.run(self._await_coroutine(self.mock))

        with self.assertRaises(AssertionError):
            self.mock.assert_awaited()
        with self.assertRaises(AssertionError):
            self.mock.assert_called()

    def test_assert_has_calls_not_awaits(self):
        kalls = [call('foo')]
        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            self.mock('foo')
        self.mock.assert_has_calls(kalls)
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(kalls)

    def test_assert_has_mock_calls_on_async_mock_no_spec(self):
        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            self.mock()
        kalls_empty = [('', (), {})]
        self.assertEqual(self.mock.mock_calls, kalls_empty)

        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            self.mock('foo')
            self.mock('baz')
        mock_kalls = ([call(), call('foo'), call('baz')])
        self.assertEqual(self.mock.mock_calls, mock_kalls)

    def test_assert_has_mock_calls_on_async_mock_with_spec(self):
        a_class_mock = AsyncMock(AsyncClass)
        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            a_class_mock.async_method()
        kalls_empty = [('', (), {})]
        self.assertEqual(a_class_mock.async_method.mock_calls, kalls_empty)
        self.assertEqual(a_class_mock.mock_calls, [call.async_method()])

        with self.assertWarns(RuntimeWarning):
            # Will raise a warning because never awaited
            a_class_mock.async_method(1, 2, 3, a=4, b=5)
        method_kalls = [call(), call(1, 2, 3, a=4, b=5)]
        mock_kalls = [
            call.async_method(),
            call.async_method(1, 2, 3, a=4, b=5)
        ]
        self.assertEqual(a_class_mock.async_method.mock_calls, method_kalls)
        self.assertEqual(a_class_mock.mock_calls, mock_kalls)

    def test_async_method_calls_recorded(self):
        with self.assertWarns(RuntimeWarning):
            # Will raise warnings because never awaited
            self.mock.something(3, fish=None)
            self.mock.something_else.something(6, cake=sentinel.Cake)

        self.assertEqual(self.mock.method_calls, [("something", (3, ), {
            'fish': None
        }), ("something_else.something", (6, ), {
            'cake': sentinel.Cake
        })], "method calls not recorded correctly")
        self.assertEqual(self.mock.something_else.method_calls,
                         [("something", (6, ), {
                             'cake': sentinel.Cake
                         })], "method calls not recorded correctly")

    def test_async_arg_lists(self):
        def assert_attrs(mock):
            names = ('call_args_list', 'method_calls', 'mock_calls')
            for name in names:
                attr = getattr(mock, name)
                self.assertIsInstance(attr, _CallList)
                self.assertIsInstance(attr, list)
                self.assertEqual(attr, [])

        assert_attrs(self.mock)
        with self.assertWarns(RuntimeWarning):
            # Will raise warnings because never awaited
            self.mock()
            self.mock(1, 2)
            self.mock(a=3)

        self.mock.reset_mock()
        assert_attrs(self.mock)

        a_mock = AsyncMock(AsyncClass)
        with self.assertWarns(RuntimeWarning):
            # Will raise warnings because never awaited
            a_mock.async_method()
            a_mock.async_method(1, a=3)

        a_mock.reset_mock()
        assert_attrs(a_mock)

    def test_assert_awaited(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited()

        asyncio.run(self._runnable_test())
        self.mock.assert_awaited()

    def test_assert_awaited_once(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited_once()

        asyncio.run(self._runnable_test())
        self.mock.assert_awaited_once()

        asyncio.run(self._runnable_test())
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited_once()

    def test_assert_awaited_with(self):
        msg = 'Not awaited'
        with self.assertRaisesRegex(AssertionError, msg):
            self.mock.assert_awaited_with('foo')

        asyncio.run(self._runnable_test())
        msg = 'expected await not found'
        with self.assertRaisesRegex(AssertionError, msg):
            self.mock.assert_awaited_with('foo')

        asyncio.run(self._runnable_test('foo'))
        self.mock.assert_awaited_with('foo')

        asyncio.run(self._runnable_test('SomethingElse'))
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited_with('foo')

    def test_assert_awaited_once_with(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited_once_with('foo')

        asyncio.run(self._runnable_test('foo'))
        self.mock.assert_awaited_once_with('foo')

        asyncio.run(self._runnable_test('foo'))
        with self.assertRaises(AssertionError):
            self.mock.assert_awaited_once_with('foo')

    def test_assert_any_wait(self):
        with self.assertRaises(AssertionError):
            self.mock.assert_any_await('foo')

        asyncio.run(self._runnable_test('baz'))
        with self.assertRaises(AssertionError):
            self.mock.assert_any_await('foo')

        asyncio.run(self._runnable_test('foo'))
        self.mock.assert_any_await('foo')

        asyncio.run(self._runnable_test('SomethingElse'))
        self.mock.assert_any_await('foo')

    def test_assert_has_awaits_no_order(self):
        calls = [call('foo'), call('baz')]

        with self.assertRaises(AssertionError) as cm:
            self.mock.assert_has_awaits(calls)
        self.assertEqual(len(cm.exception.args), 1)

        asyncio.run(self._runnable_test('foo'))
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(calls)

        asyncio.run(self._runnable_test('foo'))
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(calls)

        asyncio.run(self._runnable_test('baz'))
        self.mock.assert_has_awaits(calls)

        asyncio.run(self._runnable_test('SomethingElse'))
        self.mock.assert_has_awaits(calls)

    def test_assert_has_awaits_ordered(self):
        calls = [call('foo'), call('baz')]
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(calls, any_order=True)

        asyncio.run(self._runnable_test('baz'))
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(calls, any_order=True)

        asyncio.run(self._runnable_test('bamf'))
        with self.assertRaises(AssertionError):
            self.mock.assert_has_awaits(calls, any_order=True)

        asyncio.run(self._runnable_test('foo'))
        self.mock.assert_has_awaits(calls, any_order=True)

        asyncio.run(self._runnable_test('qux'))
        self.mock.assert_has_awaits(calls, any_order=True)

    def test_assert_not_awaited(self):
        self.mock.assert_not_awaited()

        asyncio.run(self._runnable_test())
        with self.assertRaises(AssertionError):
            self.mock.assert_not_awaited()

    def test_assert_has_awaits_not_matching_spec_error(self):
        async def f(x=None):
            pass

        self.mock = AsyncMock(spec=f)
        asyncio.run(self._runnable_test(1))

        with self.assertRaisesRegex(
                AssertionError, '^{}$'.format(
                    re.escape('Awaits not found.\n'
                              'Expected: [call()]\n'
                              'Actual: [call(1)]'))) as cm:
            self.mock.assert_has_awaits([call()])
        self.assertIsNone(cm.exception.__cause__)

        with self.assertRaisesRegex(
                AssertionError, '^{}$'.format(
                    re.escape('Error processing expected awaits.\n'
                              "Errors: [None, TypeError('too many positional "
                              "arguments')]\n"
                              'Expected: [call(), call(1, 2)]\n'
                              'Actual: [call(1)]'))) as cm:
            self.mock.assert_has_awaits([call(), call(1, 2)])
        self.assertIsInstance(cm.exception.__cause__, TypeError)
Exemplo n.º 21
0
 def test_mention_alias_command_simple(self):
     bot = Bot("app_name", "version", alias="|")
     bot.enforce_write_permission = False
     simple_callback = AsyncMock()
     bot.register_command("test", simple_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "|test hey"
     self._await(bot.on_message(message))
     simple_callback.assert_awaited_once_with(bot.client, message, "test",
                                              "hey")
     watcher_callback.assert_awaited_once_with(bot.client, message)
     fallback_callback.assert_not_awaited()
Exemplo n.º 22
0
 def setUp(self):
     self.mock = AsyncMock()
Exemplo n.º 23
0
 def test_mention_self(self):
     bot = Bot("app_name", "version")
     bot.enforce_write_permission = False
     bot.client.user.id = "12345"
     simple_callback = AsyncMock()
     bot.register_command("test", simple_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "<@12345> test arg0 arg1"
     message.author = bot.client.user
     self._await(bot.on_message(message))
     simple_callback.assert_not_awaited()
     watcher_callback.assert_not_awaited()
     fallback_callback.assert_not_awaited()
Exemplo n.º 24
0
async def test_protocol_send_end_data(protocol: H11Protocol) -> None:
    protocol.stream = AsyncMock()
    await protocol.stream_send(EndData(stream_id=1))
    assert protocol.stream is not None
Exemplo n.º 25
0
 def test_lower_command_names_off(self):
     bot = Bot("app_name", "version")
     bot.enforce_write_permission = False
     bot.lower_command_names = False
     bot.client.user.id = "12345"
     simple_callback = AsyncMock()
     bot.register_command("test", simple_callback, "short", "long")
     watcher_callback = AsyncMock()
     bot.register_watcher(watcher_callback)
     fallback_callback = AsyncMock()
     bot.register_fallback(fallback_callback)
     message = AsyncMock()
     message.content = "<@12345> Test arg0 arg1"
     self._await(bot.on_message(message))
     simple_callback.assert_not_awaited()
     watcher_callback.assert_awaited_once_with(bot.client, message)
     fallback_callback.assert_awaited_once_with(bot.client, message, "Test",
                                                "arg0", "arg1")
Exemplo n.º 26
0
def _get_mock_harmonyapi(connect=None, close=None):
    harmonyapi_mock = MagicMock()
    type(harmonyapi_mock).connect = AsyncMock(return_value=connect)
    type(harmonyapi_mock).close = AsyncMock(return_value=close)

    return harmonyapi_mock
Exemplo n.º 27
0
 def test_no_log(self):
     bot = Bot("app_name", "version")
     bot.guild_logs_file = None
     guild = AsyncMock()
     self._await(bot.on_guild_join(guild))
     self.assertFalse(path.exists(self.LOG_PATH))
Exemplo n.º 28
0
 async def test_multiple_attempts_with_error_before_end(self):
     mock = AsyncMock(side_effect=(Exception, Exception, None))
     await retry(attempts=3)(mock)()
     self.assertEqual(mock.await_args_list, [call()] * 3)
Exemplo n.º 29
0
async def test_two_step_flow(hass, client, enable_custom_integrations):
    """Test we can finish a two step flow."""
    mock_integration(
        hass, MockModule("test", async_setup_entry=AsyncMock(return_value=True))
    )
    mock_entity_platform(hass, "config_flow.test", None)

    class TestFlow(core_ce.ConfigFlow):
        VERSION = 1

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

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

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

    with patch.dict(HANDLERS, {"test": TestFlow}):
        resp = await client.post(
            f"/api/config/config_entries/flow/{flow_id}",
            json={"user_title": "user-title"},
        )
        assert resp.status == HTTPStatus.OK

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

        data = await resp.json()
        data.pop("flow_id")
        assert data == {
            "handler": "test",
            "type": "create_entry",
            "title": "user-title",
            "version": 1,
            "result": {
                "disabled_by": None,
                "domain": "test",
                "entry_id": entries[0].entry_id,
                "source": core_ce.SOURCE_USER,
                "state": core_ce.ConfigEntryState.LOADED.value,
                "supports_options": False,
                "supports_remove_device": False,
                "supports_unload": False,
                "pref_disable_new_entities": False,
                "pref_disable_polling": False,
                "title": "user-title",
                "reason": None,
            },
            "description": None,
            "description_placeholders": None,
            "options": {},
        }
Exemplo n.º 30
0
 def _func(recv_string_args):
     socket = AsyncMock()
     socket.send_string.return_value = {}
     socket.recv_string = partial(recv_string, recv_string_args)
     return socket