Skip to content

Instantly share code, notes, and snippets.

@DrMartiner
Created June 18, 2019 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrMartiner/fccfdb4bfdd64fd4f7f9a54000ac2c84 to your computer and use it in GitHub Desktop.
Save DrMartiner/fccfdb4bfdd64fd4f7f9a54000ac2c84 to your computer and use it in GitHub Desktop.
Mock aiohttp http request
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})
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