コード例 #1
0
    async def test_on_queue_message_bulk_size_bigger_that_one(self):
        """
        Confere que o handler real só é chamado quando o bucket atinge o limite máximo de
        tamanho. E que o handler é chamado com a lista de mensagens.
        * Bucket deve estart vazio após o "flush"
        """

        class MyBucket(Bucket):
            def pop_all(self):
                return self._items

        handler_mock = CoroutineMock()
        self.one_route_fixture["handler"] = handler_mock
        self.one_route_fixture["options"]["bulk_size"] = 2

        consumer = SSEConsumer(
            self.one_route_fixture, *(self.consumer_params + (MyBucket,))
        )

        result = await consumer.on_event(
            b"deployment_info", b'{"key": "value"}'
        )
        self.assertEqual(0, handler_mock.await_count)

        result = await consumer.on_event(
            b"deployment_info", b'{"key": "value"}'
        )
        handler_mock.assert_awaited_once_with(consumer.bucket._items)
コード例 #2
0
    def setUp(self):
        self.taskMethod = CoroutineMock(spec=some_task_to_run)
        self.now = datetime(2000, 1, 1, 0, 0, 0)

        patcher = patch('bot.utils.logException')
        self.addCleanup(patcher.stop)
        self.mock_logException = patcher.start()
コード例 #3
0
 async def test_chatCommand(self, mock_commands, mock_data, mock_log):
     command1 = CoroutineMock(spec=lambda args: False, return_value=False)
     command2 = CoroutineMock(spec=lambda args: False, return_value=True)
     command3 = CoroutineMock(spec=lambda args: False, return_value=False)
     mock_commands.return_value = [command1, command2, command3]
     data = MagicMock(spec=CacheStore)
     data.__aenter__.return_value = data
     data.__aexit__.return_value = True
     data.isPermittedUser.return_value = False
     data.isBotManager.return_value = False
     mock_data.return_value = data
     message = Mock(spec=Message)
     type(message).command = PropertyMock(return_value='Kappa')
     await channel.chatCommand(self.channel, self.tags, 'botgotsthis',
                               message, self.now)
     data.twitch_save_id.assert_has_calls(
         [call('2', 'megotsthis'),
          call('1', 'botgotsthis')])
     self.assertEqual(data.isPermittedUser.call_count, 1)
     self.assertEqual(data.isBotManager.call_count, 1)
     self.assertEqual(mock_commands.call_count, 1)
     self.assertEqual(command1.call_count, 1)
     self.assertEqual(command2.call_count, 1)
     self.assertEqual(command3.call_count, 0)
     self.assertEqual(mock_log.call_count, 0)
コード例 #4
0
async def _stream() -> WSStream:
    stream = WSStream(Config(), False, None, None, CoroutineMock(),
                      CoroutineMock(), 1)
    stream.spawn_app.return_value = CoroutineMock()
    stream.app_put = CoroutineMock()
    stream.config._log = AsyncMock(spec=Logger)
    return stream
コード例 #5
0
 async def setUp(self):
     self.one_route_fixture = {
         "routes": ["/asgard/counts/ok"],
         "handler": _handler,
         "options": {
             "vhost": "/",
             "bulk_size": 1,
             "bulk_flush_interval": 60,
         },
     }
     self.consumer_params = (
         "http://localhost:8080/v2/events",
         "guest",
         "guest",
     )
     self.consumer = SSEConsumer(self.one_route_fixture,
                                 *self.consumer_params)
     self.consumer.interval = 0
     self.logger_patcher = asynctest.mock.patch.object(
         conf,
         "logger",
         CoroutineMock(
             info=CoroutineMock(),
             debug=CoroutineMock(),
             error=CoroutineMock(),
         ),
     )
コード例 #6
0
ファイル: test_h11.py プロジェクト: miracle2k/hypercorn
async def _protocol(monkeypatch: MonkeyPatch) -> H11Protocol:
    MockHTTPStream = AsyncMock()  # noqa: N806
    MockHTTPStream.return_value = AsyncMock(spec=HTTPStream)
    monkeypatch.setattr(hypercorn.protocol.h11, "HTTPStream", MockHTTPStream)
    MockEvent = AsyncMock()  # noqa: N806
    MockEvent.return_value = AsyncMock(spec=IOEvent)
    return H11Protocol(Config(), False, None, None, CoroutineMock(), CoroutineMock(), MockEvent)
コード例 #7
0
 async def test_process_message_to_be_acked(self):
     expected_body = {"key": "value"}
     message = RabbitMQMessage(body=expected_body, delivery_tag=42)
     queue_mock = CoroutineMock(ack=CoroutineMock(), reject=CoroutineMock())
     await message.process(queue_mock)
     queue_mock.ack.assert_awaited_once_with(delivery_tag=42)
     self.assertEqual(0, queue_mock.reject.await_count)
コード例 #8
0
ファイル: test_config.py プロジェクト: PikalaxALT/BotGotsThis
    def setUp(self):
        patcher = patch('os.path.isfile')
        self.addCleanup(patcher.stop)
        self.mock_isfile = patcher.start()
        self.mock_isfile.return_value = True

        patcher = patch('os.path.isdir')
        self.addCleanup(patcher.stop)
        self.mock_isdir = patcher.start()
        self.mock_isdir.return_value = False

        patcher = patch('os.mkdir')
        self.addCleanup(patcher.stop)
        self.mock_mkdir = patcher.start()

        patcher = patch('aiofiles.open')
        self.addCleanup(patcher.stop)
        self.mock_open = patcher.start()

        self.file_mock = MagicMock()
        self.file_mock.__aenter__ = CoroutineMock()
        self.file_mock.__aenter__.return_value = self.file_mock
        self.file_mock.__aexit__ = CoroutineMock()
        self.file_mock.__aexit__.return_value = False
        self.file_mock.read = CoroutineMock()
        self.file_mock.read.return_value = config_data
        self.mock_open.return_value = self.file_mock
コード例 #9
0
 async def test_match_partner__first_partner_has_blocked_the_bot(self):
     stranger_mock = CoroutineMock()
     partner = CoroutineMock()
     partner.id = 31416
     self.stranger_service._match_partner = Mock(return_value=partner)
     self.stranger_service._locked_strangers_ids = Mock()
     self.stranger_service.get_stranger_by_id = Mock(
         return_value=stranger_mock)
     partner.notify_partner_found.side_effect = [StrangerError(), None]
     stranger_id = 271828
     await self.stranger_service.match_partner(stranger_id)
     self.assertEqual(
         self.stranger_service._locked_strangers_ids.discard.call_args_list,
         [
             call(partner.id),
             call(partner.id),
         ],
     )
     self.assertEqual(
         partner.notify_partner_found.call_args_list,
         [
             call(stranger_id),
             call(stranger_id),
         ],
     )
     stranger_mock.notify_partner_found.assert_called_once_with(partner.id)
コード例 #10
0
async def test_handle_message():
    player = PlayerNetworkChild(
        player_configuration=player_configuration,
        avatar=12,
        server_configuration=server_configuration,
        start_listening=False,
    )
    player._log_in = CoroutineMock()

    await player._handle_message("|challstr")
    player._log_in.assert_called_once()

    assert player.logged_in.is_set() is False
    await player._handle_message("|updateuser| username")
    assert player._logged_in.is_set() is True

    player._update_challenges = CoroutineMock()
    await player._handle_message("|updatechallenges")
    player._update_challenges.assert_called_once_with(["", "updatechallenges"])

    player._handle_battle_message = CoroutineMock()
    await player._handle_message(">battle|thing")
    player._handle_battle_message.assert_called_once_with([[">battle", "thing"]])

    await player._handle_message("|updatesearch")

    player._logger.warning = CoroutineMock()
    await player._handle_message("that was unexpected!|")
    player._logger.warning.assert_called_once_with(
        "Unhandled message: %s", "that was unexpected!|"
    )
コード例 #11
0
async def test_handle_message():
    player = PlayerNetworkChild(
        player_configuration=player_configuration,
        avatar=12,
        server_configuration=server_configuration,
        start_listening=False,
    )
    player._log_in = CoroutineMock()

    await player._handle_message("|challstr")
    player._log_in.assert_called_once()

    assert player.logged_in.is_set() is False
    await player._handle_message("|updateuser| username")
    assert player._logged_in.is_set() is True

    player._update_challenges = CoroutineMock()
    await player._handle_message("|updatechallenges")
    player._update_challenges.assert_called_once_with(["", "updatechallenges"])

    player._handle_battle_message = CoroutineMock()
    await player._handle_message(">battle|thing")
    player._handle_battle_message.assert_called_once_with([[">battle", "thing"]])

    await player._handle_message("|updatesearch")

    with pytest.raises(ShowdownException):
        await player._handle_message("|nametaken")

    player._logger.critical = CoroutineMock()
    with pytest.raises(NotImplementedError):
        await player._handle_message("that was unexpected!|")
    player._logger.critical.assert_called_once_with(
        "Unhandled message: %s", "that was unexpected!|"
    )
コード例 #12
0
 async def test_calls_get_alternate_accounts(self):
     backend = CoroutineMock(get_alternate_accounts=CoroutineMock())
     user = CoroutineMock()
     current_account = CoroutineMock()
     await UsersService.get_alternate_accounts(user, current_account,
                                               backend)
     backend.get_alternate_accounts.assert_awaited_with(
         user, current_account)
コード例 #13
0
    async def test_call_on_connect_callback(self):
        session_mock = CoroutineMock(get=CoroutineMock())
        self.consumer.session = session_mock

        with asynctest.patch.object(self.consumer, 'keep_runnig', side_effect=self.total_loops(1)), \
                asynctest.patch.object(self.consumer, "on_connection", side_effect=CoroutineMock()) as on_connection_mock:
            await self.consumer.start()
            self.assertEqual(1, on_connection_mock.call_count)
            self.assertEqual(1, on_connection_mock.await_count)
コード例 #14
0
    async def test_it_doesnt_calls_connect_if_queue_is_connected(self):
        async_queue = Mock(
            connection=Mock(is_connected=True, _connect=CoroutineMock()))
        coro = CoroutineMock()
        wrapped = _ensure_connected(coro)
        await wrapped(async_queue, 1, dog="Xablau")

        async_queue.connection._connect.assert_not_awaited()
        coro.assert_awaited_once_with(async_queue, 1, dog="Xablau")
コード例 #15
0
 async def wrapper(*args, **kwargs):
     with patch("kutana.storages.mongodb.AsyncIOMotorClient") as client:
         collection = Mock()
         collection.update_one = CoroutineMock()
         collection.create_index = CoroutineMock()
         collection.find_one = CoroutineMock()
         collection.delete_one = CoroutineMock()
         client.return_value = {"kutana": {"storage": collection}}
         return await coro(*args, storage=MongoDBStorage("mongo"), **kwargs)
コード例 #16
0
 async def test_starting_the_consumer_calls_on_consumer_starts_on_delegate_class(
         self):
     consumer = Mock(queue=self.queue, on_consumption_start=CoroutineMock())
     self.queue.delegate = consumer
     consumer_tag = 'Xablau'
     with patch.object(self.queue, 'consume',
                       CoroutineMock(return_value=consumer_tag)):
         await consumer.queue.start_consumer()
         consumer.on_consumption_start.assert_awaited_once_with(
             consumer_tag, queue=self.queue)
コード例 #17
0
        class Foo(AsyncQueueConsumerDelegate):
            loop = self.loop
            queue_name = q_name
            queue = self.queue

            on_connection_error = CoroutineMock()
            on_message_handle_error = CoroutineMock()
            on_queue_error = CoroutineMock()
            on_queue_message = CoroutineMock()
            on_consumer_start = CoroutineMock()
コード例 #18
0
    async def test_post_process(self):
        async def process(args):
            args.messages[0] = 'Kappa'

        mock_process = CoroutineMock(spec=process, side_effect=process)
        self.mock_list.postProcess.return_value = [mock_process]
        self.mock_split.return_value = []
        self.assertEqual(
            await library.create_messages(self.command, self.args), ['Kappa'])
        mock_process.assert_called_once_with(TypeMatch(CustomProcessArgs))
コード例 #19
0
async def test_came_in_1():
    store = Mock(EventReaderWriter)
    store.push_event = CoroutineMock()
    turnstile = TurnstileService(store)
    turnstile._check_deadline = CoroutineMock(return_value=False)

    assert not await turnstile.came_in('42')
    turnstile._check_deadline.assert_awaited_once()
    assert turnstile._check_deadline.await_args[0][0] == '42'
    store.push_event.assert_not_awaited()
コード例 #20
0
    async def test_reconect_if_unhandled_reconnected(self):
        session_mock = CoroutineMock(get=CoroutineMock(
            side_effect=["", Exception()]))
        self.consumer.session = session_mock

        with asynctest.patch.object(self.consumer, 'keep_runnig', side_effect=[True, True, False]), \
                asynctest.patch.object(self.consumer, "_consume_events", side_effect=CoroutineMock()) as consume_events_mock:
            await self.consumer.start()
            self.assertEqual(1, consume_events_mock.await_count)
            self.assertEqual(2, session_mock.get.call_count)
            self.assertEqual(1, session_mock.get.await_count)
コード例 #21
0
 async def test_process_log(self, mockopen):
     file_mock = MagicMock()
     file_mock.__aenter__ = CoroutineMock()
     file_mock.__aenter__.return_value = file_mock
     file_mock.__aexit__ = CoroutineMock()
     file_mock.__aexit__.return_value = True
     mockopen.return_value = file_mock
     bot.coroutine.logging._queue = deque([('log', 'Kappa')])
     await bot.coroutine.logging._process_log()
     self.assertTrue(mockopen.called)
     self.assertTrue(file_mock.write.called)
コード例 #22
0
    def test_differential(self, app, community):
        community.get_ud_block = CoroutineMock(
            return_value={'membersCount': 5})
        community.monetary_mass = CoroutineMock(return_value=500)
        referential = QuantitativeZSum(110, community, app, None)

        async def exec_test():
            value = await referential.value()
            self.assertEqual(value, 10)

        self.lp.run_until_complete(exec_test())
コード例 #23
0
    async def test_consume_again_if_reconnected(self):
        session_mock = CoroutineMock(get=CoroutineMock(
            side_effect=["", aiohttp.ClientError(), ""]))
        self.consumer.session = session_mock

        with asynctest.patch.object(self.consumer, 'keep_runnig', side_effect=[True, True, True, False]), \
                asynctest.patch.object(self.consumer, "_consume_events", side_effect=CoroutineMock()) as consume_events_mock:
            await self.consumer.start()
            self.assertEqual(2, consume_events_mock.await_count)
            self.assertEqual(3, session_mock.get.call_count)
            self.assertEqual(2, session_mock.get.await_count)
コード例 #24
0
async def test_client_write_small_message():
    writer = CoroutineMock()
    writer.drain = CoroutineMock()
    connection = PlayerConnection(reader=None, writer=writer)
    await connection.write({'test': 'test'})

    assert writer.method_calls == [
        call.write(b'{"test": "test"}'),
        call.write(b'\n'),
        call.drain(),
    ]
コード例 #25
0
 def setUp(self):
     from randtalkbot.stranger_sender import get_translation
     self.bot = CoroutineMock()
     self.stranger = Mock()
     self.stranger.telegram_id = 31416
     self.stranger.get_languages.return_value = 'foo_languages'
     self.sender = StrangerSender(self.bot, self.stranger)
     self.sender.sendMessage = CoroutineMock()
     self.get_translation = get_translation
     self.translation = self.get_translation.return_value
     self.translation.reset_mock()
コード例 #26
0
def asyncio_sleep(monkeypatch, sleep_queues):
    """Requests.get() mocked to return {'mock_key':'mock_response'}."""
    mock = CoroutineMock()
    monkeypatch.setattr(asyncio, "sleep", mock)

    async def sleeper(delay: float):
        await make_queue_waiter(sleep_queues[delay].called,
                                sleep_queues[delay].results)(delay)

    mock.side_effect = sleeper
    return mock
コード例 #27
0
 async def test_handle_command_begin(self):
     from randtalkbot.stranger_handler import datetime as datetime_mock
     from randtalkbot.stranger_handler import StrangerService
     datetime_mock.datetime.utcnow.return_value = datetime.datetime(1970, 1, 1)
     partner = CoroutineMock()
     partner.looking_for_partner_from = datetime.datetime(1970, 1, 1)
     stranger_service = StrangerService.get_instance.return_value
     stranger_service.match_partner = CoroutineMock(return_value=partner)
     message = Mock()
     await self.stranger_handler._handle_command_begin(message)
     self.stranger.prevent_advertising.assert_called_once_with()
     stranger_service.match_partner.assert_called_once_with(self.stranger)
コード例 #28
0
 def test_200_response(self):
     response = CoroutineMock()
     response.status = 200
     response.text.return_value = "this is my return value"
     self.mock_aiohttp_get.side_effect = [response]
     retval = yield from self.http_get_request(
         "https://www.example.com")  # NOQA
     expected = call('https://www.example.com',
                     headers={'Content-type': 'application/json'})
     self.assertEqual(self.mock_aiohttp_get.mock_calls, [expected])
     self.assertEqual(response.close.mock_calls, [])
     self.assertEqual(retval, "this is my return value")
コード例 #29
0
 async def test_reload_config(self, mock_bot, mock_reload):
     module = Mock()
     originalConfig = mock_bot.config
     mock_read = CoroutineMock()
     mock_bot._config.BotConfig.return_value.read_config = mock_read
     sys.modules = {'bot._config': module}
     self.assertIs(await reload.reload_config(self.send), True)
     self.assertEqual(self.send.call_count, 2)
     self.assertEqual(mock_reload.call_count, 1)
     mock_bot._config.BotConfig.assert_called_once_with()
     mock_read.assert_called_once_with()
     self.assertNotEqual(mock_bot.config, originalConfig)
コード例 #30
0
 async def test_handle_command_begin(self):
     from randtalkbot.stranger_handler import datetime as datetime_mock
     from randtalkbot.stranger_handler import StrangerService
     datetime_mock.datetime.utcnow.return_value = datetime.datetime(1970, 1, 1)
     partner = CoroutineMock()
     partner.looking_for_partner_from = datetime.datetime(1970, 1, 1)
     stranger_service = StrangerService.get_instance.return_value
     stranger_service.match_partner = CoroutineMock(return_value=partner)
     message = Mock()
     await self.stranger_handler._handle_command_begin(message)
     self.stranger.prevent_advertising.assert_called_once_with()
     stranger_service.match_partner.assert_called_once_with(self.stranger)
コード例 #31
0
 async def test_match_partner__ok(self):
     stranger = CoroutineMock()
     partner = CoroutineMock()
     partner.id = 31416
     self.stranger_service._match_partner = Mock(return_value=partner)
     self.stranger_service._locked_strangers_ids = Mock()
     await self.stranger_service.match_partner(stranger)
     self.stranger_service._locked_strangers_ids.discard. \
         assert_called_once_with(31416)
     stranger.notify_partner_found.assert_called_once_with(partner)
     partner.notify_partner_found.assert_called_once_with(stranger)
     stranger.set_partner.assert_called_once_with(partner)
コード例 #32
0
 async def test_match_partner__stranger_error(self):
     stranger = CoroutineMock()
     partner = CoroutineMock()
     partner.id = 31416
     self.stranger_service._match_partner = Mock(return_value=partner)
     self.stranger_service._locked_strangers_ids = Mock()
     stranger.notify_partner_found.side_effect = StrangerError()
     with self.assertRaises(StrangerServiceError):
         await self.stranger_service.match_partner(stranger)
     self.stranger_service._locked_strangers_ids.discard. \
         assert_called_once_with(31416)
     stranger.set_partner.assert_not_called()
コード例 #33
0
 async def test_match_partner__stranger_error(self):
     stranger_mock = CoroutineMock()
     partner = CoroutineMock()
     partner.id = 31416
     self.stranger_service._match_partner = Mock(return_value=partner)
     self.stranger_service._locked_strangers_ids = Mock()
     stranger_mock.notify_partner_found.side_effect = StrangerError()
     with self.assertRaises(StrangerServiceError):
         await self.stranger_service.match_partner(stranger_mock)
     self.stranger_service._locked_strangers_ids.discard. \
         assert_called_once_with(31416)
     stranger_mock.set_partner.assert_not_called()
コード例 #34
0
 def test_200_response(self):
     response = CoroutineMock()
     response.status = 200
     response.text.return_value = "this is my return value"
     self.mock_aiohttp_get.side_effect = [response]
     retval = yield from self.http_get_request("https://www.example.com")  # NOQA
     expected = call('https://www.example.com',
                     headers={
                         'Content-type': 'application/json'
                     })
     self.assertEqual(self.mock_aiohttp_get.mock_calls, [expected])
     self.assertEqual(response.close.mock_calls, [])
     self.assertEqual(retval, "this is my return value")
コード例 #35
0
 def test_non_200_response(self):
     response = CoroutineMock()
     response.status = 201
     response.text.return_value = "this is my return value"
     self.mock_aiohttp_get.side_effect = [response]
     retval = yield from self.http_get_auth_request("sekrit",
                                                    "https://www.example.com")  # NOQA
     expected = call('https://www.example.com',
                     headers={
                         'Authorization': 'Token sekrit',
                         'Content-type': 'application/json'
                     },
                     params={})
     self.assertEqual(self.mock_aiohttp_get.mock_calls, [expected])
     self.assertEqual(response.close.mock_calls, call())
     self.assertEqual(retval, "")
コード例 #36
0
 async def test_match_partner__first_partner_has_blocked_the_bot(self):
     stranger = CoroutineMock()
     partner = CoroutineMock()
     partner.id = 31416
     self.stranger_service._match_partner = Mock(return_value=partner)
     self.stranger_service._locked_strangers_ids = Mock()
     partner.notify_partner_found.side_effect = [StrangerError(), None]
     await self.stranger_service.match_partner(stranger)
     self.assertEqual(
         self.stranger_service._locked_strangers_ids.discard.call_args_list,
         [
             call(31416),
             call(31416),
             ],
         )
     self.assertEqual(
         partner.notify_partner_found.call_args_list,
         [
             call(stranger),
             call(stranger),
             ],
         )
     stranger.notify_partner_found.assert_called_once_with(partner)