Created
June 18, 2019 13:32
-
-
Save DrMartiner/fccfdb4bfdd64fd4f7f9a54000ac2c84 to your computer and use it in GitHub Desktop.
Mock aiohttp http request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aiohttp import web, ClientSession | |
async def handler(request): | |
async with ClientSession() as session: | |
async with session.post("http://service/path", json={"key": "value"}) as response: | |
if response.status in [200, 201]: | |
data = await response.json() | |
result = data.get("result", False) | |
await session.close() | |
return web.json_response({"result": result}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from asynctest import CoroutineMock, patch | |
from aiohttp import web, ClientResponse | |
from aiohttp.test_utils import TestClient | |
@patch("aiohttp.ClientSession.post") | |
async def test_call_other_service(mock: CoroutineMock, aiohttp_client: TestClient) -> None: | |
""" | |
Mock calling aiohttp HTTP request | |
""" | |
returned_data = {"key": "value"} | |
mock.return_value.__aenter__.return_value.json = CoroutineMock( | |
side_effect=lambda: returned_data | |
) | |
app = web.Application() | |
web_client = await aiohttp_client(app) | |
response: ClientResponse = await web_client.get("/path") | |
assert response.status == 200 | |
assert mock.called | |
assert mock.call_count == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment