Beispiel #1
0
async def test_get_random_actor_paged(client, token):
    with mock.patch.object(TMDbClient, 'get_data') as _get_data, \
            mock.patch('atmdb.client.random.randrange', return_value=15) as randrange:
        first_page = future_from({
            'page': 1,
            'results': [{}] * 10,
            'total_results': 20,
            'total_pages': 2,
        })
        second_page = future_from({
            'page': 2,
            'results': ([{}] * 4) + [{'id': 1, 'name': 'Some Person'}, {}],
            'total_results': 20,
            'total_pages': 2,
        })
        person = future_from({'biography': 'extra stuff'})
        _get_data.side_effect = [first_page, second_page, person]

        result = await client.get_random_popular_person(1)

        assert result.name == 'Some Person'
        assert result.biography == 'extra stuff'
        _get_data.assert_has_calls([
            mock.call('https://api.themoviedb.org/3/person/popular'
                      '?page=1&api_key={}'.format(token)),
            mock.call('https://api.themoviedb.org/3/person/popular'
                      '?page=2&api_key={}'.format(token)),
            mock.call('https://api.themoviedb.org/3/person/1'
                      '?api_key={}'.format(token)),
        ])
Beispiel #2
0
    def test_successful_http_post(self):
        self.mock_http_post_request.side_effect = [True]
        self.mock_get_trigger_payload.return_value = {
            "payload": "test payload"
        }

        yield from self.pd.trigger_escalation_incident("service1",
                                                       self.slack_message)
        expected_slack_user_call = call(self.pd.slack, "U2147483697")
        self.mock_slack_user.assert_has_calls([expected_slack_user_call])

        expected_http_post_call = call(
            url="https://events.pagerduty.com/generic/2010-04-15/create_event.json",  # NOQA
            payload='{"payload": "test payload"}'
        )
        self.mock_http_post_request.assert_has_calls([expected_http_post_call])

        expected_send_channel_message_call = call(
            "C2147483705",
            "Successfully escalated this service1 incident!"  # NOQA
        )
        self.pd.slack.send_channel_message.assert_has_calls(
            [expected_send_channel_message_call]
        )
        self.assertEqual(len(self.pd.slack.send_channel_message.mock_calls), 2)
 async def test_send_notification__with_reply_markup_with_keyboard(self):
     self.translation.return_value = 'foo_translation'
     await self.sender.send_notification(
         'foo',
         reply_markup={
             'keyboard': [['fff', 'bar'], ['baz', 'boo']],
             },
         )
     self.assertEqual(
         self.translation.call_args_list,
         [call('foo'), call('fff'), call('bar'), call('baz'), call('boo'), ],
         )
     self.sender.sendMessage.assert_called_once_with(
         '*Rand Talk:* foo_translation',
         disable_notification=None,
         disable_web_page_preview=None,
         parse_mode='Markdown',
         reply_markup={
             'keyboard': [
                 ['foo_translation', 'foo_translation'],
                 ['foo_translation', 'foo_translation'],
                 ],
             'one_time_keyboard': True,
             },
         )
 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)
 async def test_send_notification__with_reply_markup_with_keyboard(self):
     self.translation.return_value = 'foo_translation'
     await self.sender.send_notification(
         'foo',
         reply_markup={
             'keyboard': [['fff', 'bar'], ['baz', 'boo']],
         },
     )
     self.assertEqual(
         self.translation.call_args_list,
         [
             call('foo'),
             call('fff'),
             call('bar'),
             call('baz'),
             call('boo'),
         ],
     )
     self.sender.sendMessage.assert_called_once_with(
         '*Rand Talk:* foo_translation',
         disable_notification=None,
         disable_web_page_preview=None,
         parse_mode='Markdown',
         reply_markup={
             'keyboard': [
                 ['foo_translation', 'foo_translation'],
                 ['foo_translation', 'foo_translation'],
             ],
             'one_time_keyboard':
             True,
         },
     )
Beispiel #6
0
async def test_ack_failure(
    subscriber: SinglePartitionSingleSubscriber,
    underlying,
    transformer,
    ack_set_tracker,
):
    ack_called_queue = asyncio.Queue()
    ack_result_queue = asyncio.Queue()
    ack_set_tracker.ack.side_effect = make_queue_waiter(
        ack_called_queue, ack_result_queue)
    async with subscriber:
        message = SequencedMessage(cursor=Cursor(offset=1), size_bytes=5)
        underlying.read.return_value = message
        read: Message = await subscriber.read()
        ack_set_tracker.track.assert_has_calls([call(1)])
        read.ack()
        await ack_called_queue.get()
        ack_set_tracker.ack.assert_has_calls([call(1)])
        await ack_result_queue.put(FailedPrecondition("Bad ack"))

        async def sleep_forever():
            await asyncio.sleep(float("inf"))

        underlying.read.side_effect = sleep_forever
        with pytest.raises(FailedPrecondition):
            await subscriber.read()
    def test_list_of_map_with_of_and_custom_attribute(self, mocker):
        class CustomMapAttribute(MapAttribute):
            custom = NumberAttribute()

            def __eq__(self, other):
                return self.custom == other.custom

        serialize_mock = mocker.spy(
            CustomMapAttribute.custom,
            'serialize',
        )
        deserialize_mock = mocker.spy(CustomMapAttribute.custom, 'deserialize')

        attribute1 = CustomMapAttribute()
        attribute1.custom = 1

        attribute2 = CustomMapAttribute()
        attribute2.custom = 2

        inp = [attribute1, attribute2]

        list_attribute = ListAttribute(default=[], of=CustomMapAttribute)
        serialized = list_attribute.serialize(inp)
        deserialized = list_attribute.deserialize(serialized)

        assert deserialized == inp
        assert serialize_mock.call_args_list == [call(1), call(2)]
        assert deserialize_mock.call_args_list == [call('1'), call('2')]
Beispiel #8
0
async def test_nack_calls_ack(
    subscriber: SinglePartitionSingleSubscriber,
    underlying,
    transformer,
    ack_set_tracker,
    nack_handler,
):
    ack_called_queue = asyncio.Queue()
    ack_result_queue = asyncio.Queue()
    ack_set_tracker.ack.side_effect = make_queue_waiter(
        ack_called_queue, ack_result_queue)
    async with subscriber:
        message = SequencedMessage(cursor=Cursor(offset=1), size_bytes=5)
        underlying.read.return_value = message
        read: Message = await subscriber.read()
        ack_set_tracker.track.assert_has_calls([call(1)])

        def on_nack(nacked: PubsubMessage, ack: Callable[[], None]):
            assert nacked.message_id == "1"
            ack()

        nack_handler.on_nack.side_effect = on_nack
        read.nack()
        await ack_called_queue.get()
        await ack_result_queue.put(None)
        ack_set_tracker.ack.assert_has_calls([call(1)])
 async def test_multiple(self):
     self.data.twitch_num_followers.return_value = 0
     message = Message('https://twitch.tv megotsthis.com')
     self.mock_response.url = yarl.URL('http://twitch.tv')
     await block_url.check_domain_redirect(self.channel, 'megotsthis',
                                           message, self.now)
     self.data.twitch_num_followers.assert_called_once_with('megotsthis')
     self.mock_log.assert_called_once_with(
         StrContains('botgotsthis', 'blockurl'),
         StrContains('megotsthis', str(message)), self.now)
     self.assertEqual(self.mock_clientsession.call_count, 1)
     self.assertEqual(self.mock_session.get.call_count, 2)
     self.mock_compare.assert_has_calls([
         call('https://twitch.tv',
              'http://twitch.tv',
              chat=self.channel,
              nick='megotsthis',
              timestamp=self.now),
         call('http://megotsthis.com',
              'http://twitch.tv',
              chat=self.channel,
              nick='megotsthis',
              timestamp=self.now),
     ])
     self.assertFalse(self.mock_handle.called)
     self.assertFalse(self.mock_except.called)
async def test_play_media(hass, remote):
    """Test for play_media."""
    asyncio_sleep = asyncio.sleep
    sleeps = []

    async def sleep(duration, loop):
        sleeps.append(duration)
        await asyncio_sleep(0, loop=loop)

    await setup_samsungtv(hass, MOCK_CONFIG)
    with patch("asyncio.sleep", new=sleep):
        assert await hass.services.async_call(
            DOMAIN,
            SERVICE_PLAY_MEDIA,
            {
                ATTR_ENTITY_ID: ENTITY_ID,
                ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_CHANNEL,
                ATTR_MEDIA_CONTENT_ID: "576",
            },
            True,
        )
        # keys and update called
        assert remote.control.call_count == 4
        assert remote.control.call_args_list == [
            call("KEY_5"),
            call("KEY_7"),
            call("KEY_6"),
            call("KEY_ENTER"),
        ]
        assert remote.close.call_count == 1
        assert remote.close.call_args_list == [call()]
        assert len(sleeps) == 3
 def test_topic_channel_found(self):
     channels = {
         "ok": True,
         "channels": [
             {
                 "name": "chan1",
                 "id": "C1",
             },
             {
                 "name": "chan2",
                 "id": "C2",
             },
             {
                 "name": "chan3",
                 "id": "C3",
             },
         ]
     }
     self.rd_lock.locked_by_user = "******"
     self.rd_lock.topic_channel = "chan2"
     self.mock_api_call.side_effect = [json.dumps(channels), None]
     yield from self.rd_lock.set_channel_topic(False)
     calls = [
         call("channels.list", exclude_archived=1),
         call("channels.setTopic",
              channel="C2",
              topic="")
     ]
     self.assertEqual(self.mock_api_call.mock_calls, calls)
Beispiel #12
0
 async def test_handle_command__start_has_invited_himself(self):
     from randtalkbot.stranger_handler import StrangerService
     message = Mock()
     message.command_args = 'foo_args'
     message.decode_command_args.return_value = {'i': 'foo_invitation'}
     self.stranger.wizard = 'none'
     self.stranger.invited_by = None
     self.stranger.invitation = 'foo_invitation'
     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.assertEqual(
         self.sender.send_notification.call_args_list,
         [
             call(
                 'Don\'t try to fool me. Forward message with the link to your friends and'
                 ' receive well-earned bonuses that will help you to find partner quickly.'
             ),
             call(
                 '*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_iterator(
    default_subscriber,
    subscriber_factory,
    multiplexed_client: AsyncSubscriberClientInterface,
):
    read_queues = wire_queues(default_subscriber.read)
    subscription = SubscriptionPath(1, CloudZone.parse("us-central1-a"), "abc")
    message = Message(PubsubMessage(message_id="1")._pb, "", 0, None)
    async with multiplexed_client:
        iterator = await multiplexed_client.subscribe(
            subscription, DISABLED_FLOW_CONTROL
        )
        subscriber_factory.assert_has_calls(
            [call(subscription, None, DISABLED_FLOW_CONTROL)]
        )
        read_fut_1 = asyncio.ensure_future(iterator.__anext__())
        assert not read_fut_1.done()
        await read_queues.called.get()
        default_subscriber.read.assert_has_calls([call()])
        await read_queues.results.put(message)
        assert await read_fut_1 is message
        read_fut_2 = asyncio.ensure_future(iterator.__anext__())
        assert not read_fut_2.done()
        await read_queues.called.get()
        default_subscriber.read.assert_has_calls([call(), call()])
        await read_queues.results.put(FailedPrecondition(""))
        with pytest.raises(FailedPrecondition):
            await read_fut_2
        default_subscriber.__aexit__.assert_called_once()
 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)
Beispiel #15
0
    async def test_negotiate_transport_non_default(self, create_transport):
        non_default_type = ConnectionType.WEBSOCKET
        self.client._connection_types = [non_default_type]
        response = {
            "supportedConnectionTypes":
            [DEFAULT_CONNECTION_TYPE.value, non_default_type.value],
            "successful":
            True
        }
        transport1 = mock.MagicMock()
        transport1.connection_type = DEFAULT_CONNECTION_TYPE
        transport1.client_id = "client_id"
        transport1.handshake = mock.CoroutineMock(return_value=response)
        transport1.reconnect_advice = object()
        transport1.close = mock.CoroutineMock()
        transport2 = mock.MagicMock()
        transport2.connection_type = non_default_type
        transport2.client_id = None
        create_transport.side_effect = [transport1, transport2]
        self.client._pick_connection_type = \
            mock.MagicMock(return_value=non_default_type)
        self.client._verify_response = mock.MagicMock()
        self.client.extensions = object()
        self.client.auth = object()

        with self.assertLogs("aiocometd.client", "DEBUG") as log:
            result = await self.client._negotiate_transport()

        self.assertEqual(result, transport2)
        create_transport.assert_has_calls([
            mock.call(DEFAULT_CONNECTION_TYPE,
                      url=self.client.url,
                      incoming_queue=self.client._incoming_queue,
                      ssl=self.client.ssl,
                      extensions=self.client.extensions,
                      auth=self.client.auth,
                      json_dumps=self.client._json_dumps,
                      json_loads=self.client._json_loads,
                      loop=self.client._loop),
            mock.call(non_default_type,
                      url=self.client.url,
                      incoming_queue=self.client._incoming_queue,
                      client_id=transport1.client_id,
                      ssl=self.client.ssl,
                      extensions=self.client.extensions,
                      auth=self.client.auth,
                      json_dumps=self.client._json_dumps,
                      json_loads=self.client._json_loads,
                      reconnect_advice=transport1.reconnect_advice,
                      loop=self.client._loop)
        ])
        transport1.handshake.assert_called_with(self.client._connection_types)
        self.client._verify_response.assert_called_with(response)
        self.client._pick_connection_type.assert_called_with(
            response["supportedConnectionTypes"])
        transport1.close.assert_called()
        log_message = ("INFO:aiocometd.client:"
                       "Connection types supported by the server: {!r}".format(
                           response["supportedConnectionTypes"]))
        self.assertEqual(log.output, [log_message])
Beispiel #16
0
async def test_assignment_change(subscriber, assigner, subscriber_factory):
    assign_queues = wire_queues(assigner.get_assignment)
    async with subscriber:
        await assign_queues.called.get()
        sub1 = mock_async_context_manager(
            MagicMock(spec=AsyncSingleSubscriber))
        sub2 = mock_async_context_manager(
            MagicMock(spec=AsyncSingleSubscriber))
        sub3 = mock_async_context_manager(
            MagicMock(spec=AsyncSingleSubscriber))
        subscriber_factory.side_effect = (
            lambda partition: sub1 if partition == Partition(1) else sub2
            if partition == Partition(2) else sub3)
        await assign_queues.results.put({Partition(1), Partition(2)})
        await assign_queues.called.get()
        subscriber_factory.assert_has_calls(
            [call(Partition(1)), call(Partition(2))], any_order=True)
        sub1.__aenter__.assert_called_once()
        sub2.__aenter__.assert_called_once()
        await assign_queues.results.put({Partition(1), Partition(3)})
        await assign_queues.called.get()
        subscriber_factory.assert_has_calls(
            [call(Partition(1)),
             call(Partition(2)),
             call(Partition(3))],
            any_order=True)
        sub3.__aenter__.assert_called_once()
        sub2.__aexit__.assert_called_once()
    sub1.__aexit__.assert_called_once()
    sub2.__aexit__.assert_called_once()
    sub3.__aexit__.assert_called_once()
Beispiel #17
0
 def test_multiple_msgs_one_plugin(self):
     self.mock_slack.get_stream_messages.return_value = ['msg1', 'msg2']
     self.robot.plugin_list = ['plug1']
     yield from self.robot.produce()
     expected_call_1 = call('msg1', 'plug1')
     expected_call_2 = call('msg2', 'plug1')
     self.assertTrue(len(self.mock_queue_message.mock_calls), 2)
     self.assertTrue(expected_call_1 in self.mock_queue_message.mock_calls)
     self.assertTrue(expected_call_2 in self.mock_queue_message.mock_calls)
Beispiel #18
0
 async def test_post_ratelimit__under_threshold__seconds_failure(
     self, mock_sleep, _
 ):
     with pytest.raises(RedditAPIException) as exception:
         await self.reddit.post("test")
     assert (
         exception.value.message
         == "You are doing that too much. Try again in 1 second."
     )
     mock_sleep.assert_has_calls([mock.call(6), mock.call(4), mock.call(2)])
async def test_media_previous_track(hass, remote):
    """Test for media_previous_track."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_CHDOWN")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #20
0
 async def test_dump_to_default_rcfile(self, mock_path_exists, mock_info,
                                       mock_get_tabs, mock_get_kbs,
                                       mock_get_sets):
     mock_path_exists.return_value = False
     process = await self.execute(DumpCmd)
     self.assertEqual(open.call_args_list, [call('/mock/path/to/rc', 'w')])
     self.assertEqual(mock_info.call_args_list,
                      [call('Wrote rc file: /mock/path/to/rc')])
     self.assert_stderr()
     self.assertEqual(process.success, True)
Beispiel #21
0
 async def test_comma_separated_arguments(self):
     self.localcfg['some.string'] = 'foo'
     self.localcfg['some.number'] = 12
     process = await self.execute(ResetCmd, 'some.string,some.number')
     self.assertEqual(process.success, True)
     self.assertEqual(
         self.localcfg.reset.mock_calls,
         [call('some.string'), call('some.number')])
     self.assert_stdout()
     self.assert_stderr()
async def test_volume_down(hass, remote):
    """Test for volume_down."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_DOWN,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_VOLDOWN")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
async def test_media_pause(hass, remote):
    """Test for media_pause."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PAUSE,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_PAUSE")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #24
0
 async def test_multiple(self):
     self.data.getAutoRepeatToSend.return_value = AsyncIterator([
         AutoRepeatMessage('botgotsthis', '', 'Kappa'),
         AutoRepeatMessage('botgotsthis', 'Kappa', 'Keepo'),
     ])
     await tasks.autoRepeatMessage(self.now)
     self.data.sentAutoRepeat.assert_has_calls(
         [call('botgotsthis', ''),
          call('botgotsthis', 'Kappa')])
     self.assertFalse(self.mock_timeout.called)
     self.channel.send.assert_has_calls([call('Kappa'), call('Keepo')])
Beispiel #25
0
 def test_multiple_tickets_sentence(self):
     self.sm.text = "Tickets ATL-1, ATL-2,,ATL-3\nOh, Also ATL-04 and ATL05"
     yield from self.jira.process_message(self.sm)
     expected_calls = [
         call("https://jira.atlassian.com", "ATL-1"),
         call("https://jira.atlassian.com", "ATL-2"),
         call("https://jira.atlassian.com", "ATL-3"),
         call("https://jira.atlassian.com", "ATL-04"),
     ]
     self.assertEqual(self.mock_get_jira_issue_info.mock_calls,
                      expected_calls)
async def test_send_key(hass, remote):
    """Test for send key."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_UP,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    state = hass.states.get(ENTITY_ID)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_VOLUP")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
    assert state.state == STATE_ON
Beispiel #27
0
 def test_multiple_tickets(self):
     self.sm.text = "JIRA-001,JIRA-002, JIRA-003.JIRA-04 JIRA-05"
     yield from self.jira.process_message(self.sm)
     expected_calls = [
         call("https://jira.atlassian.com", "JIRA-001"),
         call("https://jira.atlassian.com", "JIRA-002"),
         call("https://jira.atlassian.com", "JIRA-003"),
         call("https://jira.atlassian.com", "JIRA-04"),
         call("https://jira.atlassian.com", "JIRA-05"),
     ]
     self.assertEqual(self.mock_get_jira_issue_info.mock_calls,
                      expected_calls)
 def test_authorized_user_unlock(self):
     self.rd_lock.populate_slack_user_object.side_effect = [self.su]
     yield from self.rd_lock.toggle_rundeck_lock(self.sm, False)
     self.assertEqual(self.rd_lock.set_channel_topic.mock_calls,
                      [call(False)])
     send_channel_msg_calls = [
         call("C001", ":white_check_mark: Rundeck executions unlocked! :white_check_mark:")  # NOQA
     ]
     self.assertEqual(self.rd_lock.slack.send_channel_message.mock_calls,
                      send_channel_msg_calls)
     self.assertEqual(self.rd_lock.print_lock_status.mock_calls,
                      [call(self.sm)])
 def test_authorized_user_lock(self):
     self.rd_lock.populate_slack_user_object.side_effect = [self.su]
     yield from self.rd_lock.toggle_rundeck_lock(self.sm, True)
     self.assertEqual(self.rd_lock.set_channel_topic.mock_calls,
                      [call(True)])
     send_channel_msg_calls = [
         call("C001", ":lock: Rundeck executions locked by <@suser> :lock:")
     ]
     self.assertEqual(self.rd_lock.slack.send_channel_message.mock_calls,
                      send_channel_msg_calls)
     self.assertEqual(self.rd_lock.print_lock_status.mock_calls,
                      [call(self.sm)])
Beispiel #30
0
 async def test_offline_community_empty(self, mock_channel, mock_community):
     mock_community.return_value = []
     mock_channel.return_value = TwitchStatus(None, 'Keepo', 'Music', None)
     self.channel.isStreaming = False
     self.cache_property.return_value = self.now - timedelta(hours=1)
     await twitch.checkOfflineChannels(self.now)
     mock_channel.assert_called_once_with('botgotsthis')
     self.cache_property.assert_has_calls([call(), call(self.now)])
     self.streaming_property.assert_called_once_with(None)
     self.status_property.assert_called_once_with('Keepo')
     self.game_property.assert_called_once_with('Music')
     mock_community.assert_called_once_with('botgotsthis')
     self.assertFalse(self.data.twitch_save_community.called)
Beispiel #31
0
 async def test_dump_to_existing_rcfile_with_force(self, mock_path_exists,
                                                   mock_info, mock_get_tabs,
                                                   mock_get_kbs,
                                                   mock_get_sets):
     mock_path_exists.return_value = True
     process = await self.execute(DumpCmd, '/some/other/path/to/rc',
                                  '--force')
     self.assertEqual(open.call_args_list,
                      [call('/some/other/path/to/rc', 'w')])
     self.assertEqual(mock_info.call_args_list,
                      [call('Wrote rc file: /some/other/path/to/rc')])
     self.assert_stderr()
     self.assertEqual(process.success, True)
Beispiel #32
0
 async def check_existing_path(self, path, exp_path=None):
     if exp_path is None:
         exp_path = path
     self.mock_rcfile.read.return_value = ('mock command 1',
                                           'mock command 2')
     process = await self.execute(RcCmd, path)
     self.mock_rcfile.read.assert_called_with(exp_path)
     self.assertEqual(process.success, True)
     self.assert_stdout()
     self.assert_stderr()
     self.assertEqual(self.cmdmgr.run_async.mock_calls,
                      [call('mock command 1'),
                       call('mock command 2')])
 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_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, call())
     self.assertEqual(retval, "")
 def test_send_key_connection_closed_retry_succeed(self):
     """Test retry on connection closed."""
     _remote = mock.Mock()
     _remote.control = mock.Mock(side_effect=[
         self.device._exceptions_class.ConnectionClosed('Boom'),
         mock.DEFAULT])
     self.device.get_remote = mock.Mock(return_value=_remote)
     command = 'HELLO'
     self.device.send_key(command)
     self.assertEqual(STATE_ON, self.device._state)
     # verify that _remote.control() get called twice because of retry logic
     expected = [mock.call(command),
                 mock.call(command)]
     assert expected == _remote.control.call_args_list
 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`'),
             ],
         )
 def test_print_service_one_item(self):
     self.pd.pd_service_mappings = {
         "service1": "key1"
     }
     yield from self.pd.print_service_list(self.slack_message)
     expected_call = call("C2147483705", "```\nservice1\n```")
     self.pd.slack.send_channel_message.assert_has_calls([expected_call])
 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`'),
             ],
         )
 def test_lock_valid_response(self):
     self.mock_http_post_request.side_effect = ["200"]
     yield from self.rd_lock.lock_or_unlock_rundeck_job(self.rd_job, True)
     calls = [
         call("job.com/execution/disable", self.headers)
     ]
     self.assertTrue(self.rd_job.execution_enabled)
     self.assertEqual(self.mock_http_post_request.mock_calls, calls)
 def test_process_slack_message(self):
     msg = SlackMessage(type="message",
                        user="******",
                        channel="C2147483705",
                        text="!version")
     yield from self.ping.process_message(msg)
     expected = [call('C2147483705')]
     self.ping.send_version_message.assert_has_calls(expected)
 def test_unauthorized_user(self):
     self.su.is_admin = False
     self.rd_lock.populate_slack_user_object.side_effect = [self.su]
     yield from self.rd_lock.toggle_rundeck_lock(self.sm, True)
     calls = [
         call("C001", "Sorry <@suser>, you are not allowed to lock Rundeck executions.")  # NOQA
     ]
     self.assertEqual(self.rd_lock.slack.send_channel_message.mock_calls,
                      calls)
 def test_process_message_escalate_two(self):
     message = SlackMessage(type="message",
                            user="******",
                            channel="C2147483705",
                            text="!lassie website halp plz")
     yield from self.pd.process_message(message)
     expected_call = call("website halp plz", message)
     self.assertEqual(self.mock_print_service_list.mock_calls, [])
     self.assertEqual(self.mock_trigger_escalation_incident.mock_calls,
                      [expected_call])
 def test_service_key_not_found_with_message(self):
     yield from self.pd.trigger_escalation_incident("website halp plz",
                                                    self.slack_message)
     expected_call = call(
         "C2147483705",
         "Could not find key for service 'website', check that the service exists in the config file!"  # NOQA
     )
     self.pd.slack.send_channel_message.assert_has_calls([expected_call])
     self.assertEqual(len(self.mock_slack_user.mock_calls), 0)
     self.assertEqual(len(self.mock_http_post_request.mock_calls), 0)
 def test_empty_slack_response(self):
     self.su.name = "suser"
     self.mock_api_call.side_effect = ["{}"]
     yield from self.su.retrieve_slack_user_info(self.slack_connection,
                                                 "fake123")
     expected_call = call("users.info", user="******")
     self.assertEqual(self.mock_api_call.mock_calls,
                      [expected_call]),
     self.assertEqual(self.su.name, "suser")
     self.assertEqual(self.su.last_name, "")
     self.assertEqual(self.su.is_bot, "")
 def test_topic_channel_id_already_set(self):
     self.rd_lock.locked_by_user = "******"
     self.rd_lock.topic_channel = "chan1"
     self.rd_lock.topic_channel_id = "C1234"
     yield from self.rd_lock.set_channel_topic(True)
     calls = [
         call("channels.setTopic",
              channel="C1234",
              topic=":lock: Rundeck executions locked by @bob :lock:")
     ]
     self.assertEqual(self.mock_api_call.mock_calls, calls)
 def test_empty_job_list(self):
     self.rd_lock.rundeck_jobs = []
     expected_slack_msg_raw = []
     expected_slack_msg_raw.append("*Rundeck Job Lock Report*")
     expected_slack_msg_raw.append("```")
     expected_slack_msg_raw.append("```")
     expected_slack_msg = "\n".join(expected_slack_msg_raw)
     expected_call = call("sixchan", expected_slack_msg)
     yield from self.rd_lock.print_lock_status(self.sm)
     self.assertEqual(self.rd_lock.slack.send_channel_message.mock_calls,
                      [expected_call])
 def test_process_message_lock_release(self):
     message = SlackMessage(type="message",
                            user="******",
                            channel="C001",
                            text="!lock release")
     yield from self.rd.process_message(message)
     expected_calls = [
         call(message, lock_job=False)
     ]
     self.assertEqual(self.rd.rundeck_lock.toggle_rundeck_lock.mock_calls,
                      expected_calls)
     self.assertEqual(self.rd.rundeck_lock.print_lock_status.mock_calls, [])
 async def test_handle_command__start_has_invited_himself(self):
     from randtalkbot.stranger_handler import StrangerService
     message = Mock()
     message.command_args = 'foo_args'
     message.decode_command_args.return_value = {'i': 'foo_invitation'}
     self.stranger.wizard = 'none'
     self.stranger.invited_by = None
     self.stranger.invitation = 'foo_invitation'
     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.assertEqual(
         self.sender.send_notification.call_args_list,
         [
             call('Don\'t try to fool me. Forward message with the link to your friends and '
                 'receive well-earned bonuses that will help you to find partner quickly.'),
             call('*Manual*\n\nUse /begin to start looking for a conversational partner, once '
                 'you\'re matched you can use /end to end the conversation.'),
             ],
         )
Beispiel #48
0
async def test_get_random_actor_simple(client, token):
    with mock.patch.object(TMDbClient, 'get_data') as _get_data:
        _get_data.side_effect = [
            future_from({
                'page': 1,
                'results': [{'id': 1, 'name': 'Some Person'}],
                'total_results': 1,
                'total_pages': 1,
            }),
            future_from({'biography': 'extra stuff'}),
        ]

        result = await client.get_random_popular_person(1)

        assert result.name == 'Some Person'
        assert result.biography == 'extra stuff'
        _get_data.assert_has_calls([
            mock.call('https://api.themoviedb.org/3/person/popular'
                      '?page=1&api_key={}'.format(token)),
            mock.call('https://api.themoviedb.org/3/person/1'
                      '?api_key={}'.format(token)),
        ])
 def test_single_disabled_job(self):
     self.rd_lock.rundeck_jobs = [
         RundeckJob(friendly_name="job1", execution_enabled=False)
     ]
     expected_slack_msg_raw = []
     expected_slack_msg_raw.append("*Rundeck Job Lock Report*")
     expected_slack_msg_raw.append("```")
     expected_slack_msg_raw.append("job1: locked")
     expected_slack_msg_raw.append("```")
     expected_slack_msg = "\n".join(expected_slack_msg_raw)
     expected_call = call("sixchan", expected_slack_msg)
     yield from self.rd_lock.print_lock_status(self.sm)
     self.assertEqual(self.rd_lock.slack.send_channel_message.mock_calls,
                      [expected_call])
 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)
 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_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, [])
     self.assertEqual(retval, "this is my return value")
Beispiel #52
0
async def test_config(xiaomi_mock, hass):
    """Testing minimal configuration."""
    config = {
        DOMAIN: xiaomi.PLATFORM_SCHEMA({
            CONF_PLATFORM: xiaomi.DOMAIN,
            CONF_HOST: '192.168.0.1',
            CONF_PASSWORD: '******'
        })
    }
    xiaomi.get_scanner(hass, config)
    assert xiaomi_mock.call_count == 1
    assert xiaomi_mock.call_args == mock.call(config[DOMAIN])
    call_arg = xiaomi_mock.call_args[0][0]
    assert call_arg['username'] == 'admin'
    assert call_arg['password'] == 'passwordTest'
    assert call_arg['host'] == '192.168.0.1'
    assert call_arg['platform'] == 'device_tracker'
 def test_no_profile_key(self):
     self.su.name = "suser"
     user_info = {
         "ok": True,
         "user": {
             "id": "U023BECGF",
             "name": "bobby"
         }
     }
     self.mock_api_call.side_effect = [json.dumps(user_info)]
     yield from self.su.retrieve_slack_user_info(self.slack_connection,
                                                 "fake123")
     expected_call = call("users.info", user="******")
     self.assertEqual(self.mock_api_call.mock_calls,
                      [expected_call]),
     self.assertEqual(self.su.name, "bobby")
     self.assertEqual(self.su.id, "U023BECGF")
     self.assertEqual(self.su.last_name, "")
     self.assertEqual(self.su.is_bot, "")
async def test_get_scanner(unifi_mock, hass):
    """Test creating an Unifi direct scanner with a password."""
    conf_dict = {
        DOMAIN: {
            CONF_PLATFORM: 'unifi_direct',
            CONF_HOST: 'fake_host',
            CONF_USERNAME: '******',
            CONF_PASSWORD: '******',
            CONF_TRACK_NEW: True,
            CONF_CONSIDER_HOME: timedelta(seconds=180),
            CONF_NEW_DEVICE_DEFAULTS: {
                CONF_TRACK_NEW: True,
                CONF_AWAY_HIDE: False
            }
        }
    }

    with assert_setup_component(1, DOMAIN):
        assert await async_setup_component(hass, DOMAIN, conf_dict)

    conf_dict[DOMAIN][CONF_PORT] = 22
    assert unifi_mock.call_args == mock.call(conf_dict[DOMAIN])
async def test_setup_with_custom_location(hass):
    """Test the setup with a custom location."""
    # Set up some mock feed entries for this test.
    mock_entry_1 = _generate_mock_feed_entry(
        '1234', 'Title 1', 2000.5, (-31.1, 150.1))

    with patch('geojson_client.generic_feed.GenericFeed') as mock_feed:
        mock_feed.return_value.update.return_value = 'OK', [mock_entry_1]

        with assert_setup_component(1, geo_location.DOMAIN):
            assert await async_setup_component(
                hass, geo_location.DOMAIN, CONFIG_WITH_CUSTOM_LOCATION)

            # Artificially trigger update.
            hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
            # Collect events.
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 1

            assert mock_feed.call_args == call(
                (15.1, 25.2), URL, filter_radius=200.0)