|
1 |
| -import http |
2 | 1 | import inspect
|
3 | 2 | import json as json_module
|
4 | 3 | import logging
|
5 |
| -import socket |
6 | 4 | from functools import partialmethod
|
7 | 5 | from functools import wraps
|
8 | 6 | from http import client
|
@@ -535,25 +533,38 @@ def _form_response(
|
535 | 533 | headers: Optional[Mapping[str, str]],
|
536 | 534 | status: int,
|
537 | 535 | ) -> HTTPResponse:
|
538 |
| - dummy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
539 |
| - orig_response = http.client.HTTPResponse(sock=dummy_socket) |
540 | 536 | """
|
| 537 | + Function to generate `urllib3.response.HTTPResponse` object. |
| 538 | +
|
541 | 539 | The cookie handling functionality of the `requests` library relies on the response object
|
542 | 540 | having an original response object with the headers stored in the `msg` attribute.
|
543 | 541 | Instead of supplying a file-like object of type `HTTPMessage` for the headers, we provide
|
544 | 542 | the headers directly. This approach eliminates the need to parse the headers into a file-like
|
545 | 543 | object and then rely on the library to unparse it back. These additional conversions can
|
546 | 544 | introduce potential errors.
|
547 |
| - Therefore, we intentionally ignore type checking for this assignment. |
548 | 545 | """
|
549 |
| - orig_response.msg = headers # type: ignore[assignment] |
550 | 546 |
|
| 547 | + data = BytesIO() |
| 548 | + data.close() |
| 549 | + |
| 550 | + """ |
| 551 | + The type `urllib3.response.HTTPResponse` is incorrect; we should |
| 552 | + use `http.client.HTTPResponse` instead. However, changing this requires opening |
| 553 | + a real socket to imitate the object. This may not be desired, as some users may |
| 554 | + want to completely restrict network access in their tests. |
| 555 | + See https://github.com/getsentry/responses/issues/691 |
| 556 | + """ |
| 557 | + orig_response = HTTPResponse( |
| 558 | + body=data, # required to avoid "ValueError: Unable to determine whether fp is closed." |
| 559 | + msg=headers, # type: ignore[arg-type] |
| 560 | + preload_content=False, |
| 561 | + ) |
551 | 562 | return HTTPResponse(
|
552 | 563 | status=status,
|
553 | 564 | reason=client.responses.get(status, None),
|
554 | 565 | body=body,
|
555 | 566 | headers=headers,
|
556 |
| - original_response=orig_response, |
| 567 | + original_response=orig_response, # type: ignore[arg-type] # See comment above |
557 | 568 | preload_content=False,
|
558 | 569 | )
|
559 | 570 |
|
|
0 commit comments