Skip to content

Commit

Permalink
Allow handler to optionally be async when MockTransport is used with …
Browse files Browse the repository at this point in the history
…AsyncClient (#1449)
  • Loading branch information
tomchristie committed Feb 17, 2021
1 parent 645ae4e commit 084f356
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions httpx/_transports/mock.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
from typing import Callable, List, Optional, Tuple

import httpcore
Expand Down Expand Up @@ -47,7 +48,17 @@ async def arequest(
stream=stream,
)
await request.aread()

response = self.handler(request)

# Allow handler to *optionally* be an `async` function.
# If it is, then the `response` variable need to be awaited to actually
# return the result.

# https://simonwillison.net/2020/Sep/2/await-me-maybe/
if asyncio.iscoroutine(response):
response = await response

return (
response.status_code,
response.headers.raw,
Expand Down
13 changes: 13 additions & 0 deletions tests/client/test_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,3 +301,16 @@ async def test_mounted_transport():
response = await client.get("custom://www.example.com")
assert response.status_code == 200
assert response.json() == {"app": "mounted"}


@pytest.mark.usefixtures("async_environment")
async def test_async_mock_transport():
async def hello_world(request):
return httpx.Response(200, text="Hello, world!")

transport = httpx.MockTransport(hello_world)

async with httpx.AsyncClient(transport=transport) as client:
response = await client.get("https://www.example.com")
assert response.status_code == 200
assert response.text == "Hello, world!"

0 comments on commit 084f356

Please sign in to comment.