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
Provenance
- Commit
05ac117- Tree
0c597e0- Author
Roy Williams <roy.williams.iii@gmail.com>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
8155352
9 files changed+94 added−7 removed
modified:docs/api.md+5 added
57 unmodified lines5859606162636465666768697092 unmodified lines57 unmodified lines* `.is_redirect` - **bool*** `.request` - **Request*** `.cookies` - **Cookies*** `.history` - **List[Response]*** `.elapsed` - **[timedelta](https://docs.python.org/3/library/datetime.html)** * The amount of time elapsed between sending the first byte and parsing the headers (not including time spent reading the response). Use [total_seconds()](https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds) to correctly get the total elapsed seconds.* `def .raise_for_status()` - **None*** `def .json()` - **Any*** `def .read()` - **bytes*** `def .stream()` - **bytes iterator**92 unmodified linesmodified:httpx/client.py+7 added-4 removed
43 unmodified lines44 Response,45 ResponseContent,46 URLTypes,47 )48-from .utils import get_netrc_login48+from .utils import ElapsedTimer, get_netrc_login49 50 51 class BaseClient:52 def __init__(114 unmodified lines167 raise InvalidURL('URL scheme must be "http" or "https".')168 169 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 raise528 unmodified lines708 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 linesmodified:httpx/models.py+7 added
1 import cgi2+import datetime3 import email.message4 import json as jsonlib5 import typing6 import urllib.request710 unmodified lines717 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)726 727 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] = None731 732 @property733 def reason_phrase(self) -> str:169 unmodified lines903 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 )917 918 self.history = [] if history is None else list(history)919 84 unmodified lines1004 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 )1018 1019 self.history = [] if history is None else list(history)1020 241 unmodified linesmodified:httpx/utils.py+27 added
3 unmodified lines4 import os5 import re6 import sys7 import typing8+from datetime import timedelta9 from pathlib import Path10+from time import perf_counter11+from types import TracebackType12 13 14 def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:15 """169 unmodified lines185 186 187 def unquote(value: str) -> str:188 return value[1:-1] if value[0] == value[-1] == '"' else value189+190+191+class ElapsedTimer:192+ def __init__(self) -> None:193+ self.start: float = perf_counter()194+ self.end: typing.Optional[float] = None195+196+ def __enter__(self) -> "ElapsedTimer":197+ self.start = perf_counter()198+ return self199+200+ 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()207+208+ @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
1+from datetime import timedelta2+3 import pytest4 5 import httpx6 6 unmodified lines13 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)18 19 20 async def test_build_request(server, backend):21 url = server.url.copy_with(path="/echo_headers")127 unmodified linesmodified:tests/client/test_client.py+18 added
1+from datetime import timedelta2+from time import sleep3+4 import pytest5 6 import httpx7 11 unmodified lines19 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)24 25 26 def test_build_request(server):27 url = server.url.copy_with(path="/echo_headers")131 unmodified lines159 httpx.Client(backend=DerivedFromAsyncioBackend())160 161 with pytest.raises(ValueError):162 httpx.Client(backend=AnyBackend())163+164+165+def 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)169+170+171+def 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
1+import datetime2 import json3 from unittest import mock4 5 import pytest15 unmodified lines21 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)26 27 28 def test_response_repr():29 response = httpx.Response(200, content=b"Hello, world!")299 unmodified linesmodified:tests/conftest.py+7 added-2 removed
51 unmodified lines52 53 54 async 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 lines76 await send({"type": "http.response.body", "body": b"Hello, world!"})77 78 79 async 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 linesmodified:tests/test_utils.py+18 added-1 removed
1+import asyncio2 import logging3 import os4 5 import pytest6 7 import httpx8 from httpx import utils8-from httpx.utils import get_netrc_login, guess_json_utf, parse_header_links9+from httpx.utils import (10+ ElapsedTimer,11+ get_netrc_login,12+ guess_json_utf,13+ parse_header_links,14+)15 16 17 @pytest.mark.parametrize(18 "encoding",97 unmodified lines116 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err117 118 # Reset the logger so we don't have verbose output in all unit tests119 logging.getLogger("httpx").handlers = []120+121+122+@pytest.mark.asyncio123+async 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)