Skip to content

Commit

Permalink
Refactor anyio.sleep into an event
Browse files Browse the repository at this point in the history
  • Loading branch information
uSpike committed May 13, 2021
1 parent c4d49a7 commit 4dd8c5d
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions starlette/testclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,17 +169,16 @@ def send(

request_complete = False
response_started = False
response_complete = False
response_complete: anyio.Event
raw_kwargs = {"body": io.BytesIO()} # type: typing.Dict[str, typing.Any]
template = None
context = None

async def receive() -> Message:
nonlocal request_complete, response_complete
nonlocal request_complete

if request_complete:
while not response_complete:
await anyio.sleep(0.0001)
await response_complete.wait()
return {"type": "http.disconnect"}

body = request.body
Expand All @@ -203,7 +202,7 @@ async def receive() -> Message:
return {"type": "http.request", "body": body_bytes}

async def send(message: Message) -> None:
nonlocal raw_kwargs, response_started, response_complete, template, context
nonlocal raw_kwargs, response_started, template, context

if message["type"] == "http.response.start":
assert (
Expand All @@ -225,21 +224,22 @@ async def send(message: Message) -> None:
response_started
), 'Received "http.response.body" without "http.response.start".'
assert (
not response_complete
not response_complete.is_set()
), 'Received "http.response.body" after response completed.'
body = message.get("body", b"")
more_body = message.get("more_body", False)
if request.method != "HEAD":
raw_kwargs["body"].write(body)
if not more_body:
raw_kwargs["body"].seek(0)
response_complete = True
response_complete.set()
elif message["type"] == "http.response.template":
template = message["template"]
context = message["context"]

try:
with anyio.start_blocking_portal(**self.async_backend) as portal:
response_complete = portal.call(anyio.Event)
portal.call(self.app, scope, receive, send)
except BaseException as exc:
if self.raise_server_exceptions:
Expand Down

0 comments on commit 4dd8c5d

Please sign in to comment.