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
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
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
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!" }
async def test_ignore_errors(api: API): api.ignore_errors = True assert await api.request("some.method", {}) is None
async def test_response_validators(api: API): api.response_validators = [] assert await api.request("some.method", {}) == 1
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"}
def set_http_callback(api: API, callback: Callable[[dict], Any]): api.http_client = MockedClient(callback=callback)
async def wrapper(*args, **kwargs): api = API("token") api.http._session = MockedClient(return_value) return await func(*args, **kwargs, api=api)