Skip to content

Commit

Permalink
modernize source with pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile-sentry committed Aug 24, 2023
1 parent 771477f commit 2f81bd5
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 30 deletions.
7 changes: 6 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ repos:
hooks:
- id: flake8
args: [ '--max-line-length', '100', '--max-doc-length', '120' ]
- repo: https://github.com/asottile/blacken-docs
- repo: https://github.com/asottile/pyupgrade
rev: v3.10.1
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.14.0
hooks:
- id: blacken-docs
Expand Down
12 changes: 5 additions & 7 deletions responses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,6 @@ class FalseBool:
def __bool__(self) -> bool:
return False

__nonzero__ = __bool__


def urlencoded_params_matcher(params: Optional[Dict[str, str]]) -> Callable[..., Any]:
warn(
Expand Down Expand Up @@ -369,7 +367,7 @@ def is_closed() -> bool:
return data


class BaseResponse(object):
class BaseResponse:
passthrough: bool = False
content_type: Optional[str] = None
headers: Optional[Mapping[str, str]] = None
Expand Down Expand Up @@ -662,7 +660,7 @@ def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, passthrough=True, **kwargs)


class RequestsMock(object):
class RequestsMock:
DELETE: Literal["DELETE"] = "DELETE"
GET: Literal["GET"] = "GET"
HEAD: Literal["HEAD"] = "HEAD"
Expand Down Expand Up @@ -792,7 +790,7 @@ def add(
def _parse_response_file(
self, file_path: "Union[str, bytes, os.PathLike[Any]]"
) -> "Dict[str, Any]":
with open(file_path, "r") as file:
with open(file_path) as file:
data = yaml.safe_load(file)
return data

Expand Down Expand Up @@ -1047,7 +1045,7 @@ def _on_request(
if self.passthru_prefixes:
error_msg += "Passthru prefixes:\n"
for p in self.passthru_prefixes:
error_msg += "- {}\n".format(p)
error_msg += f"- {p}\n"

response = ConnectionError(error_msg)
response.request = request
Expand Down Expand Up @@ -1156,7 +1154,7 @@ def stop(self, allow_assert: bool = True) -> None:
not_called = [m for m in self.registered() if m.call_count == 0]
if not_called:
raise AssertionError(
"Not all requests have been executed {0!r}".format(
"Not all requests have been executed {!r}".format(
[(match.method, match.url) for match in not_called]
)
)
Expand Down
2 changes: 1 addition & 1 deletion responses/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def list_to_str(input_list: List[str]) -> str:
elif isinstance(val, list):
val = list_to_str(input_list=val)

items_list.append("{}: {}".format(key, val))
items_list.append(f"{key}: {val}")

key_val_str = "{{{}}}".format(", ".join(items_list))
return key_val_str
Expand Down
6 changes: 2 additions & 4 deletions responses/registries.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from responses import BaseResponse


class FirstMatchRegistry(object):
class FirstMatchRegistry:
def __init__(self) -> None:
self._responses: List["BaseResponse"] = []

Expand Down Expand Up @@ -67,9 +67,7 @@ def replace(self, response: "BaseResponse") -> "BaseResponse":
try:
index = self.registered.index(response)
except ValueError:
raise ValueError(
"Response is not registered for URL {}".format(response.url)
)
raise ValueError(f"Response is not registered for URL {response.url}")
self.registered[index] = response
return response

Expand Down
2 changes: 1 addition & 1 deletion responses/tests/test_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def run():

run()

with open(self.out_file, "r") as file:
with open(self.out_file) as file:
data = yaml.safe_load(file)

assert data == get_data(httpserver.host, httpserver.port)
Expand Down
30 changes: 14 additions & 16 deletions responses/tests/test_responses.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

import inspect
import os
import re
Expand Down Expand Up @@ -912,7 +910,7 @@ def fruit_basket(my_fruit):


@pytest.mark.usefixtures("my_fruit", "fruit_basket")
class TestFixtures(object):
class TestFixtures:
"""
Test that pytest fixtures work well with 'activate' decorator
"""
Expand Down Expand Up @@ -960,7 +958,7 @@ def test_function(a, b=None):


def test_activate_doesnt_change_signature_for_method():
class TestCase(object):
class TestCase:
def test_function(self, a, b=None):
return self, a, b

Expand Down Expand Up @@ -1100,10 +1098,10 @@ def test_response_filebody():
def run():
current_file = os.path.abspath(__file__)
with responses.RequestsMock() as m:
with open(current_file, "r", encoding="utf-8") as out:
with open(current_file, encoding="utf-8") as out:
m.add(responses.GET, "http://example.com", body=out.read(), stream=True)
resp = requests.get("http://example.com", stream=True)
with open(current_file, "r", encoding="utf-8") as out:
with open(current_file, encoding="utf-8") as out:
assert resp.text == out.read()

run()
Expand Down Expand Up @@ -1195,7 +1193,7 @@ def test_some_second_function():
def test_allow_redirects_samehost():
redirecting_url = "http://example.com"
final_url_path = "/1"
final_url = "{0}{1}".format(redirecting_url, final_url_path)
final_url = f"{redirecting_url}{final_url_path}"
url_re = re.compile(r"^http://example.com(/)?(\d+)?$")

def request_callback(request):
Expand All @@ -1209,7 +1207,7 @@ def request_callback(request):
n = 1
else:
n = 0
redirect_headers = {"location": "/{0!s}".format(n)}
redirect_headers = {"location": f"/{n!s}"}
return 301, redirect_headers, None

def run():
Expand Down Expand Up @@ -1696,12 +1694,12 @@ def test_passthrough_response(self, httpserver):
@responses.activate
def run():
responses.add(PassthroughResponse(responses.GET, url))
responses.add(responses.GET, "{}/one".format(url), body="one")
responses.add(responses.GET, f"{url}/one", body="one")
responses.add(responses.GET, "http://example.com/two", body="two")

resp = requests.get("http://example.com/two")
assert_response(resp, "two")
resp = requests.get("{}/one".format(url))
resp = requests.get(f"{url}/one")
assert_response(resp, "one")
resp = requests.get(url)
assert_response(resp, "OK")
Expand Down Expand Up @@ -1762,12 +1760,12 @@ def test_passthru(self, httpserver):
@responses.activate
def run():
responses.add_passthru(url)
responses.add(responses.GET, "{}/one".format(url), body="one")
responses.add(responses.GET, f"{url}/one", body="one")
responses.add(responses.GET, "http://example.com/two", body="two")

resp = requests.get("http://example.com/two")
assert_response(resp, "two")
resp = requests.get("{}/one".format(url))
resp = requests.get(f"{url}/one")
assert_response(resp, "one")
resp = requests.get(url)
assert_response(resp, "OK")
Expand All @@ -1784,7 +1782,7 @@ def test_passthru_regex(self, httpserver):
@responses.activate
def run():
responses.add_passthru(re.compile(f"{url}/\\w+"))
responses.add(responses.GET, "{}/one".format(url), body="one")
responses.add(responses.GET, f"{url}/one", body="one")
responses.add(responses.GET, "http://example.com/two", body="two")

resp = requests.get("http://example.com/two")
Expand Down Expand Up @@ -1876,7 +1874,7 @@ def run():
params = {"hello": "world", "example": "params"}
responses.add(
method=responses.GET,
url="{0}?hello=world".format(url),
url=f"{url}?hello=world",
body="test",
match_querystring=False,
)
Expand Down Expand Up @@ -1923,7 +1921,7 @@ def run():

with pytest.raises(AssertionError) as excinfo:
responses.assert_call_count(url, 2)
assert "Expected URL '{0}' to be called 2 times. Called 0 times.".format(
assert "Expected URL '{}' to be called 2 times. Called 0 times.".format(
url
) in str(excinfo.value)

Expand All @@ -1936,7 +1934,7 @@ def run():
requests.get(url)
with pytest.raises(AssertionError) as excinfo:
responses.assert_call_count(url, 3)
assert "Expected URL '{0}' to be called 3 times. Called 2 times.".format(
assert "Expected URL '{}' to be called 3 times. Called 2 times.".format(
url
) in str(excinfo.value)

Expand Down

0 comments on commit 2f81bd5

Please sign in to comment.