Skip to content

fix: set elapsed property in MockTransport responses - #3843

Open
shrimanasa wants to merge 1 commit into
encode:masterfrom
shrimanasa:fix/mock-transport-elapsed-property
Open

shrimanasa wants to merge 1 commit into
encode:masterfrom
shrimanasa:fix/mock-transport-elapsed-property

Conversation

@shrimanasa

Copy link
Copy Markdown

Summary

Fixes #3712

MockTransport did not set the elapsed property on responses, causing a RuntimeError when users accessed response.elapsed in tests.

Changes

Both handle_request and handle_async_request now:

  1. Record the start time before invoking the handler
  2. Set response.elapsed as a datetime.timedelta after the handler returns

If the handler already sets elapsed manually, it is preserved (the fix only sets it when _elapsed is not already present).

Example

Before this fix:

def handler(request):
    return httpx.Response(200)

transport = httpx.MockTransport(handler)
client = httpx.Client(transport=transport)
response = client.get('http://example.com')
print(response.elapsed)  # RuntimeError: '.elapsed' may only be accessed after the response has been read or closed.

After this fix:

print(response.elapsed)  # datetime.timedelta(microseconds=42)

MockTransport did not set the  property on responses,
causing a RuntimeError when users accessed
in tests using MockTransport.

Both sync and async handlers now record the time taken to invoke
the handler and set response.elapsed accordingly, matching the
behaviour of real transports. If the handler already sets elapsed
manually, it is left untouched.

Closes encode#3712

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

MockTransport doesn't set the elapsed property

1 participant