Beispiel #1
0
async def test_deliver_with_message_translator(dummy_provider):
    mock_handler = CoroutineMock(return_value=True)
    route = Route(dummy_provider, mock_handler)
    route.apply_message_translator = mock.Mock(return_value={'content': 'whatever', 'metadata': {}})
    result = await route.deliver('test')
    assert result is True
    assert route.apply_message_translator.called
    assert mock_handler.called
    mock_handler.assert_called_once_with('whatever', {})
Beispiel #2
0
async def test_error_handler_coroutine(dummy_provider):
    error_handler = CoroutineMock(return_value=True)
    route = Route(dummy_provider, mock.Mock(), error_handler=error_handler)
    exc = TypeError()
    exc_info = (type(exc), exc, 'traceback')
    result = await route.error_handler(exc_info, 'whatever')
    assert result is True
    assert error_handler.called
    error_handler.assert_called_once_with(exc_info, 'whatever')
Beispiel #3
0
 async def test_007_on_direct_message(self):
     cb = CoroutineMock()
     self.bus.direct_subscribe(cb)
     msg = self.bus.client.Message()
     msg['type'] = 'message'
     msg['from'] = JID('other@localhost')
     msg['body'] = '{"key": "value"}'
     await self.bus._on_direct_message(msg)
     cb.assert_called_once_with('other', {'key': 'value'})
def test_main_async(mocker, event_loop):
    COMMANDS = []
    mocker.patch('jenkins_epo.main.COMMANDS', COMMANDS)
    command = CoroutineMock()
    command.__name__ = 'bot'
    command.__code__ = Mock(co_varnames=(), co_argcount=0)
    COMMANDS.append(command)
    from jenkins_epo.main import main

    main(argv=['bot'], loop=event_loop)

    assert command.mock_calls
Beispiel #5
0
 async def test_002_on_event(self):
     cb = CoroutineMock()
     with patch.object(self.bus._mucs, 'joinMUC') as join_mock:
         self.bus._connected.set()
         await self.bus.subscribe('other', cb)
         join_mock.assert_called_once_with('*****@*****.**', 'login')
     msg = self.bus.client.Message()
     msg['type'] = 'groupchat'
     msg['from'] = JID('other@localhost')
     msg['body'] = '{"key": "value"}'
     await self.bus._on_event(msg)
     cb.assert_called_once_with({'key': 'value'})
def test_main_async_exception(mocker, event_loop):
    COMMANDS = []
    mocker.patch('jenkins_epo.main.COMMANDS', COMMANDS)
    command = CoroutineMock()
    command.__name__ = 'bot'
    command.__code__ = Mock(co_varnames=(), co_argcount=0)
    command.side_effect = ValueError()
    COMMANDS.append(command)

    from jenkins_epo.main import main

    with pytest.raises(ValueError):
        main(argv=['bot'], loop=event_loop)

    assert command.mock_calls
    assert event_loop.is_closed()
Beispiel #7
0
    async def test_resolve_request_with_last_falsy_matcher(self):
        handler = CoroutineMock(return_value=sentinel.response)
        matcher1 = CoroutineMock(return_value=True)
        matcher2 = CoroutineMock(return_value=False)
        self.resolver.register_matcher(matcher1, handler)
        self.resolver.register_matcher(matcher2, handler)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, self.default_handler)

        matcher1.assert_called_once_with(request)
        matcher2.assert_called_once_with(request)
        handler.assert_not_called()
    async def test_resolve_request_priority(self):
        matcher = CoroutineMock(side_effect=(True, True))
        handler1 = CoroutineMock(return_value=sentinel.response1)
        handler2 = CoroutineMock(return_value=sentinel.response2)
        self.resolver.register_matcher(matcher, handler1)
        self.resolver.register_matcher(matcher, handler2)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, handler1)

        handler1.assert_not_called()
        handler2.assert_not_called()
        matcher.assert_called_once_with(request)
    async def test_resolve_request_with_multiple_handlers(self):
        matcher = CoroutineMock(side_effect=(False, True))
        handler1 = CoroutineMock(return_value=sentinel.response1)
        handler2 = CoroutineMock(return_value=sentinel.response2)
        self.resolver.register_matcher(matcher, handler1)
        self.resolver.register_matcher(matcher, handler2)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, handler2)

        handler1.assert_not_called()
        handler2.assert_not_called()
        matcher.assert_has_calls([call(request)] * 2)
        self.assertEqual(matcher.call_count, 2)
Beispiel #10
0
async def test_get_image_new(ota, image, key, image_with_version, monkeypatch):
    newer = image_with_version(image.version + 1)

    ota.async_event = CoroutineMock(return_value=[None, image, newer])

    assert len(ota._image_cache) == 0
    res = await ota.get_ota_image(MANUFACTURER_ID, IMAGE_TYPE)

    # got new image in the cache
    assert len(ota._image_cache) == 1
    assert res.header == newer.header
    assert res.subelements == newer.subelements
    assert ota.async_event.call_count == 1
    assert ota.async_event.call_args[0][0] == "get_image"
    assert ota.async_event.call_args[0][1] == key

    ota.async_event.reset_mock()
    assert len(ota._image_cache) == 1
    res = await ota.get_ota_image(MANUFACTURER_ID, IMAGE_TYPE)

    # should get just the cached image
    assert len(ota._image_cache) == 1
    assert res.header == newer.header
    assert res.subelements == newer.subelements
    assert ota.async_event.call_count == 0

    # on cache expiration, ping listeners
    ota.async_event.reset_mock()
    assert len(ota._image_cache) == 1

    monkeypatch.setattr(
        zigpy.ota,
        "TIMEDELTA_0",
        zigpy.ota.CachedImage.DEFAULT_EXPIRATION +
        datetime.timedelta(seconds=1),
    )
    res = await ota.get_ota_image(MANUFACTURER_ID, IMAGE_TYPE)

    assert len(ota._image_cache) == 1
    assert res.header == newer.header
    assert res.subelements == newer.subelements
    assert ota.async_event.call_count == 1
Beispiel #11
0
async def test_single_wrong_report_still_rated_correctly(
        game: Game, player_factory):
    # based on replay with UID 11255492

    # Mocking out database calls, since not all player IDs exist.
    game.update_game_player_stats = CoroutineMock()

    game.state = GameState.LOBBY

    # Loading log data
    with open("tests/data/uid11255492.log.json", "r") as f:
        log_dict = json.load(f)

    old_rating = 1500
    players = {
        player_id: player_factory(
            login=f"{player_id}",
            player_id=player_id,
            global_rating=Rating(old_rating, 250),
            with_lobby_connection=False,
        )
        for team in log_dict["teams"].values() for player_id in team
    }

    add_connected_players(game, list(players.values()))
    for team_id, team_list in log_dict["teams"].items():
        for player_id in team_list:
            game.set_player_option(player_id, "Team", team_id)
            game.set_player_option(player_id, "Army", player_id - 1)
    await game.launch()

    for reporter, reportee, outcome, score in log_dict["results"]:
        await game.add_result(players[reporter], reportee, outcome, score)

    result = game.compute_rating()
    winning_ids = log_dict["teams"][str(log_dict["winning_team"])]
    for team in result:
        for player, new_rating in team.items():
            assert player in game.players
            player_is_on_winning_team = player.id in winning_ids
            rating_improved = new_rating.mu > old_rating
            assert rating_improved is player_is_on_winning_team
Beispiel #12
0
 async def test_play_track_list_loops(self, example_music_manager,
                                      monkeypatch):
     """
     The _play_track_list() method should call _play_track() for every track in it. If all tracks have been played
     and the `loop` attribute is set on the track_list, repeat.
     """
     play_track_mock = CoroutineMock()
     monkeypatch.setattr("src.music.music_manager.MusicManager._play_track",
                         play_track_mock)
     group = example_music_manager.groups[0]
     track_list = MagicMock()
     track_list.tracks = [Track("track-1.mp3"), Track("track-2.mp3")]
     loop_property = PropertyMock(side_effect=[True, False])
     type(track_list).loop = loop_property
     group.track_lists = [track_list]
     await example_music_manager._play_track_list(request=None,
                                                  group_index=0,
                                                  track_list_index=0)
     assert play_track_mock.await_count == 4  # loops once again over two tracks
     assert loop_property.call_count == 2
Beispiel #13
0
async def test_subscription_keepalive_count(mocker):
    """
    Check the subscription parameter MaxKeepAliveCount value
    with various publishInterval and session_timeout values.
    """

    mock_subscription = mocker.patch(
        "asyncua.common.subscription.Subscription.init", new=CoroutineMock())
    c = Client("opc.tcp://fake")
    # session timeout < publish_interval
    c.session_timeout = 30000  # ms
    publish_interval = 1000  # ms
    handler = 123
    sub = await c.create_subscription(publish_interval, handler)
    assert sub.parameters.RequestedMaxKeepAliveCount == 22
    # session_timeout > publish_interval
    c.session_timeout = 30000
    publish_interval = 75000
    sub = await c.create_subscription(publish_interval, handler)
    assert sub.parameters.RequestedMaxKeepAliveCount == 0
Beispiel #14
0
 async def test_it_calls_handler_error_if_emit_fails(self):
     temp_file = NamedTemporaryFile(delete=False)
     handler = AsyncFileHandler(temp_file.name)
     log_record = LogRecord(
         name="Xablau",
         level=20,
         pathname="/aiologger/tests/test_logger.py",
         lineno=17,
         msg="Xablau!",
         exc_info=None,
         args=None,
     )
     await handler._init_writer()
     exc = Exception("Xablau")
     with patch.object(handler.stream, "write",
                       side_effect=exc), patch.object(
                           handler, "handle_error",
                           CoroutineMock()) as handle_error:
         await handler.emit(log_record)
         handle_error.assert_awaited_once_with(log_record, exc)
Beispiel #15
0
 async def test_emit_awaits_for_handle_error_is_an_exceptions_is_raised(
         self):
     handler = BaseAsyncRotatingFileHandler(filename=self.temp_file.name)
     handler.should_rollover = Mock(return_value=False)
     exc = OSError()
     with patch("aiologger.handlers.files.AsyncFileHandler.emit",
                side_effect=exc), patch.object(
                    handler, "handle_error",
                    CoroutineMock()) as handleError:
         log_record = LogRecord(
             name="Xablau",
             level=20,
             pathname="/aiologger/tests/test_logger.py",
             lineno=17,
             msg="Xablau!",
             exc_info=None,
             args=None,
         )
         await handler.emit(log_record)
         handleError.assert_awaited_once_with(log_record, exc)
Beispiel #16
0
    async def test_getby_url(self):
        summarized_at = datetime.now()
        self.mock_cursor.fetchone = CoroutineMock(
            return_value=("document_id", "user_id", "www.test.com", "contents",
                          summarized_at))

        doc = DocumentRepository(self.postgres_pool_mock)
        obtained_doc = await doc.getby_url("www.test.com")

        self.postgres_pool_mock.acquire.assert_called_once()
        self.postgres_pool_mock.release.assert_called_once()
        self.mock_cursor.execute.assert_called_once()
        self.mock_cursor.fetchone.assert_called_once()

        self.assertIsInstance(obtained_doc, DocumentRepository.DocumentView)
        self.assertEqual(obtained_doc.document_id, "document_id")
        self.assertEqual(obtained_doc.user_id, "user_id")
        self.assertEqual(obtained_doc.url, "www.test.com")
        self.assertEqual(obtained_doc.contents, "contents")
        self.assertIs(obtained_doc.summarized_at, summarized_at)
Beispiel #17
0
async def test_command_game_join_game_not_found(
    lobbyconnection,
    game_service,
    test_game_info,
    players
):
    lobbyconnection.send = CoroutineMock()
    lobbyconnection.game_service = game_service
    lobbyconnection.player = players.hosting
    test_game_info["uid"] = 42

    await lobbyconnection.on_message_received({
        "command": "game_join",
        **test_game_info
    })
    lobbyconnection.send.assert_called_once_with({
        "command": "notice",
        "style": "info",
        "text": "The host has left the game."
    })
Beispiel #18
0
def test_request(mock_post):
    mock_post.return_value.__aenter__.return_value.json = CoroutineMock(
        side_effect=[{
            "ok": True,
            "result": 1
        }, {
            "ok": False
        }])

    async def test():
        telegram = Telegram(token="token")

        assert await telegram._request("method1", {"arg": "val1"}) == 1

        with pytest.raises(RequestException):
            await telegram._request("method2", {"arg": "val2"})

        await telegram.session.close()

    asyncio.get_event_loop().run_until_complete(test())
Beispiel #19
0
    async def test_send_code_changed_flag(self, mocked_socketio, app):
        self.mocked_mappings[self.sid] = 1
        self.game_api.worker_manager.add_new_worker(
            self.mocked_mappings[self.sid])
        worker = self.game_api.worker_manager.player_id_to_worker[
            self.mocked_mappings[self.sid]]
        worker.has_code_updated = True

        with mock.patch('service.socketio_server.emit',
                        new=CoroutineMock()) as mocked_emit:
            await self.game_api.send_updates()

            user_game_state_call = mock.call('game-state', {'foo': 'bar'},
                                             room=self.sid)
            user_game_code_changed_call = mock.call('feedback-avatar-updated',
                                                    room=self.sid)

            mocked_emit.assert_has_calls(
                [user_game_state_call, user_game_code_changed_call],
                any_order=True)
Beispiel #20
0
    async def test_can_handle_connected_frame_with_heartbeat_disabled(
            self, heartbeater_klass_mock):
        frame = Frame('CONNECTED', {
            'heart-beat': '1000,1000',
        }, '{}')

        heartbeater_mock = heartbeater_klass_mock.return_value
        heartbeater_mock.start = CoroutineMock()

        stomp = StompReader(None,
                            self.loop,
                            heartbeat={
                                'enabled': False,
                                'cx': 0,
                                'cy': 0
                            })
        stomp._transport = Mock()
        await stomp._handle_connect(frame)

        heartbeater_klass_mock.assert_not_called
    async def test_ok(self, mocker: MockFixture,
                      fake_data_provider: BaseDataProvider):
        fake_data = mocker.Mock()
        fake_include_name = 'foo'
        fake_include_params = mocker.Mock()
        mocker.patch.object(fake_data_provider, '_available_includes',
                            {fake_include_name: 'bar'})
        mocked_update_with_include_data = mocker.patch.object(
            fake_data_provider, 'update_with_include_data')
        mocked_get_list_include_data = mocker.patch.object(
            fake_data_provider, 'get_list_include_data', CoroutineMock())

        await fake_data_provider.extend_data_with_includes(
            fake_data, fake_include_name, fake_include_params)

        mocked_get_list_include_data.assert_called_once_with(
            fake_data, 'bar', fake_include_params)
        mocked_update_with_include_data.assert_called_once_with(
            fake_data, fake_include_name,
            mocked_get_list_include_data.return_value)
Beispiel #22
0
async def test_interval_functions(http_redirect, ssl_certificate):
    with patch("asyncio.sleep", new=CoroutineMock()):
        async with CaseControlledTestServer(
                ssl=ssl_certificate.server_context()) as server:
            controller = await setup_multi_session(server, http_redirect)

        INVALID_NEW_INTERVAL = 25
        VALID_NEW_INTERVAL = 500

        assert controller.get_update_interval() == sc.DEFAULT_UPDATE_INTERVAL
        controller.set_update_interval(INVALID_NEW_INTERVAL)
        assert controller.get_update_interval() == sc.DEFAULT_UPDATE_INTERVAL
        controller.set_update_interval(VALID_NEW_INTERVAL)
        assert controller.get_update_interval() == VALID_NEW_INTERVAL

        assert controller.get_fetch_interval() == sc.DEFAULT_FETCH_INTERVAL
        controller.set_fetch_interval(INVALID_NEW_INTERVAL)
        assert controller.get_fetch_interval() == sc.DEFAULT_FETCH_INTERVAL
        controller.set_fetch_interval(VALID_NEW_INTERVAL)
        assert controller.get_fetch_interval() == VALID_NEW_INTERVAL
Beispiel #23
0
def test_register_failure(mocker, SETTINGS, WORKERS):
    SETTINGS.GITHUB_SECRET = 'notasecret'

    from concurrent.futures import Future
    future = Future()
    future.set_exception(Exception())
    register_webhook = mocker.patch(
        'jenkins_epo.main.register_webhook',
        CoroutineMock(return_value=[future]),
    )
    mocker.patch('jenkins_epo.main.WORKERS', WORKERS)

    from jenkins_epo.main import register

    with pytest.raises(SystemExit):
        yield from register()

    assert WORKERS.start.mock_calls
    assert register_webhook.mock_calls
    assert WORKERS.terminate.mock_calls
    async def test_execute_query_with_headers(self, mock_post):
        """Sends a graphql POST request with headers."""
        mock_post.return_value.__aenter__.return_value.json = CoroutineMock()
        client = GraphqlClient(
            endpoint="http://www.test-api.com/",
            headers={"Content-Type": "application/json", "Existing": "123",},
        )
        query = ""

        await client.execute_async("", headers={"Existing": "456", "New": "foo"})

        mock_post.assert_called_once_with(
            "http://www.test-api.com/",
            json={"query": query},
            headers={
                "Content-Type": "application/json",
                "Existing": "456",
                "New": "foo",
            },
        )
 async def test_set_indexes(self, *args):
     mock_ctx = {
         '_id': 'some-value',
         'path': 'some-path',
         'host': 'some-host',
         'status_code': 'some-value',
         'rule_id': 'some-value',
     }
     mock_db = MagicMock()
     mock_hset = CoroutineMock()
     mock_db.hset = mock_hset
     await RateLimiter._set_indexes(mock_ctx, mock_db)
     args[0].assert_awaited()
     for call in mock_hset.await_args_list:
         expect([
             rule_status_code_index, entry_rule_id_index, entry_host_index
         ]).to(contain(call[0][0]))
         expect(call[0][1]).to(equal(mock_ctx['_id']))
         expect([mock_ctx[key]
                 for key in mock_ctx.keys()]).to(contain(call[0][2]))
Beispiel #26
0
async def nbu_converter() -> NBUConverter:
    crawler = Crawler()
    await crawler.prepare()
    crawler.get_json = CoroutineMock(return_value=[{
        "r030": 840,
        "txt": "Долар США",
        "rate": 26.619328,
        "cc": "USD",
        "exchangedate": "13.05.2019"
    }, {
        "r030": 978,
        "txt": "Євро",
        "rate": 29.608679,
        "cc": "EUR",
        "exchangedate": "13.05.2019"
    }])
    converter = NBUConverter(crawler)
    await converter.prepare()
    yield converter
    await crawler.spare()
Beispiel #27
0
async def test_on_gmail():
    handler = CallbackHandler(MagicMock(), MagicMock())
    with mock.patch(SEND_TO_TELEGRAM, new=CoroutineMock()) as send:
        await handler.on_mail_choice({
            'callback_query': {
                'message': {
                    'chat': {
                        'id': 12
                    }
                },
                'data': '/gmail',
            }
        })
        args, _ = send.call_args
        send.assert_called_once()
        assert args[0] == 'sendMessage'
        assert args[1]['chat_id'] == 12
        assert args[1]['text'][57:62] == 'Gmail'
        assert args[1]['parse_mode'] == 'Markdown'
        assert args[1]['disable_web_page_preview'] is True
Beispiel #28
0
    def test_from_address(self, peering):
        peering.return_value.get = CoroutineMock(return_value={
            "version": 2,
            "currency": "meta_brouzouf",
            "endpoints": [
                "BASIC_MERKLED_API duniter.inso.ovh 80"
            ],
            "block": "48698-000005E0F228038E4DDD4F6CA4ACB01EC88FBAF8",
            "signature": "82o1sNCh1bLpUXU6nacbK48HBcA9Eu2sPkL1/3c2GtDPxBUZd2U2sb7DxwJ54n6ce9G0Oy7nd1hCxN3fS0oADw==",
            "raw": "Version: 2\nType: Peer\nCurrency: meta_brouzouf\nPublicKey: 8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU\nBlock: 48698-000005E0F228038E4DDD4F6CA4ACB01EC88FBAF8\nEndpoints:\nBASIC_MERKLED_API duniter.inso.ovh 80\n",
            "pubkey": "8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU"
        })

        async def exec_test():
            node = await Node.from_address("meta_brouzouf", "127.0.0.1", 9000, Mock("aiohttp.ClientSession"))
            self.assertEqual(node.pubkey, "8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU")
            self.assertEqual(node.endpoint.inline(), "BASIC_MERKLED_API duniter.inso.ovh 80")
            self.assertEqual(node.currency, "meta_brouzouf")

        self.lp.run_until_complete(exec_test())
Beispiel #29
0
    async def test_bulk_flushes_on_timeout_even_with_bucket_not_full(self):
        class MyBucket(Bucket):
            def pop_all(self):
                global items
                items = self._items
                self._items = []
                return items

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

        consumer = Consumer(
            self.one_route_fixture,
            *self.connection_parameters,
            bucket_class=MyBucket,
        )

        msgs = [
            self._make_msg(delivery_tag=10),
            self._make_msg(delivery_tag=11),
        ]
        await consumer.on_queue_message(msgs[0])
        handler_mock.assert_not_awaited()

        await consumer.on_queue_message(msgs[1])
        handler_mock.assert_not_awaited()

        self.loop.create_task(consumer._flush_clocked())
        # Realizando sleep para devolver o loop para o clock
        await asyncio.sleep(0.1)

        handler_mock.assert_awaited_once_with(items)

        msgs[0].ack.assert_awaited_once()
        msgs[1].ack.assert_awaited_once()

        msgs[0].reject.assert_not_awaited()
        msgs[1].reject.assert_not_awaited()
Beispiel #30
0
    async def test_lock_expire_retries_for_timeouts(self,
                                                    lock_manager_redis_patched,
                                                    locked_lock):
        lock_manager, redis = lock_manager_redis_patched
        redis.set_lock = CoroutineMock(side_effect=[(True,
                                                     1100), (True,
                                                             1001), (True,
                                                                     2000)])

        lock = await lock_manager.lock('resource')

        calls = [
            call('resource', ANY),
            call('resource', ANY),
            call('resource', ANY)
        ]
        redis.set_lock.assert_has_calls(calls)
        assert lock.resource == 'resource'
        assert lock.id == ANY
        assert lock.valid is False
Beispiel #31
0
async def test_get_is_bad_url_true():
    url = str(HOSTNAME + "/" + PATH)
    #TODO: This line is ridiculously long, shorten it
    expected_response_body = str({
        url: {
            url: True
        }
    }).lower().replace("\'", "\"").replace(" ", "").encode('ascii')
    expected_response_code = 200
    request_data = {"hostname_port": HOSTNAME, "path_query": PATH}

    main.datastore = CoroutineMock(Datastore)
    main.datastore.get_is_url_bad.return_value = {url: True}

    request = Mock(path_params=request_data)

    response = await main.get_is_url_bad(request)

    assert response.body == expected_response_body
    assert response.status_code == expected_response_code
Beispiel #32
0
 async def test_run_dispatches_a_new_task_for_each_valid_clock_tick(self):
     clock = asynctest.MagicMock()
     clock.__aiter__.return_value = range(3)
     wrapped_task = Mock()
     with patch.multiple(
         self.task_runner,
         clock=clock,
         _wrapped_task=wrapped_task,
         can_dispatch_task=CoroutineMock(side_effect=[True, False, True]),
     ), patch(
         "asyncworker.task_runners.asyncio.ensure_future"
     ) as ensure_future:
         await self.task_runner._run()
         self.assertEqual(
             ensure_future.call_args_list,
             [
                 call(wrapped_task.return_value),
                 call(wrapped_task.return_value),
             ],
         )
Beispiel #33
0
    async def test_can_open_browser(self, browser_open_mock):
        storage = Mock()
        storage.load.return_value = None

        site = Mock()
        site.stop = CoroutineMock()
        token_waiter = Future()
        token_waiter.set_result({'access_token': '1234'})
        app = {'port': 30000, 'token_waiter': token_waiter}

        self.manager.storage = storage
        self.manager.app = app
        self.manager.site = site

        token = await self.manager.get_token()

        self.assertEqual(token, '1234')
        browser_open_mock.assert_called_with(
            'http://endpoint/authorize?response_type=token&client_id=client_id&redirect_uri=http%3A//localhost%3A30000'
        )  # noqa
Beispiel #34
0
async def test_cache(config, http, cache):
    """
    Make sure an API method, when called more than once with the same
    parameters, only results in one HTTP call, since the second time it
    gets the data from the cache.
    """
    http.get = CoroutineMock()
    text = '{}'
    http.get.return_value = {'status': 200, 'text': text}
    api = Api(config, http, cache)

    user = '******'
    params = {'limit': 10}

    await api.purchases_by_user(params, username=user)
    await api.purchases_by_user(params, username=user)

    path = api._paths['purchases_by_user'].format(username=user)
    url = config['API_BASE_URL'] + path + '?limit=10'
    api.http.get.assert_called_once_with(url)
Beispiel #35
0
async def test_request(nw: Network):
    class MagicMockContext(MagicMock):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            type(self).__aenter__ = CoroutineMock(return_value='response data')
            type(self).__aexit__ = CoroutineMock(return_value=MagicMock())

    method = HttpMethod.POST
    url = 'someurl'
    data = {'some': 'data'}

    nw._handle_response = CoroutineMock()
    nw._handle_response.return_value = 'some value'

    with patch('aiohttp.ClientSession.post',
               new_callable=MagicMockContext) as m:
        result = await nw._request(method, url, data)
        m.assert_called_once_with(url, data=data)
        nw._handle_response.assert_awaited_once_with('response data')
        assert result == 'some value'
Beispiel #36
0
async def test_async_error_wrapper():
    async def tmp():
        1 / 0

    f = WrappedFunction(tmp)
    WrappedFunction._EVENT_LOOP = asyncio.get_event_loop()
    err_func = CoroutineMock()
    err_listener = HABApp.core.EventBusListener(
        'HABApp.Errors', WrappedFunction(err_func, name='ErrMock'))
    HABApp.core.EventBus.add_listener(err_listener)

    f.run()
    await asyncio.sleep(0.05)

    assert err_func.called
    err = err_func.call_args[0][0]
    assert isinstance(err, HABApp.core.events.habapp_events.HABAppError)
    assert err.func_name == 'tmp'
    assert isinstance(err.exception, ZeroDivisionError)
    assert err.traceback.startswith('Traceback (most recent call last):')
Beispiel #37
0
    async def test_lock_expire_retries_for_timeouts(self, lock_manager_redis_patched, locked_lock):
        lock_manager, redis = lock_manager_redis_patched
        redis.set_lock = CoroutineMock(side_effect=[
            1.100,
            1.001,
            2.000
        ])

        with pytest.raises(LockError):
            await lock_manager.lock('resource', 1.0)

        await real_sleep(0.1)  # wait until cleaning is completed

        calls = [
            call('resource', ANY, 1.0),
            call('resource', ANY, 1.0),
            call('resource', ANY, 1.0)
        ]
        redis.set_lock.assert_has_calls(calls)
        redis.unset_lock.assert_called_once_with('resource', ANY)
async def test_auth_exception_no_handler(mock_httpclient, caplog):
    async_client = mock_httpclient.AsyncHTTPClient.return_value
    # No body, so _write_key will raise exception
    async_client.fetch = CoroutineMock(return_value=Mock(
        spec=['code'],
        **{'code': 200},
    ))
    authenticator = SSHAPIAuthenticator()
    authenticator.server = 'http://localhost:9999'
    authenticator.skey = ''
    data = {'username': '******', 'password': '******'}
    assert_keys_do_not_exist()
    resp = await authenticator.authenticate(None, data)
    assert_keys_do_not_exist()
    assert resp is None
    logs = caplog.record_tuples
    assert len(logs) == 1
    _, _, message = logs[0]
    expected_message = 'SSH Auth API Authentication failed for user "tester"'
    assert message == expected_message
Beispiel #39
0
async def test_write_rating_progress_message(ladder_service: LadderService,
                                             player_factory):
    player = player_factory(ladder_rating=(1500, 500))
    player.write_message = CoroutineMock()

    ladder_service.write_rating_progress(player, RatingType.LADDER_1V1)

    player.write_message.assert_called_once_with({
        "command":
        "notice",
        "style":
        "info",
        "text": ("<i>Welcome to the matchmaker</i><br><br><b>Until "
                 "you've played enough games for the system to learn "
                 "your skill level, you'll be matched randomly.</b><br>"
                 "Afterwards, you'll be more reliably matched up with "
                 "people of your skill level: so don't worry if your "
                 "first few games are uneven. This will improve as you "
                 "play!</b>")
    })