示例#1
0
async def test_request_many(api: API):
    i = 0
    async for response in api.request_many(
        [api.APIRequest("some.method", {}),
         api.APIRequest("some.method", {})]):
        assert response == {"response": 1}
        i += 1
    assert i == 2
示例#2
0
def test_run_multibot(mocker: MockerFixture):
    bot_apis = []

    mocker.patch("vkbottle.bot.Bot.run_polling", lambda s, custom_polling: s.api)
    mocker.patch("asyncio.iscoroutine", lambda _: True)
    mocker.patch(
        "vkbottle.tools.dev.loop_wrapper.LoopWrapper.run_forever",
        lambda s: bot_apis.extend(s.tasks),
    )

    run_multibot(Bot(), (API("1"), API("2"), API("3")))
    assert len(bot_apis) == 3  # type: ignore
示例#3
0
    def api_builder(
            text: str,
            from_id: int = 92540660,
            on_datetime: datetime.datetime = datetime.datetime.fromtimestamp(
                1620678005),
            n_messages: int = 1):
        # Все подобрано как отвечает реальный ВК, поэтому дважды подумайте, прежде чем менять
        # Забрал с https://github.com/timoniq/vkbottle/blob/c6ebefb/tests/bot_test.py
        def callback(data: dict):
            # Этот парень нужен
            if "groups.getById" in data["url"]:
                return {"response": [{"id": 1}]}
            # И этот тоже
            elif "groups.getLongPollServer" in data["url"]:
                return {"response": {"ts": 1, "server": "!SERVER!", "key": ""}}
            # И этот тоже
            elif "!SERVER!" in data["url"]:
                return raw_message_builder(text=text,
                                           from_id=from_id,
                                           on_datetime=on_datetime,
                                           n_messages=n_messages)
            # Отправка сообщений со стороны бота.
            elif "messages.send" in data["url"]:
                target_data = data['data']
                if 'keyboard' in target_data:
                    try:
                        json.dumps(target_data['keyboard'])
                    except TypeError:
                        target_data['keyboard'] = target_data[
                            'keyboard'].get_json()
                return json.dumps({"response": {**data['data'], **{"r": 1}}})

        # Создадим API, в котором клиент будет ходить на коллбеки выше ВМЕСТО vk.com
        api = API("token")
        api.http._session = MockedClient(None, callback=callback)
        return api
示例#4
0
async def test_types_translator():
    api = API("token")
    assert await api.validate_request({"a": [1, 2, 3, 4, "hi!"]}) == {
        "a": "1,2,3,4,hi!"
    }
示例#5
0
async def test_ignore_errors(api: API):
    api.ignore_errors = True
    assert await api.request("some.method", {}) is None
示例#6
0
async def test_response_validators(api: API):
    api.response_validators = []
    assert await api.request("some.method", {}) == 1
示例#7
0
async def test_api_invalid_response(api: API):
    api.request_rescheduler = MockedRescheduler(None, {"some": "response"})
    response = await api.request("some.method", {})
    assert response == {"some": "response"}
示例#8
0
def set_http_callback(api: API, callback: Callable[[dict], Any]):
    api.http_client = MockedClient(callback=callback)
示例#9
0
 async def wrapper(*args, **kwargs):
     api = API("token")
     api.http._session = MockedClient(return_value)
     return await func(*args, **kwargs, api=api)