Skip to content
Myr

Add `.elapsed` onto Response objects tracking how long a request took. (#351)

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

* Add `.elapsed` onto Response objects tracking how long a request took. * Move elapsed timing from send methods into _get_response * Address feedback * Update tests/test_api.py

authored by Roy Williams · committed by Florimond Manca · parent 8155352 · Browse files · 9 files+94 added−7 removed
This commit

State

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

Trailers

  • Co-Authored-By: Florimond Manca <florimond.manca@gmail.com>

Diff stats

9 files+94 added−7 removed

  • tests:+48 added−3 removed
  • other:+46 added−4 removed

9 files+94 added−7 removed

modified:docs/api.md+5 added
modified:httpx/client.py+7 added-4 removed
43 unmodified lines
44 Response,45 ResponseContent,46 URLTypes,47)48from .utils import get_netrc_login48from .utils import ElapsedTimer, get_netrc_login495051class BaseClient:52 def __init__(
114 unmodified lines
167 raise InvalidURL('URL scheme must be "http" or "https".')168169 async def get_response(request: AsyncRequest) -> AsyncResponse:170 try:171 with ElapsedTimer() as timer:171 response = await self.dispatch.send(172 request, verify=verify, cert=cert, timeout=timeout173 )172 response = await self.dispatch.send(173 request, verify=verify, cert=cert, timeout=timeout174 )175 response.elapsed = timer.elapsed176 except HTTPError as exc:177 # Add the original request to any HTTPError178 exc.request = request179 raise
528 unmodified lines
708 content=sync_content,709 on_close=sync_on_close,710 request=async_response.request,711 history=async_response.history,712 elapsed=async_response.elapsed,713 )714 if not stream:715 try:716 response.read()
252 unmodified lines
modified:httpx/models.py+7 added
1import cgi2import datetime3import email.message4import json as jsonlib5import typing6import urllib.request
710 unmodified lines
717 http_version: str = None,718 headers: HeaderTypes = None,719 request: BaseRequest = None,720 on_close: typing.Callable = None,721 elapsed: datetime.timedelta = None,722 ):723 self.status_code = status_code724 self.http_version = http_version725 self.headers = Headers(headers)726727 self.request = request728 self.on_close = on_close729 self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed730 self.call_next: typing.Optional[typing.Callable] = None731732 @property733 def reason_phrase(self) -> str:
169 unmodified lines
903 content: AsyncResponseContent = None,904 on_close: typing.Callable = None,905 request: AsyncRequest = None,906 history: typing.List["BaseResponse"] = None,907 elapsed: datetime.timedelta = None,908 ):909 super().__init__(910 status_code=status_code,911 http_version=http_version,912 headers=headers,913 request=request,914 on_close=on_close,915 elapsed=elapsed,916 )917918 self.history = [] if history is None else list(history)919
84 unmodified lines
1004 content: ResponseContent = None,1005 on_close: typing.Callable = None,1006 request: Request = None,1007 history: typing.List["BaseResponse"] = None,1008 elapsed: datetime.timedelta = None,1009 ):1010 super().__init__(1011 status_code=status_code,1012 http_version=http_version,1013 headers=headers,1014 request=request,1015 on_close=on_close,1016 elapsed=elapsed,1017 )10181019 self.history = [] if history is None else list(history)1020
241 unmodified lines
modified:httpx/utils.py+27 added
3 unmodified lines
4import os5import re6import sys7import typing8from datetime import timedelta9from pathlib import Path10from time import perf_counter11from types import TracebackType121314def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:15 """
169 unmodified lines
185186187def unquote(value: str) -> str:188 return value[1:-1] if value[0] == value[-1] == '"' else value189190191class ElapsedTimer:192 def __init__(self) -> None:193 self.start: float = perf_counter()194 self.end: typing.Optional[float] = None195196 def __enter__(self) -> "ElapsedTimer":197 self.start = perf_counter()198 return self199200 def __exit__(201 self,202 exc_type: typing.Type[BaseException] = None,203 exc_value: BaseException = None,204 traceback: TracebackType = None,205 ) -> None:206 self.end = perf_counter()207208 @property209 def elapsed(self) -> timedelta:210 if self.end is None:211 return timedelta(seconds=perf_counter() - self.start)212 return timedelta(seconds=self.end - self.start)
modified:tests/client/test_async_client.py+3 added
1from datetime import timedelta23import pytest45import httpx6
6 unmodified lines
13 assert response.text == "Hello, world!"14 assert response.http_version == "HTTP/1.1"15 assert response.headers16 assert repr(response) == "<Response [200 OK]>"17 assert response.elapsed > timedelta(seconds=0)181920async def test_build_request(server, backend):21 url = server.url.copy_with(path="/echo_headers")
127 unmodified lines
modified:tests/client/test_client.py+18 added
1from datetime import timedelta2from time import sleep34import pytest56import httpx7
11 unmodified lines
19 assert response.request.url == url20 assert response.headers21 assert response.is_redirect is False22 assert repr(response) == "<Response [200 OK]>"23 assert response.elapsed > timedelta(0)242526def test_build_request(server):27 url = server.url.copy_with(path="/echo_headers")
131 unmodified lines
159 httpx.Client(backend=DerivedFromAsyncioBackend())160161 with pytest.raises(ValueError):162 httpx.Client(backend=AnyBackend())163164165def test_elapsed_delay(server):166 with httpx.Client() as http:167 response = http.get(server.url.copy_with(path="/slow_response/100"))168 assert response.elapsed.total_seconds() == pytest.approx(0.1, abs=0.01)169170171def test_elapsed_delay_ignores_read_time(server):172 with httpx.Client() as http:173 response = http.get(server.url.copy_with(path="/slow_response/50"), stream=True)174 sleep(0.1)175 response.read()176 assert response.elapsed.total_seconds() == pytest.approx(0.05, abs=0.01)
modified:tests/models/test_responses.py+2 added
1import datetime2import json3from unittest import mock45import pytest
15 unmodified lines
21 response = httpx.Response(200, content=b"Hello, world!")22 assert response.status_code == 20023 assert response.reason_phrase == "OK"24 assert response.text == "Hello, world!"25 assert response.elapsed == datetime.timedelta(0)262728def test_response_repr():29 response = httpx.Response(200, content=b"Hello, world!")
299 unmodified lines
modified:tests/conftest.py+7 added-2 removed
51 unmodified lines
525354async def app(scope, receive, send):55 assert scope["type"] == "http"56 if scope["path"] == "/slow_response":56 if scope["path"].startswith("/slow_response"):57 await slow_response(scope, receive, send)58 elif scope["path"].startswith("/status"):59 await status_code(scope, receive, send)60 elif scope["path"].startswith("/echo_body"):
15 unmodified lines
76 await send({"type": "http.response.body", "body": b"Hello, world!"})777879async def slow_response(scope, receive, send):80 delay_ms_str: str = scope["path"].replace("/slow_response/", "")81 try:82 delay_ms = float(delay_ms_str)83 except ValueError:84 delay_ms = 10080 await asyncio.sleep(0.1)85 await asyncio.sleep(delay_ms / 1000.0)86 await send(87 {88 "type": "http.response.start",89 "status": 200,
188 unmodified lines
modified:tests/test_utils.py+18 added-1 removed
1import asyncio2import logging3import os45import pytest67import httpx8from httpx import utils8from httpx.utils import get_netrc_login, guess_json_utf, parse_header_links9from httpx.utils import (10 ElapsedTimer,11 get_netrc_login,12 guess_json_utf,13 parse_header_links,14)151617@pytest.mark.parametrize(18 "encoding",
97 unmodified lines
116 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err117118 # Reset the logger so we don't have verbose output in all unit tests119 logging.getLogger("httpx").handlers = []120121122@pytest.mark.asyncio123async def test_elapsed_timer():124 with ElapsedTimer() as timer:125 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)126 await asyncio.sleep(0.1)127 await asyncio.sleep(128 0.1129 ) # test to ensure time spent after timer exits isn't accounted for.130 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)