Skip to content
Myr

utils.py

This file

Path

tests/utils.py

103 lines · 2.9 KiB · Python

Last changed by

Requests from transport API (#1293)Tom Christiebefore adoptione1f7791

History of this file

Take it

1import contextlib2import logging3import os4from typing import Callable, List, Mapping, Optional, Tuple56import httpcore78import httpx9from httpx import _utils101112@contextlib.contextmanager13def override_log_level(log_level: str):14    os.environ["HTTPX_LOG_LEVEL"] = log_level1516    # Force a reload on the logging handlers17    _utils._LOGGER_INITIALIZED = False18    _utils.get_logger("httpx")1920    try:21        yield22    finally:23        # Reset the logger so we don't have verbose output in all unit tests24        logging.getLogger("httpx").handlers = []252627class MockTransport(httpcore.SyncHTTPTransport):28    def __init__(self, handler: Callable) -> None:29        self.handler = handler3031    def request(32        self,33        method: bytes,34        url: Tuple[bytes, bytes, Optional[int], bytes],35        headers: List[Tuple[bytes, bytes]] = None,36        stream: httpcore.SyncByteStream = None,37        timeout: Mapping[str, Optional[float]] = None,38    ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:39        request_headers = httpx.Headers(headers)40        content = (41            (item for item in stream)42            if stream43            and (44                "Content-Length" in request_headers45                or "Transfer-Encoding" in request_headers46            )47            else None48        )4950        request = httpx.Request(51            method=method,52            url=url,53            headers=request_headers,54            content=content,55        )56        request.read()57        response = self.handler(request)58        return (59            (response.http_version or "HTTP/1.1").encode("ascii"),60            response.status_code,61            response.reason_phrase.encode("ascii"),62            response.headers.raw,63            response._raw_stream,64        )656667class AsyncMockTransport(httpcore.AsyncHTTPTransport):68    def __init__(self, handler: Callable) -> None:69        self.impl = MockTransport(handler)7071    async def request(72        self,73        method: bytes,74        url: Tuple[bytes, bytes, Optional[int], bytes],75        headers: List[Tuple[bytes, bytes]] = None,76        stream: httpcore.AsyncByteStream = None,77        timeout: Mapping[str, Optional[float]] = None,78    ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:79        content = (80            httpcore.PlainByteStream(b"".join([part async for part in stream]))81            if stream82            else httpcore.PlainByteStream(b"")83        )8485        (86            http_version,87            status_code,88            reason_phrase,89            headers,90            response_stream,91        ) = self.impl.request(92            method, url, headers=headers, stream=content, timeout=timeout93        )9495        content = httpcore.PlainByteStream(b"".join([part for part in response_stream]))9697        return (98            http_version,99            status_code,100            reason_phrase,101            headers,102            content,103        )