| 1 |
import json |
| 2 |
import re |
| 3 |
from typing import Optional, Union, Any |
| 4 |
from re import Pattern |
| 5 |
|
| 6 |
import httpx |
| 7 |
from httpx import QueryParams |
| 8 |
|
| 9 |
from pytest_httpx._httpx_internals import _proxy_url |
| 10 |
from pytest_httpx._options import _HTTPXMockOptions |
| 11 |
|
| 12 |
|
| 13 |
def _url_match( |
| 14 |
url_to_match: Union[Pattern[str], httpx.URL], |
| 15 |
received: httpx.URL, |
| 16 |
params: Optional[dict[str, Union[str | list[str]]]], |
| 17 |
) -> bool: |
| 18 |
if isinstance(url_to_match, re.Pattern): |
| 19 |
return url_to_match.match(str(received)) is not None |
| 20 |
|
| 21 |
# Compare query parameters apart as order of parameters should not matter |
| 22 |
received_params = to_params_dict(received.params) |
| 23 |
if params is None: |
| 24 |
params = to_params_dict(url_to_match.params) |
| 25 |
|
| 26 |
# Remove the query parameters from the original URL to compare everything besides query parameters |
| 27 |
received_url = received.copy_with(query=None) |
| 28 |
url = url_to_match.copy_with(query=None) |
| 29 |
|
| 30 |
return (received_params == params) and (url == received_url) |
| 31 |
|
| 32 |
|
| 33 |
def to_params_dict(params: QueryParams) -> dict[str, Union[str | list[str]]]: |
| 34 |
"""Convert query parameters to a dict where the value is a string if the parameter has a single value and a list of string otherwise.""" |
| 35 |
d = {} |
| 36 |
for key in params: |
| 37 |
values = params.get_list(key) |
| 38 |
d[key] = values if len(values) > 1 else values[0] |
| 39 |
return d |
| 40 |
|
| 41 |
|
| 42 |
class _RequestMatcher: |
| 43 |
def __init__( |
| 44 |
self, |
| 45 |
options: _HTTPXMockOptions, |
| 46 |
url: Optional[Union[str, Pattern[str], httpx.URL]] = None, |
| 47 |
method: Optional[str] = None, |
| 48 |
proxy_url: Optional[Union[str, Pattern[str], httpx.URL]] = None, |
| 49 |
match_headers: Optional[dict[str, Any]] = None, |
| 50 |
match_content: Optional[bytes] = None, |
| 51 |
match_json: Optional[Any] = None, |
| 52 |
match_data: Optional[dict[str, Any]] = None, |
| 53 |
match_files: Optional[Any] = None, |
| 54 |
match_extensions: Optional[dict[str, Any]] = None, |
| 55 |
match_params: Optional[dict[str, Union[str | list[str]]]] = None, |
| 56 |
is_optional: Optional[bool] = None, |
| 57 |
is_reusable: Optional[bool] = None, |
| 58 |
): |
| 59 |
self._options = options |
| 60 |
self.nb_calls = 0 |
| 61 |
self.url = httpx.URL(url) if url and isinstance(url, str) else url |
| 62 |
self.method = method.upper() if method else method |
| 63 |
self.headers = match_headers |
| 64 |
self.content = match_content |
| 65 |
self.json = match_json |
| 66 |
self.data = match_data |
| 67 |
self.files = match_files |
| 68 |
self.params = match_params |
| 69 |
self.proxy_url = ( |
| 70 |
httpx.URL(proxy_url) |
| 71 |
if proxy_url and isinstance(proxy_url, str) |
| 72 |
else proxy_url |
| 73 |
) |
| 74 |
self.extensions = match_extensions |
| 75 |
self.is_optional = ( |
| 76 |
not options.assert_all_responses_were_requested |
| 77 |
if is_optional is None |
| 78 |
else is_optional |
| 79 |
) |
| 80 |
self.is_reusable = ( |
| 81 |
options.can_send_already_matched_responses |
| 82 |
if is_reusable is None |
| 83 |
else is_reusable |
| 84 |
) |
| 85 |
if self._is_matching_body_more_than_one_way(): |
| 86 |
raise ValueError( |
| 87 |
"Only one way of matching against the body can be provided. " |
| 88 |
"If you want to match against the JSON decoded representation, use match_json. " |
| 89 |
"If you want to match against the multipart representation, use match_files (and match_data). " |
| 90 |
"Otherwise, use match_content." |
| 91 |
) |
| 92 |
if self.params and not self.url: |
| 93 |
raise ValueError("URL must be provided when match_params is used.") |
| 94 |
if self.params and isinstance(self.url, re.Pattern): |
| 95 |
raise ValueError( |
| 96 |
"match_params cannot be used in addition to regex URL. Request this feature via https://github.com/Colin-b/pytest_httpx/issues/new?title=Regex%20URL%20should%20allow%20match_params&body=Hi,%20I%20need%20a%20regex%20to%20match%20the%20non%20query%20part%20of%20the%20URL%20only" |
| 97 |
) |
| 98 |
if self._is_matching_params_more_than_one_way(): |
| 99 |
raise ValueError( |
| 100 |
"Provided URL must not contain any query parameter when match_params is used." |
| 101 |
) |
| 102 |
if self.data and not self.files: |
| 103 |
raise ValueError( |
| 104 |
"match_data is meant to be used for multipart matching (in conjunction with match_files)." |
| 105 |
"Use match_content to match url encoded data." |
| 106 |
) |
| 107 |
|
| 108 |
def expect_body(self) -> bool: |
| 109 |
matching_ways = [ |
| 110 |
self.content is not None, |
| 111 |
self.json is not None, |
| 112 |
self.files is not None, |
| 113 |
] |
| 114 |
return sum(matching_ways) == 1 |
| 115 |
|
| 116 |
def _is_matching_body_more_than_one_way(self) -> bool: |
| 117 |
matching_ways = [ |
| 118 |
self.content is not None, |
| 119 |
self.json is not None, |
| 120 |
self.files is not None, |
| 121 |
] |
| 122 |
return sum(matching_ways) > 1 |
| 123 |
|
| 124 |
def _is_matching_params_more_than_one_way(self) -> bool: |
| 125 |
url_has_params = ( |
| 126 |
bool(self.url.params) |
| 127 |
if (self.url and isinstance(self.url, httpx.URL)) |
| 128 |
else False |
| 129 |
) |
| 130 |
matching_ways = [ |
| 131 |
self.params is not None, |
| 132 |
url_has_params, |
| 133 |
] |
| 134 |
return sum(matching_ways) > 1 |
| 135 |
|
| 136 |
def match( |
| 137 |
self, |
| 138 |
real_transport: Union[httpx.HTTPTransport, httpx.AsyncHTTPTransport], |
| 139 |
request: httpx.Request, |
| 140 |
) -> bool: |
| 141 |
return ( |
| 142 |
self._url_match(request) |
| 143 |
and self._method_match(request) |
| 144 |
and self._headers_match(request) |
| 145 |
and self._content_match(request) |
| 146 |
and self._proxy_match(real_transport) |
| 147 |
and self._extensions_match(request) |
| 148 |
) |
| 149 |
|
| 150 |
def _url_match(self, request: httpx.Request) -> bool: |
| 151 |
if not self.url: |
| 152 |
return True |
| 153 |
|
| 154 |
return _url_match(self.url, request.url, self.params) |
| 155 |
|
| 156 |
def _method_match(self, request: httpx.Request) -> bool: |
| 157 |
if not self.method: |
| 158 |
return True |
| 159 |
|
| 160 |
return request.method == self.method |
| 161 |
|
| 162 |
def _headers_match(self, request: httpx.Request) -> bool: |
| 163 |
if not self.headers: |
| 164 |
return True |
| 165 |
|
| 166 |
encoding = request.headers.encoding |
| 167 |
request_headers = {} |
| 168 |
# Can be cleaned based on the outcome of https://github.com/encode/httpx/discussions/2841 |
| 169 |
for raw_name, raw_value in request.headers.raw: |
| 170 |
if raw_name in request_headers: |
| 171 |
request_headers[raw_name] += b", " + raw_value |
| 172 |
else: |
| 173 |
request_headers[raw_name] = raw_value |
| 174 |
|
| 175 |
return all( |
| 176 |
request_headers.get(header_name.encode(encoding)) |
| 177 |
== header_value.encode(encoding) |
| 178 |
for header_name, header_value in self.headers.items() |
| 179 |
) |
| 180 |
|
| 181 |
def _content_match(self, request: httpx.Request) -> bool: |
| 182 |
if self.content is not None: |
| 183 |
return request.content == self.content |
| 184 |
|
| 185 |
if self.json is not None: |
| 186 |
try: |
| 187 |
# httpx._content.encode_json hard codes utf-8 encoding. |
| 188 |
return json.loads(request.content.decode("utf-8")) == self.json |
| 189 |
except json.decoder.JSONDecodeError: |
| 190 |
return False |
| 191 |
|
| 192 |
if self.files: |
| 193 |
if not ( |
| 194 |
boundary_matched := re.match(b"^--([0-9a-f]*)\r\n", request.content) |
| 195 |
): |
| 196 |
return False |
| 197 |
# Ensure we re-use the same boundary for comparison |
| 198 |
boundary = boundary_matched.group(1) |
| 199 |
# Prevent internal httpx changes from impacting users not matching on files |
| 200 |
from httpx._multipart import MultipartStream |
| 201 |
|
| 202 |
multipart_content = b"".join( |
| 203 |
MultipartStream(self.data or {}, self.files, boundary) |
| 204 |
) |
| 205 |
return request.content == multipart_content |
| 206 |
|
| 207 |
return True |
| 208 |
|
| 209 |
def _proxy_match( |
| 210 |
self, real_transport: Union[httpx.HTTPTransport, httpx.AsyncHTTPTransport] |
| 211 |
) -> bool: |
| 212 |
if not self.proxy_url: |
| 213 |
return True |
| 214 |
|
| 215 |
if real_proxy_url := _proxy_url(real_transport): |
| 216 |
return _url_match(self.proxy_url, real_proxy_url, params=None) |
| 217 |
|
| 218 |
return False |
| 219 |
|
| 220 |
def _extensions_match(self, request: httpx.Request) -> bool: |
| 221 |
if not self.extensions: |
| 222 |
return True |
| 223 |
|
| 224 |
return all( |
| 225 |
request.extensions.get(extension_name) == extension_value |
| 226 |
for extension_name, extension_value in self.extensions.items() |
| 227 |
) |
| 228 |
|
| 229 |
def should_have_matched(self) -> bool: |
| 230 |
"""Return True if the matcher did not serve its purpose.""" |
| 231 |
return not self.is_optional and not self.nb_calls |
| 232 |
|
| 233 |
def __str__(self) -> str: |
| 234 |
if self.is_reusable: |
| 235 |
matcher_description = f"Match {self.method or 'every'} request" |
| 236 |
else: |
| 237 |
matcher_description = "Already matched" if self.nb_calls else "Match" |
| 238 |
matcher_description += f" {self.method or 'any'} request" |
| 239 |
if self.url: |
| 240 |
matcher_description += f" on {self.url}" |
| 241 |
if extra_description := self._extra_description(): |
| 242 |
matcher_description += f" with {extra_description}" |
| 243 |
return matcher_description |
| 244 |
|
| 245 |
def _extra_description(self) -> str: |
| 246 |
extra_description = [] |
| 247 |
|
| 248 |
if self.params: |
| 249 |
extra_description.append(f"{self.params} query parameters") |
| 250 |
if self.headers: |
| 251 |
extra_description.append(f"{self.headers} headers") |
| 252 |
if self.content is not None: |
| 253 |
extra_description.append(f"{self.content} body") |
| 254 |
if self.json is not None: |
| 255 |
extra_description.append(f"{self.json} json body") |
| 256 |
if self.data is not None: |
| 257 |
extra_description.append(f"{self.data} multipart data") |
| 258 |
if self.files is not None: |
| 259 |
extra_description.append(f"{self.files} files") |
| 260 |
if self.proxy_url: |
| 261 |
extra_description.append(f"{self.proxy_url} proxy URL") |
| 262 |
if self.extensions: |
| 263 |
extra_description.append(f"{self.extensions} extensions") |
| 264 |
|
| 265 |
return " and ".join(extra_description) |