| 1 |
from typing import Union |
| 2 |
|
| 3 |
import httpx |
| 4 |
|
| 5 |
from pytest_httpx._httpx_internals import _proxy_url |
| 6 |
from pytest_httpx._request_matcher import _RequestMatcher |
| 7 |
|
| 8 |
|
| 9 |
class RequestDescription: |
| 10 |
def __init__( |
| 11 |
self, |
| 12 |
real_transport: Union[httpx.BaseTransport, httpx.AsyncBaseTransport], |
| 13 |
request: httpx.Request, |
| 14 |
matchers: list[_RequestMatcher], |
| 15 |
): |
| 16 |
self.real_transport = real_transport |
| 17 |
self.request = request |
| 18 |
|
| 19 |
headers_encoding = request.headers.encoding |
| 20 |
self.expected_headers = { |
| 21 |
# httpx uses lower cased header names as internal key |
| 22 |
header.lower().encode(headers_encoding) |
| 23 |
for matcher in matchers |
| 24 |
if matcher.headers |
| 25 |
for header in matcher.headers |
| 26 |
} |
| 27 |
self.expect_body = any([matcher.expect_body() for matcher in matchers]) |
| 28 |
self.expect_proxy = any([matcher.proxy_url is not None for matcher in matchers]) |
| 29 |
self.expected_extensions = { |
| 30 |
extension |
| 31 |
for matcher in matchers |
| 32 |
if matcher.extensions |
| 33 |
for extension in matcher.extensions |
| 34 |
} |
| 35 |
|
| 36 |
def __str__(self) -> str: |
| 37 |
request_description = f"{self.request.method} request on {self.request.url}" |
| 38 |
if extra_description := self.extra_request_description(): |
| 39 |
request_description += f" with {extra_description}" |
| 40 |
return request_description |
| 41 |
|
| 42 |
def extra_request_description(self) -> str: |
| 43 |
extra_description = [] |
| 44 |
|
| 45 |
if self.expected_headers: |
| 46 |
headers_encoding = self.request.headers.encoding |
| 47 |
present_headers = {} |
| 48 |
# Can be cleaned based on the outcome of https://github.com/encode/httpx/discussions/2841 |
| 49 |
for name, lower_name, value in self.request.headers._list: |
| 50 |
if lower_name in self.expected_headers: |
| 51 |
name = name.decode(headers_encoding) |
| 52 |
if name in present_headers: |
| 53 |
present_headers[name] += f", {value.decode(headers_encoding)}" |
| 54 |
else: |
| 55 |
present_headers[name] = value.decode(headers_encoding) |
| 56 |
|
| 57 |
extra_description.append(f"{present_headers} headers") |
| 58 |
|
| 59 |
if self.expect_body: |
| 60 |
extra_description.append(f"{self.request.read()} body") |
| 61 |
|
| 62 |
if self.expect_proxy: |
| 63 |
proxy_url = _proxy_url(self.real_transport) |
| 64 |
extra_description.append(f"{proxy_url if proxy_url else 'no'} proxy URL") |
| 65 |
|
| 66 |
if self.expected_extensions: |
| 67 |
present_extensions = { |
| 68 |
name: value |
| 69 |
for name, value in self.request.extensions.items() |
| 70 |
if name in self.expected_extensions |
| 71 |
} |
| 72 |
extra_description.append(f"{present_extensions} extensions") |
| 73 |
|
| 74 |
return " and ".join(extra_description) |