async def test_handle__other_wizard(self):
     self.stranger.wizard = "other_wizard"
     self.stranger_setup_wizard.activate = CoroutineMock()
     message = Mock()
     message.text = "foo_text"
     self.assertFalse((await self.stranger_setup_wizard.handle(message)))
     self.stranger_setup_wizard.activate.assert_not_called()
 async def test_handle_command__not_activated_command_start(self):
     self.stranger.wizard = "none"
     message = Mock()
     message.command = "start"
     self.stranger_setup_wizard.handle = CoroutineMock(return_value=True)
     self.assertFalse((await self.stranger_setup_wizard.handle_command(message)))
     self.stranger_setup_wizard.handle.assert_called_once_with(message)
 async def test_send__unknown_content_type(self):
     message = Mock()
     message.is_reply = False
     message.type = 'foo_type'
     with self.assertRaises(StrangerSenderError):
         await self.sender.send(message)
     self.sender.sendMessage.assert_not_called()
 def test_get_cached_stranger__cached(self):
     cached_stranger = Mock()
     cached_stranger.id = 31416
     self.stranger_service._strangers_cache[31416] = cached_stranger
     stranger = Mock()
     stranger.id = 31416
     self.assertEqual(self.stranger_service.get_cached_stranger(stranger), cached_stranger)
 async def test_handle_command__other_command(self, handle_command):
     from randtalkbot.admin_handler import StrangerHandler
     message = Mock()
     message.command = 'foo_command'
     message.command_args = 'foo_args'
     await self.admin_handler.handle_command(message)
     handle_command.assert_called_once_with(message)
 async def test_send__reply(self):
     message = Mock()
     message.is_reply = True
     message.type = 'text'
     with self.assertRaises(StrangerSenderError):
         await self.sender.send(message)
     self.sender.sendMessage.assert_not_called()
 async def test_on_chat_message__text_stranger_has_blocked_the_bot(self, handle_command_mock):
     from randtalkbot.stranger_handler import LOGGER
     from randtalkbot.stranger_handler import Message
     from randtalkbot.stranger_handler import telepot
     from randtalkbot.stranger_handler import StrangerError
     telepot.glance.return_value = 'text', 'private', 31416
     self.stranger_setup_wizard.handle.return_value = False
     message_json = {
         'text': 'message_text',
         }
     Message.return_value.command = None
     partner = Mock()
     partner.id = 27183
     self.stranger.get_partner = Mock(return_value=partner)
     self.stranger.id = 31416
     self.stranger.send_to_partner = CoroutineMock(side_effect=TelegramError({}, '', 0))
     await self.stranger_handler.on_chat_message(message_json)
     LOGGER.warning(
         'Send text. Can\'t send to partned: %d -> %d',
         31416,
         27183
         )
     self.sender.send_notification.assert_called_once_with(
         'Your partner has blocked me! How did you do that?!',
         )
def get_strangers():
    for stranger_json in STRANGERS:
        stranger = Mock()
        stranger.sex = stranger_json['sex']
        stranger.partner_sex = stranger_json['partner_sex']
        stranger.get_languages = Mock(return_value=stranger_json['languages'])
        yield stranger
 async def test_handle_command__start_no_invitation_is_in_setup(self):
     message = Mock()
     message.command_args = ''
     self.stranger.wizard = 'setup'
     self.stranger.invited_by = None
     await self.stranger_handler._handle_command_start(message)
     self.assertEqual(self.stranger.invited_by, None)
     self.sender.send_notification.assert_not_called()
 async def test_handle__deactivated_not_novice(self):
     self.stranger.wizard = "none"
     self.stranger.is_novice = Mock(return_value=False)
     self.stranger_setup_wizard.activate = CoroutineMock()
     message = Mock()
     message.text = "foo_text"
     self.assertFalse((await self.stranger_setup_wizard.handle(message)))
     self.stranger_setup_wizard.activate.assert_not_called()
 async def test_send__text(self):
     message = Mock()
     message.is_reply = False
     message.type = 'text'
     message.sending_kwargs = {
         'foo': 'bar',
         'baz': 'boo',
         }
     await self.sender.send(message)
     self.sender.sendMessage.assert_called_once_with(**message.sending_kwargs)
async def test_get_version(mock_service_client_get: mock.Mock):
    mock_service_client_get.return_value = mock.Mock(
        status_code=200, json=lambda: {"version": "6.6.6"}
    )

    result = await cat_api.get_version()

    expected_result = {"version": "6.6.6"}
    assert result == expected_result
    mock_service_client_get.assert_called_once_with("https://cat.gengo.com/api/status")
    def setUp(self):
        self.args = CustomFieldArgs('', None, None, None, None, Message(''),
                                    Mock(spec=Channel), 'botgotsthis',
                                    Mock(spec=ChatPermissionSet),
                                    datetime(2000, 1, 1))

        patcher = patch('lib.items.custom', autospec=True)
        self.addCleanup(patcher.stop)
        self.mock_list = patcher.start()
        self.mock_list.fields.return_value = []
async def test_leave():
    store = Mock(EventReaderWriter)
    store.push_event = CoroutineMock()
    turnstile = TurnstileService(store)

    await turnstile.leave('42')
    store.push_event.assert_awaited_once()
    event = store.push_event.await_args[0][0]
    assert event.type == TurnstileEventType.Leave
    assert event.object_name == '42'
def test_user_detail_success(mock_domain_find_user_by_id: mock.Mock):
    mock_domain_find_user_by_id.return_value = fixtures.user_fixture()

    response = client.get("/users/00000000000000000000000a")

    expected_response = (200, fixtures.user_json_fixture())
    assert (response.status_code, response.json()) == expected_response
    mock_domain_find_user_by_id.assert_called_once_with(
        user_id=dto.UserID("00000000000000000000000a")
    )
 async def test_handle_command_pay__no_command_args(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     message = Mock()
     message.command_args = None
     await self.admin_handler._handle_command_pay(message)
     stranger_service.get_stranger.assert_not_called()
     self.sender.send_notification.assert_called_once_with(
         'Please specify Telegram ID and bonus amount like this: `/pay 31416 10 Thanks!`',
         )
 async def test_ffz_broadcaster(self):
     self.data.ffz_get_cached_broadcasters.return_value = {}
     channel = Mock(spec=Channel)
     channel.channel = 'botgotsthis'
     channel.isStreaming = False
     channel.sessionData = {}
     self.mock_globals.channels = {'botgotsthis': channel}
     await emotes.refreshFfzRandomBroadcasterEmotes(self.now)
     self.data.ffz_load_broadcaster_emotes.assert_called_once_with(
         'botgotsthis', background=True)
    def setUp(self):
        self.connection = connection.ConnectionHandler(
            'Kappa', 'irc.twitch.tv', 6667)
        self.channel = Channel('botgotsthis', self.connection)
        self.whisper = WhisperMessage('botgotsthis', 'Kappa')

        self.mock_transport = Mock(spec=asyncio.Transport)
        self.mock_reader = Mock(asyncio.StreamReader)
        self.mock_writer = Mock(asyncio.StreamWriter)
        self.mock_writer.transort = self.mock_transport
Exemple #19
0
 async def test_handle_command__start_no_invitation(self):
     message = Mock()
     message.command_args = ''
     self.stranger.wizard = 'none'
     self.stranger.invited_by = None
     await self.stranger_handler._handle_command_start(message)
     self.assertEqual(self.stranger.invited_by, None)
     self.sender.send_notification.assert_called_once_with(
         '*Manual*\n\nUse /begin to start looking for a conversational partner, once'
         ' you\'re matched you can use /end to end the conversation.')
Exemple #20
0
 async def test_get_agent_by_id_call_backend_with_correct_params(self):
     agent_mock = Mock()
     user_mock = Mock()
     agent_id = "id"
     await self.agents_service.get_agent_by_id(agent_id,
                                               user_mock,
                                               agent_mock,
                                               backend=self.backend_mock)
     self.backend_mock.get_agent_by_id.assert_awaited_with(
         agent_id, user_mock, agent_mock)
def test_user_detail_not_found(mock_domain_find_user_by_id: mock.Mock):
    mock_domain_find_user_by_id.return_value = None

    response = client.get("/users/00000000000000000000000f")

    expected_response = (404, {"detail": "User not found."})
    assert (response.status_code, response.json()) == expected_response
    mock_domain_find_user_by_id.assert_called_once_with(
        user_id=dto.UserID("00000000000000000000000f")
    )
    def setUp(self):
        self.database = MagicMock(spec=DatabaseMain)
        self.database.__aenter__.return_value = self.database
        self.database.__aexit__.return_value = False
        self.send = Mock(spec=send)

        patcher = patch.object(DatabaseMain, 'acquire')
        self.addCleanup(patcher.stop)
        self.mock_database = patcher.start()
        self.mock_database.return_value = self.database
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()
Exemple #24
0
 async def test_handle_command_pay__no_command_args(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     message = Mock()
     message.command_args = None
     await self.admin_handler._handle_command_pay(message)
     stranger_service.get_stranger.assert_not_called()
     self.sender.send_notification.assert_called_once_with(
         'Please specify Telegram ID and bonus amount like this: `/pay 31416 10 Thanks!`',
     )
Exemple #25
0
 async def setUp(self):
     self._session_mock = CoroutineMock(
         post=CoroutineMock(),
         put=CoroutineMock(),
         delete=CoroutineMock(),
         get=CoroutineMock(),
         close=CoroutineMock(),
     )
     self.session_class_mock = Mock(return_value=self._session_mock)
     self.url = "https://httpbin.org/ip"
Exemple #26
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")
def test_list_users_pagination(mock_domain_list_users: mock.Mock):
    mock_domain_list_users.return_value = dto.UserSummaryPaginatedResponse(
        results=[
            dto.UserSummary(
                id=dto.UserID("00000000000000000000000a"),
                email="*****@*****.**",
                ctime=datetime(2020, 1, 1, 0, 0, tzinfo=UTC),
                mtime=datetime(2020, 1, 2, 0, 0, tzinfo=UTC),
            ),
            dto.UserSummary(
                id=dto.UserID("00000000000000000000000b"),
                email="*****@*****.**",
                ctime=datetime(2020, 1, 1, 0, 0, tzinfo=UTC),
                mtime=datetime(2020, 1, 2, 0, 0, tzinfo=UTC),
            ),
            dto.UserSummary(
                id=dto.UserID("00000000000000000000000c"),
                email="*****@*****.**",
                ctime=datetime(2020, 1, 1, 0, 0, tzinfo=UTC),
                mtime=datetime(2020, 1, 2, 0, 0, tzinfo=UTC),
            ),
        ],
        next_cursor=dto.UserID("00000000000000000000000c"),
    )

    response = client.get("/users?limit=3")

    expected_response = (
        200,
        {
            "results": [
                {
                    "id": "00000000000000000000000a",
                    "email": "*****@*****.**",
                    "ctime": "2020-01-01T00:00:00+00:00",
                    "mtime": "2020-01-02T00:00:00+00:00",
                },
                {
                    "id": "00000000000000000000000b",
                    "email": "*****@*****.**",
                    "ctime": "2020-01-01T00:00:00+00:00",
                    "mtime": "2020-01-02T00:00:00+00:00",
                },
                {
                    "id": "00000000000000000000000c",
                    "email": "*****@*****.**",
                    "ctime": "2020-01-01T00:00:00+00:00",
                    "mtime": "2020-01-02T00:00:00+00:00",
                },
            ],
            "next_cursor": "00000000000000000000000c",
        },
    )
    assert (response.status_code, response.json()) == expected_response
    assert mock_domain_list_users.called_once_with()
 async def test_ffz_broadcaster_recent(self):
     self.data.ffz_get_cached_broadcasters.return_value = {
         'botgotsthis': 3600,
     }
     channel = Mock(spec=Channel)
     channel.channel = 'botgotsthis'
     channel.isStreaming = False
     channel.sessionData = {}
     self.mock_globals.channels = {'botgotsthis': channel}
     await emotes.refreshFfzRandomBroadcasterEmotes(self.now)
     self.assertFalse(self.data.ffz_load_broadcaster_emotes.called)
Exemple #29
0
 async def test_it_raises_an_error_if_its_initialized_with_both_delegate_and_delegate_class(
         self):
     with self.assertRaises(ValueError):
         JsonQueue(
             host="diogommartins.com",
             username="******",
             password="******",
             loop=Mock(),
             delegate=Mock(),
             delegate_class=Mock(),
         )
 async def test_handle_command_pay(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     stranger = CoroutineMock()
     stranger_service.get_stranger.return_value = stranger
     message = Mock()
     message.command_args = '31416 27183 foo gratitude'
     await self.admin_handler._handle_command_pay(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     stranger.pay.assert_called_once_with(27183, 'foo gratitude')
     self.sender.send_notification.assert_called_once_with('Success.')
Exemple #31
0
    async def test_it_raises_and_error_if_put_message_isnt_json_serializeable(
            self):
        message = Mock()

        exchange = Mock()
        routing_key = Mock()
        with self.assertRaises(TypeError):
            await self.queue.put(message,
                                 exchange=exchange,
                                 routing_key=routing_key)
        self.queue.connection.channel.publish.assert_not_called()
 async def test_handle_command_clear(self):
     from randtalkbot.admin_handler import StrangerService
     stranger = CoroutineMock()
     stranger_service = StrangerService.get_instance.return_value
     stranger_service.get_stranger.return_value = stranger
     message = Mock()
     message.command_args = '31416'
     await self.admin_handler._handle_command_clear(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     stranger.end_talk.assert_called_once_with()
     self.sender.send_notification.assert_called_once_with('Stranger {0} was cleared', 31416)
 async def test_handle_command__start_no_invitation(self):
     message = Mock()
     message.command_args = ''
     self.stranger.wizard = 'none'
     self.stranger.invited_by = None
     await self.stranger_handler._handle_command_start(message)
     self.assertEqual(self.stranger.invited_by, None)
     self.sender.send_notification.assert_called_once_with(
         '*Manual*\n\nUse /begin to start looking for a conversational partner, once '
             'you\'re matched you can use /end to end the conversation.'
         )
Exemple #34
0
def favorites_fixture() -> Dict[int, HeosSource]:
    """Create favorites fixture."""
    station = Mock(HeosSource, autospec=True)
    station.type = const.TYPE_STATION
    station.name = "Today's Hits Radio"
    station.media_id = '123456789'
    radio = Mock(HeosSource, autospec=True)
    radio.type = const.TYPE_STATION
    radio.name = "Classical MPR (Classical Music)"
    radio.media_id = 's1234'
    return {1: station, 2: radio}
Exemple #35
0
 def setUp(self):
     self.now = datetime(2000, 1, 1)
     self.tags = IrcMessageTags()
     self.channel = Mock(spec=Channel)
     self.channel.channel = 'botgotsthis'
     self.data = Mock(spec=CacheStore)
     self.database = Mock(spec=DatabaseMain)
     self.permissions = MagicMock(spec=ChatPermissionSet)
     self.args = ChatCommandArgs(self.data,
                                 self.channel, self.tags, 'botgotsthis',
                                 Message(''), self.permissions, self.now)
 async def test_send__text(self):
     message = Mock()
     message.is_reply = False
     message.type = 'text'
     message.sending_kwargs = {
         'foo': 'bar',
         'baz': 'boo',
     }
     await self.sender.send(message)
     self.sender.sendMessage.assert_called_once_with(
         **message.sending_kwargs)
    def setUp(self):
        self.send = Mock(spec=send)

        patcher = patch('bot.config', autospec=True)
        self.addCleanup(patcher.stop)
        self.mock_config = patcher.start()
        self.mock_config.botnick = 'botgotsthis'

        patcher = patch('bot.utils.partChannel', autospec=True)
        self.addCleanup(patcher.stop)
        self.mock_part = patcher.start()
Exemple #38
0
    async def test_datagram_received_connect(self):
        self.proto.process_connect = Mock()
        mock_response = Mock()
        self.proto.process_connect.return_value = mock_response

        msg = struct.pack('!QII', 0x41727101980, 0, 1000)
        self.proto.datagram_received(msg, ('127.0.0.3', 8007))
        self.proto.process_connect.assert_called_with(('127.0.0.3', 8007),
                                                      0x41727101980, 1000, b'')
        self.proto.transport.sendto.assert_called_with(mock_response,
                                                       ('127.0.0.3', 8007))
Exemple #39
0
    async def test_datagram_received_announce(self):
        self.proto.process_announce = Mock()
        mock_response = Mock()
        self.proto.process_announce.return_value = mock_response

        msg = struct.pack('!QII', 0x123456, 1, 1000) + b'X' * 160
        self.proto.datagram_received(msg, ('127.0.0.3', 8007))
        self.proto.process_announce.assert_called_with(
            ('127.0.0.3', 8007), 0x123456, 1000, b'X' * 160)
        self.proto.transport.sendto.assert_called_with(mock_response,
                                                       ('127.0.0.3', 8007))
 async def test_handle_command_clear(self):
     from randtalkbot.admin_handler import StrangerService
     stranger = CoroutineMock()
     stranger_service = StrangerService.get_instance.return_value
     stranger_service.get_stranger.return_value = stranger
     message = Mock()
     message.command_args = '31416'
     await self.admin_handler._handle_command_clear(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     stranger.end_talk.assert_called_once_with()
     self.sender.send_notification.assert_called_once_with('Stranger {0} was cleared', 31416)
 async def test_handle_command_pay(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     stranger = CoroutineMock()
     stranger_service.get_stranger.return_value = stranger
     message = Mock()
     message.command_args = '31416 27183 foo gratitude'
     await self.admin_handler._handle_command_pay(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     stranger.pay.assert_called_once_with(27183, 'foo gratitude')
     self.sender.send_notification.assert_called_once_with('Success.')
 async def test_handle_command__full_stranger(self):
     self.stranger.wizard = "setup"
     self.stranger.wizard_step = "sex"
     self.stranger.is_full.return_value = True
     self.stranger_setup_wizard._prompt = CoroutineMock()
     self.stranger_setup_wizard.deactivate = CoroutineMock()
     message = Mock()
     message.command = "begin"
     self.assertFalse((await self.stranger_setup_wizard.handle_command(message)))
     self.stranger.is_full.assert_called_once_with()
     self.stranger_setup_wizard._prompt.assert_not_called()
     self.stranger_setup_wizard.deactivate.assert_called_once_with()
    def setUp(self):
        self.database = Mock(spec=DatabaseMain)
        self.send = Mock(spec=send)

        patcher = patch('bot.globals', autospec=True)
        self.addCleanup(patcher.stop)
        self.mock_globals = patcher.start()
        self.mock_globals.cluster = Mock(spec=ConnectionHandler)

        patcher = patch('bot.utils.joinChannel', autospec=True)
        self.addCleanup(patcher.stop)
        self.mock_join = patcher.start()
    async def test_handle__unknown_wizard_step(self):
        from randtalkbot.stranger_setup_wizard import LOGGER

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "unknown_step"
        self.stranger_setup_wizard._prompt = CoroutineMock()
        message = Mock()
        message.text = "foo_text"
        self.assertTrue((await self.stranger_setup_wizard.handle(message)))
        self.stranger_setup_wizard._prompt.assert_not_called()
        self.sender.send_notification.assert_not_called()
        LOGGER.warning.assert_called_once_with('Undknown wizard_step value was found: "%s"', "unknown_step")
Exemple #45
0
 async def test_it_doesnt_raise_value_error_if_max_message_length_is_zero(
         self):
     valid_value = 0
     queue = JsonQueue(
         host="diogommartins.com",
         username="******",
         password="******",
         loop=Mock(),
         delegate=Mock(),
         max_message_length=valid_value,
     )
     self.assertEqual(queue.max_message_length, valid_value)
    async def test_handle_command__telegram_error(self):
        from randtalkbot.stranger_setup_wizard import LOGGER

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "sex"
        self.stranger.is_full.return_value = False
        self.stranger_setup_wizard._prompt = CoroutineMock()
        message = Mock()
        message.command = "begin"
        self.sender.send_notification.side_effect = TelegramError({}, "", 0)
        self.assertTrue((await self.stranger_setup_wizard.handle_command(message)))
        self.assertTrue(LOGGER.warning.called)
Exemple #47
0
 async def test_match_partner__ok(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()
     await self.stranger_service.match_partner(stranger_mock)
     self.stranger_service._locked_strangers_ids.discard. \
         assert_called_once_with(31416)
     stranger_mock.notify_partner_found.assert_called_once_with(partner)
     partner.notify_partner_found.assert_called_once_with(stranger_mock)
     stranger_mock.set_partner.assert_called_once_with(partner)
Exemple #48
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()
 async def test_handle_command__not_full_stranger(self):
     self.stranger.wizard = "setup"
     self.stranger.wizard_step = "sex"
     self.stranger.is_full.return_value = False
     self.stranger_setup_wizard._prompt = CoroutineMock()
     message = Mock()
     message.command = "begin"
     self.assertTrue((await self.stranger_setup_wizard.handle_command(message)))
     self.sender.send_notification.assert_called_once_with(
         "Finish setup process please. After that you can start using bot."
     )
     self.stranger_setup_wizard._prompt.assert_called_once_with()
 async def test_handle__sex_ok(self):
     self.stranger.wizard = "setup"
     self.stranger.wizard_step = "sex"
     self.stranger_setup_wizard._prompt = CoroutineMock()
     self.stranger.sex = "some_sex"
     message = Mock()
     message.text = "foo_text"
     self.assertTrue((await self.stranger_setup_wizard.handle(message)))
     self.stranger.set_sex.assert_called_once_with("foo_text")
     self.stranger_setup_wizard._prompt.assert_called_once_with()
     self.assertEqual(self.stranger.wizard_step, "partner_sex")
     self.stranger.save.assert_called_once_with()
    async def test_handle__telegram_error(self):
        from randtalkbot.stranger_setup_wizard import LOGGER
        from randtalkbot.stranger_setup_wizard import get_languages_codes

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "languages"
        get_languages_codes.side_effect = EmptyLanguagesError()
        self.stranger_setup_wizard._prompt = CoroutineMock()
        message = Mock()
        message.text = "foo_text"
        self.sender.send_notification.side_effect = TelegramError({}, "", 0)
        self.assertTrue((await self.stranger_setup_wizard.handle(message)))
        self.assertTrue(LOGGER.warning.called)
 async def test_handle__sex_not_specified(self):
     self.stranger.wizard = "setup"
     self.stranger.wizard_step = "sex"
     self.stranger_setup_wizard._prompt = CoroutineMock()
     self.stranger_setup_wizard.deactivate = CoroutineMock()
     self.stranger.sex = "not_specified"
     message = Mock()
     message.text = "foo_text"
     self.assertTrue((await self.stranger_setup_wizard.handle(message)))
     self.stranger.set_sex.assert_called_once_with("foo_text")
     self.stranger_setup_wizard.deactivate.assert_called_once_with()
     self.stranger_setup_wizard._prompt.assert_not_called()
     self.stranger.save.assert_not_called()
 async def test_handle_command_pay__unknown_stranger(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     error = StrangerServiceError()
     stranger_service.get_stranger.side_effect = error
     message = Mock()
     message.command_args = '31416 27183'
     await self.admin_handler._handle_command_pay(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     self.sender.send_notification.assert_called_once_with(
         'Stranger wasn\'t found: {0}',
         error,
         )
 async def test_handle_command_clear__incorrect_telegram_id(self):
     from randtalkbot.admin_handler import StrangerService
     stranger_service = StrangerService.get_instance.return_value
     message = Mock()
     message.command_args = 'foo'
     await self.admin_handler._handle_command_clear(message)
     stranger_service.get_stranger.assert_not_called()
     self.assertEqual(
         self.sender.send_notification.call_args_list,
         [
             call('Is it really telegram_id: \"{0}\"?', 'foo'),
             call('Use it this way: `/clear 31416 27183`'),
             ],
         )
 async def test_on_chat_message__command_setup(self, handle_command_mock):
     from randtalkbot.stranger_handler import Message
     from randtalkbot.stranger_handler import telepot
     telepot.glance.return_value = 'text', 'private', 31416
     message_json = {
         'text': 'some_command_text'
         }
     message = Mock()
     message.command = 'foo_command'
     Message.return_value = message
     self.stranger_setup_wizard.handle_command.return_value = True
     await self.stranger_handler.on_chat_message(message_json)
     self.stranger.send_to_partner.assert_not_called()
     Message.assert_called_once_with(message_json)
     handle_command_mock.assert_not_called()
    async def test_handle__languages_empty_languages_error(self):
        from randtalkbot.stranger_setup_wizard import get_languages_codes
        from randtalkbot.errors import EmptyLanguagesError

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "languages"
        get_languages_codes.side_effect = EmptyLanguagesError()
        self.stranger_setup_wizard._prompt = CoroutineMock()
        message = Mock()
        message.text = "foo_text"
        self.assertTrue((await self.stranger_setup_wizard.handle(message)))
        get_languages_codes.assert_called_once_with("foo_text")
        self.stranger.set_languages.assert_not_called()
        self.stranger_setup_wizard._prompt.assert_called_once_with()
        self.sender.send_notification.assert_called_once_with("Please specify at least one language.")
    async def test_handle__languages_language_not_found(self):
        from randtalkbot.stranger_setup_wizard import get_languages_codes
        from randtalkbot.i18n import LanguageNotFoundError

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "languages"
        get_languages_codes.side_effect = LanguageNotFoundError("foo_lang")
        self.stranger_setup_wizard._prompt = CoroutineMock()
        message = Mock()
        message.text = "foo_text"
        self.assertTrue((await self.stranger_setup_wizard.handle(message)))
        get_languages_codes.assert_called_once_with("foo_text")
        self.stranger.set_languages.assert_not_called()
        self.stranger_setup_wizard._prompt.assert_called_once_with()
        self.sender.send_notification.assert_called_once_with('Language "{0}" wasn\'t found.', "foo_lang")
 async def test_handle_command__start_has_invalid_invitation_json_type(self):
     from randtalkbot.stranger_handler import StrangerService
     message = Mock()
     message.command_args = 'foo_args'
     message.decode_command_args.return_value = [1, 2, 3]
     self.stranger.wizard = 'none'
     self.stranger.invited_by = None
     stranger_service = StrangerService.get_instance.return_value
     await self.stranger_handler._handle_command_start(message)
     stranger_service.get_stranger_by_invitation.assert_not_called()
     self.assertEqual(self.stranger.invited_by, None)
     self.sender.send_notification.assert_called_once_with(
         '*Manual*\n\nUse /begin to start looking for a conversational partner, once '
             'you\'re matched you can use /end to end the conversation.'
         )
    async def test_handle__partner_sex_sex_error(self):
        from randtalkbot.errors import SexError

        self.stranger.wizard = "setup"
        self.stranger.wizard_step = "partner_sex"
        self.stranger_setup_wizard._prompt = CoroutineMock()
        self.stranger.set_partner_sex.side_effect = SexError("foo_sex")
        message = Mock()
        message.text = "foo_text"
        self.assertTrue((await self.stranger_setup_wizard.handle(message)))
        self.stranger.set_partner_sex.assert_called_once_with("foo_text")
        self.stranger_setup_wizard._prompt.assert_called_once_with()
        self.sender.send_notification.assert_called_once_with(
            'Unknown sex: "{0}" -- is not a valid sex name.', "foo_sex"
        )
 async def test_handle_command_clear__unknown_stranger(self):
     from randtalkbot.admin_handler import StrangerService
     error = StrangerServiceError()
     stranger_service = StrangerService.get_instance.return_value
     stranger_service.get_stranger.side_effect = error
     message = Mock()
     message.command_args = '31416'
     await self.admin_handler._handle_command_clear(message)
     stranger_service.get_stranger.assert_called_once_with(31416)
     self.assertEqual(
         self.sender.send_notification.call_args_list,
         [
             call('Stranger {0} wasn\'t found: {1}', 31416, error),
             call('Use it this way: `/clear 31416 27183`'),
             ],
         )