-
-
Notifications
You must be signed in to change notification settings - Fork 839
/
utils.py
75 lines (65 loc) · 2.03 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import contextlib
import logging
import os
from typing import Callable, List, Optional, Tuple
import httpcore
import httpx
from httpx import _utils
@contextlib.contextmanager
def override_log_level(log_level: str):
os.environ["HTTPX_LOG_LEVEL"] = log_level
# Force a reload on the logging handlers
_utils._LOGGER_INITIALIZED = False
_utils.get_logger("httpx")
try:
yield
finally:
# Reset the logger so we don't have verbose output in all unit tests
logging.getLogger("httpx").handlers = []
class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):
def __init__(self, handler: Callable) -> None:
self.handler = handler
def request(
self,
method: bytes,
url: Tuple[bytes, bytes, Optional[int], bytes],
headers: List[Tuple[bytes, bytes]] = None,
stream: httpcore.SyncByteStream = None,
ext: dict = None,
) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.SyncByteStream, dict]:
request = httpx.Request(
method=method,
url=url,
headers=headers,
stream=stream,
)
request.read()
response = self.handler(request)
return (
response.status_code,
response.headers.raw,
response.stream,
response.ext,
)
async def arequest(
self,
method: bytes,
url: Tuple[bytes, bytes, Optional[int], bytes],
headers: List[Tuple[bytes, bytes]] = None,
stream: httpcore.AsyncByteStream = None,
ext: dict = None,
) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:
request = httpx.Request(
method=method,
url=url,
headers=headers,
stream=stream,
)
await request.aread()
response = self.handler(request)
return (
response.status_code,
response.headers.raw,
response.stream,
response.ext,
)