Debian Codegraph @

pytest_httpx/_httpx_internals.py

raw
1 import base64
2 from typing import Union, Optional
3 from collections.abc import Sequence, Iterable, AsyncIterator, Iterator
4
5 import httpcore
6 import httpx
7
8 # TODO Get rid of this internal import
9 from httpx._content import IteratorByteStream, AsyncIteratorByteStream
10
11 # Those types are internally defined within httpx._types
12 HeaderTypes = Union[
13 httpx.Headers,
14 dict[str, str],
15 dict[bytes, bytes],
16 Sequence[tuple[str, str]],
17 Sequence[tuple[bytes, bytes]],
18 ]
19
20
21 class IteratorStream(AsyncIteratorByteStream, IteratorByteStream):
22 def __init__(self, stream: Iterable[bytes]):
23 class Stream:
24 def __iter__(self) -> Iterator[bytes]:
25 yield from stream
26
27 async def __aiter__(self) -> AsyncIterator[bytes]:
28 for chunk in stream:
29 yield chunk
30
31 AsyncIteratorByteStream.__init__(self, stream=Stream())
32 IteratorByteStream.__init__(self, stream=Stream())
33
34
35 def _to_httpx_url(url: httpcore.URL, headers: list[tuple[bytes, bytes]]) -> httpx.URL:
36 for name, value in headers:
37 if b"Proxy-Authorization" == name:
38 return httpx.URL(
39 scheme=url.scheme.decode(),
40 host=url.host.decode(),
41 port=url.port,
42 raw_path=url.target,
43 userinfo=base64.b64decode(value[6:]),
44 )
45
46 return httpx.URL(
47 scheme=url.scheme.decode(),
48 host=url.host.decode(),
49 port=url.port,
50 raw_path=url.target,
51 )
52
53
54 def _proxy_url(
55 real_transport: Union[httpx.HTTPTransport, httpx.AsyncHTTPTransport],
56 ) -> Optional[httpx.URL]:
57 if isinstance(
58 real_pool := real_transport._pool, (httpcore.HTTPProxy, httpcore.AsyncHTTPProxy)
59 ):
60 return _to_httpx_url(real_pool._proxy_url, real_pool._proxy_headers)