Repository: getsentry/responses
Pull request #482 (2022-01-21 16:21:42)

minor cleanup
clean up after py2.7

beliaev-maksim: I see that cov dropped. Means we did not have a test for that line..

will add it

Patch:
diff --git a/CHANGES b/CHANGES
index 66c1659..8a4d3df 100644
--- a/CHANGES
+++ b/CHANGES
@@ -2,6 +2,7 @@
 ------
 
 * Expose `get_registry()` method of `RequestsMock` object. Replaces internal `_get_registry()`.
+* `query_param_matcher` can now accept dictionaries with `int` and `float` values.
 * Added support for `async/await` functions.
 
 0.18.0
diff --git a/responses/__init__.py b/responses/__init__.py
index 940b742..79dbc84 100644
--- a/responses/__init__.py
+++ b/responses/__init__.py
@@ -1,13 +1,11 @@
-from __future__ import absolute_import, print_function, division, unicode_literals
+from http import client
 
-import _io
 import inspect
-from http import client
 from http import cookies
 import json as json_module
 import logging
-import re
 from itertools import groupby
+from re import Pattern
 
 
 from collections import namedtuple
@@ -46,18 +44,14 @@ from urllib.parse import (
     quote,
 )
 
-from io import BytesIO as BufferIO
+from io import BytesIO
+from io import BufferedReader
 
 from unittest import mock as std_mock
 
-
-Pattern = re.Pattern
-
-UNSET = object()
-
 Call = namedtuple("Call", ["request", "response"])
-
 _real_send = HTTPAdapter.send
+_UNSET = object()
 
 logger = logging.getLogger("responses")
 
@@ -182,10 +176,10 @@ def _get_url_and_path(url):
 def _handle_body(body):
     if isinstance(body, str):
         body = body.encode("utf-8")
-    if isinstance(body, _io.BufferedReader):
+    if isinstance(body, BufferedReader):
         return body
 
-    data = BufferIO(body)
+    data = BytesIO(body)
 
     def is_closed():
         """
@@ -220,7 +214,6 @@ class BaseResponse(object):
     passthrough = False
     content_type = None
     headers = None
-
     stream = False
 
     def __init__(self, method, url, match_querystring=None, match=()):
@@ -328,7 +321,7 @@ class Response(BaseResponse):
         status=200,
         headers=None,
         stream=None,
-        content_type=UNSET,
+        content_type=_UNSET,
         auto_calculate_content_length=False,
         **kwargs
     ):
@@ -337,10 +330,10 @@ class Response(BaseResponse):
         if json is not None:
             assert not body
             body = json_module.dumps(json)
-            if content_type is UNSET:
+            if content_type is _UNSET:
                 content_type = "application/json"
 
-        if content_type is UNSET:
+        if content_type is _UNSET:
             if isinstance(body, str) and _has_unicode(body):
                 content_type = "text/plain; charset=utf-8"
             else:
@@ -359,7 +352,7 @@ class Response(BaseResponse):
         self.stream = stream
         self.content_type = content_type
         self.auto_calculate_content_length = auto_calculate_content_length
-        super(Response, self).__init__(method, url, **kwargs)
+        super().__init__(method, url, **kwargs)
 
     def get_response(self, request):
         if self.body and isinstance(self.body, Exception):
@@ -371,7 +364,7 @@ class Response(BaseResponse):
 
         if (
             self.auto_calculate_content_length
-            and isinstance(body, BufferIO)
+            and isinstance(body, BytesIO)
             and "Content-Length" not in headers
         ):
             content_length = len(body.getvalue())
@@ -411,7 +404,7 @@ class CallbackResponse(BaseResponse):
             )
         self.stream = stream
         self.content_type = content_type
-        super(CallbackResponse, self).__init__(method, url, **kwargs)
+        super().__init__(method, url, **kwargs)
 
     def get_response(self, request):
         headers = self.get_headers()
@@ -580,6 +573,7 @@ class RequestsMock(object):
 
         Regex can be used like:
 
+        >>> import re
         >>> responses.add_passthru(re.compile('https://example.com/\\w+'))
         """
         if not isinstance(prefix, Pattern) and _has_unicode(prefix):
@@ -614,7 +608,6 @@ class RequestsMock(object):
         >>> responses.replace(responses.GET, 'http://example.org', json={'data': 2})
         """
         if isinstance(method_or_response, BaseResponse):
-            url = method_or_response.url
             response = method_or_response
         else:
             response = Response(method=method_or_response, url=url, body=body, **kwargs)
@@ -645,8 +638,6 @@ class RequestsMock(object):
         content_type="text/plain",
         match=(),
     ):
-        # ensure the url has a default path set if the url is a string
-        # url = _ensure_url_default_path(url, match_querystring)
 
         self._registry.add(
             CallbackResponse(
@@ -680,8 +671,8 @@ class RequestsMock(object):
         if func is not None:
             return get_wrapped(func, self)
 
-        def deco_activate(func):
-            return get_wrapped(func, self, registry)
+        def deco_activate(function):
+            return get_wrapped(function, self, registry)
 
         return deco_activate
 
diff --git a/responses/__init__.pyi b/responses/__init__.pyi
index 93e432d..69c1e7c 100644
--- a/responses/__init__.pyi
+++ b/responses/__init__.pyi
@@ -168,6 +168,7 @@ class RequestsMock:
     passthru_prefixes: Tuple[Union[str, Pattern[str]], ...] = ...
     target: Any = ...
     _matches: List[Any]
+    _registry: Any
     def __init__(
         self,
         assert_all_requests_are_fired: bool = ...,
diff --git a/responses/matchers.py b/responses/matchers.py
index 893edc1..1fee6a5 100644
--- a/responses/matchers.py
+++ b/responses/matchers.py
@@ -132,6 +132,10 @@ def query_param_matcher(params):
     :return: (func) matcher
     """
 
+    for k, v in params.items():
+        if isinstance(v, (int, float)):
+            params[k] = str(v)
+
     def match(request):
         reason = ""
         request_params = request.params
diff --git a/responses/matchers.pyi b/responses/matchers.pyi
index 188de2e..408eb55 100644
--- a/responses/matchers.pyi
+++ b/responses/matchers.pyi
@@ -19,7 +19,7 @@ def urlencoded_params_matcher(
 ) -> Callable[..., Any]: ...
 
 def query_param_matcher(
-    params: Optional[Dict[str, str]]
+    params: Optional[Dict[str, Any]]
 ) -> Callable[..., Any]: ...
 
 def query_string_matcher(


Test patch:
diff --git a/responses/test_matchers.py b/responses/test_matchers.py
index d061d97..937e8c0 100644
--- a/responses/test_matchers.py
+++ b/responses/test_matchers.py
@@ -87,6 +87,23 @@ def test_request_matches_post_params():
     assert_reset()
 
 
+def test_query_params_numbers():
+    @responses.activate
+    def run():
+        expected_query_params = {"float": 5.0, "int": 2}
+        responses.add(
+            responses.GET,
+            "https://example.com/",
+            match=[
+                matchers.query_param_matcher(expected_query_params),
+            ],
+        )
+        requests.get("https://example.com", params=expected_query_params)
+
+    run()
+    assert_reset()
+
+
 def test_request_matches_empty_body():
     def run():
         with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps: