Skip to content
Myr

Allow handler to optionally be async when MockTransport is used with AsyncClient (#1449)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent 645ae4e · Browse files · 2 files+24 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+24 added−0 removed

  • tests:+13 added−0 removed
  • other:+11 added−0 removed

2 files+24 added−0 removed

modified:httpx/_transports/mock.py+11 added
1import asyncio2from typing import Callable, List, Optional, Tuple34import httpcore5
41 unmodified lines
47 headers=headers,48 stream=stream,49 )50 await request.aread()5152 response = self.handler(request)5354 # Allow handler to *optionally* be an `async` function.55 # If it is, then the `response` variable need to be awaited to actually56 # return the result.5758 # https://simonwillison.net/2020/Sep/2/await-me-maybe/59 if asyncio.iscoroutine(response):60 response = await response6162 return (63 response.status_code,64 response.headers.raw,65 response.stream,
2 unmodified lines
modified:tests/client/test_async_client.py+13 added
299 unmodified lines
300301 response = await client.get("custom://www.example.com")302 assert response.status_code == 200303 assert response.json() == {"app": "mounted"}304305306@pytest.mark.usefixtures("async_environment")307async def test_async_mock_transport():308 async def hello_world(request):309 return httpx.Response(200, text="Hello, world!")310311 transport = httpx.MockTransport(hello_world)312313 async with httpx.AsyncClient(transport=transport) as client:314 response = await client.get("https://www.example.com")315 assert response.status_code == 200316 assert response.text == "Hello, world!"