Skip to content

MockTransport doesn't set the elapsed property #3712

Description

@ionelmc

This is not a nice solution:

def handler(request):
    resp = httpx.Response(200, json={"text": "Hello, world!"})
    resp.elapsed = timedelta(.......
    return resp

If you have dispatch code in that handler that can easily get boilerplatey.

I think httpx should do either of these:

  • MockTransport take the duration as an optional argument
  • httpx provide a decorator, so you can wrap your handler in it
  • automatically set a duration of 0 for manually created Response objects - why error out if the data is already there?

Activity

  1. added a commit that references this issue on Dec 9, 2025
    0baeaf2
  2. karpetrosyan commented on Dec 10, 2025

    @karpetrosyan
    Contributor

    This issue already has two PRs with proposed fixes, but for now I suggest a very simple way to fix it without extra boilerplate code. We can close the PRs until we make a good design decision around this.

    You can write a very simple wrapper around that mock transport and use it instead of the default one. Then you can handle the elapsed time for mocked responses however you want, like this.

    from __future__ import annotations
    
    from datetime import timedelta
    
    import httpx
    
    
    class CustomMock(httpx.BaseTransport):
        def __init__(self, next_transport: httpx.BaseTransport | None = None) -> None:
            self._next_transport = httpx.MockTransport() if next_transport is None else next_transport
    
        def handle_request(self, request: httpx.Request) -> httpx.Response:
            response = self._next_transport.handle_request(request)
            response.elapsed = timedelta()
            return response
    
    # use custom mock instead of the default mock
  3. added a commit that references this issue on Jan 7, 2026
    d4d9883
  4. added a commit that references this issue on Feb 8, 2026
    313a4f4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions