Debian Codegraph @

pytest_httpx/_httpx_mock.py

raw
1 import copy
2 import inspect
3 from typing import Union, Optional, Callable, Any, NoReturn
4 from collections.abc import Awaitable
5
6 import httpx
7
8 from pytest_httpx import _httpx_internals
9 from pytest_httpx._options import _HTTPXMockOptions
10 from pytest_httpx._pretty_print import RequestDescription
11 from pytest_httpx._request_matcher import _RequestMatcher
12
13
14 class HTTPXMock:
15 """
16 This class is only exposed for `httpx_mock` fixture type hinting purpose.
17 """
18
19 def __init__(self, options: _HTTPXMockOptions) -> None:
20 """Private and subject to breaking changes without notice."""
21 self._options = options
22 self._requests: list[
23 tuple[Union[httpx.HTTPTransport, httpx.AsyncHTTPTransport], httpx.Request]
24 ] = []
25 self._callbacks: list[
26 tuple[
27 _RequestMatcher,
28 Callable[
29 [httpx.Request],
30 Union[
31 Optional[httpx.Response], Awaitable[Optional[httpx.Response]]
32 ],
33 ],
34 ]
35 ] = []
36 self._requests_not_matched: list[httpx.Request] = []
37
38 def add_response(
39 self,
40 status_code: int = 200,
41 http_version: str = "HTTP/1.1",
42 headers: Optional[_httpx_internals.HeaderTypes] = None,
43 content: Optional[bytes] = None,
44 text: Optional[str] = None,
45 html: Optional[str] = None,
46 stream: Any = None,
47 json: Any = None,
48 **matchers: Any,
49 ) -> None:
50 """
51 Mock the response that will be sent if a request match.
52
53 :param status_code: HTTP status code of the response to send. Default to 200 (OK).
54 :param http_version: HTTP protocol version of the response to send. Default to HTTP/1.1
55 :param headers: HTTP headers of the response to send. Default to no headers.
56 :param content: HTTP body of the response (as bytes).
57 :param text: HTTP body of the response (as string).
58 :param html: HTTP body of the response (as HTML string content).
59 :param stream: HTTP body of the response (as httpx.SyncByteStream or httpx.AsyncByteStream) as stream content.
60 :param json: HTTP body of the response (if JSON should be used as content type) if data is not provided.
61 :param url: Full URL identifying the request(s) to match. Use in addition to match_params if you do not want to provide query parameters as part of the URL.
62 Can be a str, a re.Pattern instance or a httpx.URL instance.
63 :param method: HTTP method identifying the request(s) to match.
64 :param proxy_url: Full proxy URL identifying the request(s) to match.
65 Can be a str, a re.Pattern instance or a httpx.URL instance.
66 :param match_headers: HTTP headers identifying the request(s) to match. Must be a dictionary.
67 :param match_content: Full HTTP body identifying the request(s) to match. Must be bytes.
68 :param match_json: JSON decoded HTTP body identifying the request(s) to match. Must be JSON encodable.
69 :param match_data: Multipart data (excluding files) identifying the request(s) to match. Must be a dictionary.
70 :param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
71 :param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
72 :param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str values (or a list of str values if parameter is provided more than once).
73 :param is_optional: True will mark this response as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
74 :param is_reusable: True will allow re-using this response even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
75 """
76
77 json = copy.deepcopy(json) if json is not None else None
78
79 def response_callback(request: httpx.Request) -> httpx.Response:
80 return httpx.Response(
81 status_code=status_code,
82 extensions={"http_version": http_version.encode("ascii")},
83 headers=headers,
84 json=json,
85 content=content,
86 text=text,
87 html=html,
88 stream=stream,
89 )
90
91 self.add_callback(response_callback, **matchers)
92
93 def add_callback(
94 self,
95 callback: Callable[
96 [httpx.Request],
97 Union[Optional[httpx.Response], Awaitable[Optional[httpx.Response]]],
98 ],
99 **matchers: Any,
100 ) -> None:
101 """
102 Mock the action that will take place if a request match.
103
104 :param callback: The callable that will be called upon reception of the matched request.
105 It must expect one parameter, the received httpx.Request and should return a httpx.Response.
106 :param url: Full URL identifying the request(s) to match. Use in addition to match_params if you do not want to provide query parameters as part of the URL.
107 Can be a str, a re.Pattern instance or a httpx.URL instance.
108 :param method: HTTP method identifying the request(s) to match.
109 :param proxy_url: Full proxy URL identifying the request(s) to match.
110 Can be a str, a re.Pattern instance or a httpx.URL instance.
111 :param match_headers: HTTP headers identifying the request(s) to match. Must be a dictionary.
112 :param match_content: Full HTTP body identifying the request(s) to match. Must be bytes.
113 :param match_json: JSON decoded HTTP body identifying the request(s) to match. Must be JSON encodable.
114 :param match_data: Multipart data (excluding files) identifying the request(s) to match. Must be a dictionary.
115 :param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
116 :param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
117 :param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str values (or a list of str values if parameter is provided more than once).
118 :param is_optional: True will mark this callback as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
119 :param is_reusable: True will allow re-using this callback even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
120 """
121 self._callbacks.append((_RequestMatcher(self._options, **matchers), callback))
122
123 def add_exception(self, exception: BaseException, **matchers: Any) -> None:
124 """
125 Raise an exception if a request match.
126
127 :param exception: The exception that will be raised upon reception of the matched request.
128 :param url: Full URL identifying the request(s) to match. Use in addition to match_params if you do not want to provide query parameters as part of the URL.
129 Can be a str, a re.Pattern instance or a httpx.URL instance.
130 :param method: HTTP method identifying the request(s) to match.
131 :param proxy_url: Full proxy URL identifying the request(s) to match.
132 Can be a str, a re.Pattern instance or a httpx.URL instance.
133 :param match_headers: HTTP headers identifying the request(s) to match. Must be a dictionary.
134 :param match_content: Full HTTP body identifying the request(s) to match. Must be bytes.
135 :param match_json: JSON decoded HTTP body identifying the request(s) to match. Must be JSON encodable.
136 :param match_data: Multipart data (excluding files) identifying the request(s) to match. Must be a dictionary.
137 :param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
138 :param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
139 :param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str values (or a list of str values if parameter is provided more than once).
140 :param is_optional: True will mark this exception response as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
141 :param is_reusable: True will allow re-using this exception response even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
142 """
143
144 def exception_callback(request: httpx.Request) -> None:
145 if isinstance(exception, httpx.RequestError):
146 exception.request = request
147 raise exception
148
149 self.add_callback(exception_callback, **matchers)
150
151 def _handle_request(
152 self,
153 real_transport: httpx.HTTPTransport,
154 request: httpx.Request,
155 ) -> httpx.Response:
156 # Store the content in request for future matching
157 request.read()
158 self._requests.append((real_transport, request))
159
160 callback = self._get_callback(real_transport, request)
161 if callback:
162 response = callback(request)
163
164 if response:
165 return _unread(response)
166
167 self._request_not_matched(real_transport, request)
168
169 async def _handle_async_request(
170 self,
171 real_transport: httpx.AsyncHTTPTransport,
172 request: httpx.Request,
173 ) -> httpx.Response:
174 # Store the content in request for future matching
175 await request.aread()
176 self._requests.append((real_transport, request))
177
178 callback = self._get_callback(real_transport, request)
179 if callback:
180 response = callback(request)
181
182 if response:
183 if inspect.isawaitable(response):
184 response = await response
185 return _unread(response)
186
187 self._request_not_matched(real_transport, request)
188
189 def _request_not_matched(
190 self,
191 real_transport: Union[httpx.AsyncHTTPTransport, httpx.HTTPTransport],
192 request: httpx.Request,
193 ) -> NoReturn:
194 self._requests_not_matched.append(request)
195 raise httpx.TimeoutException(
196 self._explain_that_no_response_was_found(real_transport, request),
197 request=request,
198 )
199
200 def _explain_that_no_response_was_found(
201 self,
202 real_transport: Union[httpx.BaseTransport, httpx.AsyncBaseTransport],
203 request: httpx.Request,
204 ) -> str:
205 matchers = [matcher for matcher, _ in self._callbacks]
206
207 message = f"No response can be found for {RequestDescription(real_transport, request, matchers)}"
208
209 already_matched = []
210 unmatched = []
211 for matcher in matchers:
212 if matcher.nb_calls:
213 already_matched.append(matcher)
214 else:
215 unmatched.append(matcher)
216
217 matchers_description = "\n".join(
218 [f"- {matcher}" for matcher in unmatched + already_matched]
219 )
220 if matchers_description:
221 message += f" amongst:\n{matchers_description}"
222 # If we could not find a response, but we have already matched responses
223 # it might be that user is expecting one of those responses to be reused
224 if any(not matcher.is_reusable for matcher in already_matched):
225 message += "\n\nIf you wanted to reuse an already matched response instead of registering it again, refer to https://github.com/Colin-b/pytest_httpx/blob/master/README.md#allow-to-register-a-response-for-more-than-one-request"
226
227 return message
228
229 def _get_callback(
230 self,
231 real_transport: Union[httpx.HTTPTransport, httpx.AsyncHTTPTransport],
232 request: httpx.Request,
233 ) -> Optional[
234 Callable[
235 [httpx.Request],
236 Union[Optional[httpx.Response], Awaitable[Optional[httpx.Response]]],
237 ]
238 ]:
239 callbacks = [
240 (matcher, callback)
241 for matcher, callback in self._callbacks
242 if matcher.match(real_transport, request)
243 ]
244
245 # No callback match this request
246 if not callbacks:
247 return None
248
249 # Callbacks match this request
250 for matcher, callback in callbacks:
251 # Return the first not yet called
252 if not matcher.nb_calls:
253 matcher.nb_calls += 1
254 return callback
255
256 # Or the last registered (if it can be reused)
257 if matcher.is_reusable:
258 matcher.nb_calls += 1
259 return callback
260
261 # All callbacks have already been matched and last registered cannot be reused
262 return None
263
264 def get_requests(self, **matchers: Any) -> list[httpx.Request]:
265 """
266 Return all requests sent that match (empty list if no requests were matched).
267
268 :param url: Full URL identifying the requests to retrieve. Use in addition to match_params if you do not want to provide query parameters as part of the URL.
269 Can be a str, a re.Pattern instance or a httpx.URL instance.
270 :param method: HTTP method identifying the requests to retrieve. Must be an upper-cased string value.
271 :param proxy_url: Full proxy URL identifying the requests to retrieve.
272 Can be a str, a re.Pattern instance or a httpx.URL instance.
273 :param match_headers: HTTP headers identifying the requests to retrieve. Must be a dictionary.
274 :param match_content: Full HTTP body identifying the requests to retrieve. Must be bytes.
275 :param match_json: JSON decoded HTTP body identifying the requests to retrieve. Must be JSON encodable.
276 :param match_data: Multipart data (excluding files) identifying the requests to retrieve. Must be a dictionary.
277 :param match_files: Multipart files identifying the requests to retrieve. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
278 :param match_extensions: Extensions identifying the requests to retrieve. Must be a dictionary.
279 :param match_params: Query string parameters identifying the requests to retrieve (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str values (or a list of str values if parameter is provided more than once).
280 """
281 matcher = _RequestMatcher(self._options, **matchers)
282 return [
283 request
284 for real_transport, request in self._requests
285 if matcher.match(real_transport, request)
286 ]
287
288 def get_request(self, **matchers: Any) -> Optional[httpx.Request]:
289 """
290 Return the single request that match (or None).
291
292 :param url: Full URL identifying the request to retrieve. Use in addition to match_params if you do not want to provide query parameters as part of the URL.
293 Can be a str, a re.Pattern instance or a httpx.URL instance.
294 :param method: HTTP method identifying the request to retrieve. Must be an upper-cased string value.
295 :param proxy_url: Full proxy URL identifying the request to retrieve.
296 Can be a str, a re.Pattern instance or a httpx.URL instance.
297 :param match_headers: HTTP headers identifying the request to retrieve. Must be a dictionary.
298 :param match_content: Full HTTP body identifying the request to retrieve. Must be bytes.
299 :param match_json: JSON decoded HTTP body identifying the request to retrieve. Must be JSON encodable.
300 :param match_data: Multipart data (excluding files) identifying the request to retrieve. Must be a dictionary.
301 :param match_files: Multipart files identifying the request to retrieve. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
302 :param match_extensions: Extensions identifying the request to retrieve. Must be a dictionary.
303 :param match_params: Query string parameters identifying the request to retrieve (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str values (or a list of str values if parameter is provided more than once).
304 :raises AssertionError: in case more than one request match.
305 """
306 requests = self.get_requests(**matchers)
307 assert (
308 len(requests) <= 1
309 ), f"More than one request ({len(requests)}) matched, use get_requests instead or refine your filters."
310 return requests[0] if requests else None
311
312 def reset(self) -> None:
313 self._requests.clear()
314 self._callbacks.clear()
315 self._requests_not_matched.clear()
316
317 def _assert_options(self) -> None:
318 callbacks_not_executed = [
319 matcher for matcher, _ in self._callbacks if matcher.should_have_matched()
320 ]
321 matchers_description = "\n".join(
322 [f"- {matcher}" for matcher in callbacks_not_executed]
323 )
324
325 assert not callbacks_not_executed, (
326 "The following responses are mocked but not requested:\n"
327 f"{matchers_description}\n"
328 "\n"
329 "If this is on purpose, refer to https://github.com/Colin-b/pytest_httpx/blob/master/README.md#allow-to-register-more-responses-than-what-will-be-requested"
330 )
331
332 if self._options.assert_all_requests_were_expected:
333 requests_description = "\n".join(
334 [
335 f"- {request.method} request on {request.url}"
336 for request in self._requests_not_matched
337 ]
338 )
339 assert not self._requests_not_matched, (
340 f"The following requests were not expected:\n"
341 f"{requests_description}\n"
342 "\n"
343 "If this is on purpose, refer to https://github.com/Colin-b/pytest_httpx/blob/master/README.md#allow-to-not-register-responses-for-every-request"
344 )
345
346
347 def _unread(response: httpx.Response) -> httpx.Response:
348 # Allow to read the response on client side
349 response.is_stream_consumed = False
350 response.is_closed = False
351 if hasattr(response, "_content"):
352 del response._content
353 return response