Skip to content

Commit

Permalink
fix types (#684)
Browse files Browse the repository at this point in the history
* remove dependency on urllib3 vendored in requests since it is not maintained anymore. See python/typeshed#6893 (comment)
* new version of mypy does not require overloads for type checking
* [skip] remove pragma comment
  • Loading branch information
beliaev-maksim authored Oct 21, 2023
1 parent 30e49a4 commit 74466ec
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 52 deletions.
55 changes: 9 additions & 46 deletions responses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
from typing import Tuple
from typing import Type
from typing import Union
from typing import overload
from warnings import warn

import yaml
Expand All @@ -41,21 +40,6 @@
except ImportError: # pragma: no cover
from typing import Literal # type: ignore # pragma: no cover

try:
from requests.packages.urllib3.response import HTTPResponse
except ImportError: # pragma: no cover
from urllib3.response import HTTPResponse # pragma: no cover

try:
from requests.packages.urllib3.connection import HTTPHeaderDict
except ImportError: # pragma: no cover
from urllib3.response import HTTPHeaderDict

try:
from requests.packages.urllib3.util.url import parse_url
except ImportError: # pragma: no cover
from urllib3.util.url import parse_url # pragma: no cover

from io import BufferedReader
from io import BytesIO
from unittest import mock as std_mock
Expand All @@ -65,6 +49,10 @@
from urllib.parse import urlunparse
from urllib.parse import urlunsplit

from urllib3.response import HTTPHeaderDict
from urllib3.response import HTTPResponse
from urllib3.util.url import parse_url

if TYPE_CHECKING: # pragma: no cover
# import only for linter run
import os
Expand Down Expand Up @@ -251,14 +239,6 @@ def __iter__(self) -> Iterator[Call]:
def __len__(self) -> int:
return len(self._calls)

@overload
def __getitem__(self, idx: int) -> Call:
"""Overload when get a single item."""

@overload
def __getitem__(self, idx: slice) -> List[Call]:
"""Overload when a slice is requested."""

def __getitem__(self, idx: Union[int, slice]) -> Union[Call, List[Call]]:
return self._calls[idx]

Expand Down Expand Up @@ -527,22 +507,22 @@ def _form_response(
status: int,
) -> HTTPResponse:
# The requests library's cookie handling depends on the response object
# having an original response object with the headers as the `msg`, so
# we give it what it needs.
# having an original response object with the headers as the `msg` instead
# of `HTTPMessage`, so we give it what it needs.
data = BytesIO()
data.close()

orig_response = HTTPResponse(
body=data, # required to avoid "ValueError: Unable to determine whether fp is closed."
msg=headers,
msg=headers, # type: ignore[arg-type] # see comment above why we use headers
preload_content=False,
)
return HTTPResponse(
status=status,
reason=client.responses.get(status, None),
body=body,
headers=headers,
original_response=orig_response,
original_response=orig_response, # type: ignore[arg-type]
preload_content=False,
)

Expand Down Expand Up @@ -962,23 +942,6 @@ def __exit__(self, type: Any, value: Any, traceback: Any) -> bool:
self.reset()
return success

@overload
def activate(self, func: "_F" = ...) -> "_F":
"""Overload for scenario when 'responses.activate' is used."""

@overload
def activate(
self,
*,
registry: Type[Any] = ...,
assert_all_requests_are_fired: bool = ...,
) -> Callable[["_F"], "_F"]:
"""Overload for scenario when
'responses.activate(registry=, assert_all_requests_are_fired=True)' is used.
See https://github.com/getsentry/responses/pull/469 for more details
"""

def activate(
self,
func: Optional["_F"] = None,
Expand Down Expand Up @@ -1096,7 +1059,7 @@ def _on_request(

retries = retries or adapter.max_retries
# first validate that current request is eligible to be retried.
# See ``requests.packages.urllib3.util.retry.Retry`` documentation.
# See ``urllib3.util.retry.Retry`` documentation.
if retries.is_retry(
method=response.request.method, status_code=response.status_code # type: ignore[misc]
):
Expand Down
4 changes: 2 additions & 2 deletions responses/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from urllib.parse import urlparse

from requests import PreparedRequest
from requests.packages.urllib3.util.url import parse_url
from urllib3.util.url import parse_url


def _create_key_val_str(input_dict: Union[Dict[Any, Any], Any]) -> str:
Expand Down Expand Up @@ -256,7 +256,7 @@ def query_string_matcher(query: Optional[str]) -> Callable[..., Any]:

def match(request: PreparedRequest) -> Tuple[bool, str]:
reason = ""
data = parse_url(request.url)
data = parse_url(request.url or "")
request_query = data.query

request_qsl = sorted(parse_qsl(request_query)) if request_query else {}
Expand Down
6 changes: 2 additions & 4 deletions responses/tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1382,15 +1382,13 @@ def run():
# Type errors here and on 1250 are ignored because the stubs for requests
# are off https://github.com/python/typeshed/blob/f8501d33c737482a829c6db557a0be26895c5941
# /stubs/requests/requests/packages/__init__.pyi#L1
original_init = getattr(requests.packages.urllib3.HTTPResponse, "__init__") # type: ignore
original_init = getattr(urllib3.HTTPResponse, "__init__") # type: ignore

def patched_init(self, *args, **kwargs):
kwargs["enforce_content_length"] = True
original_init(self, *args, **kwargs)

monkeypatch.setattr(
requests.packages.urllib3.HTTPResponse, "__init__", patched_init # type: ignore
)
monkeypatch.setattr(urllib3.HTTPResponse, "__init__", patched_init) # type: ignore

run()
assert_reset()
Expand Down

0 comments on commit 74466ec

Please sign in to comment.