Flake8-comprehensions (C4) --fix go brrr

This commit is contained in:
L. Kärkkäinen
2023-10-25 02:28:52 +01:00
parent 9adb6e8ec0
commit 65ba1942cc
81 changed files with 696 additions and 793 deletions

View File

@@ -14,7 +14,7 @@ class AsyncMock(Mock):
def __call__(self, *args, **kwargs):
self.call_count += 1
parent = super(AsyncMock, self)
parent = super()
async def dummy():
self.await_count += 1

View File

@@ -24,7 +24,7 @@ class TestSanicRouteResolution:
router, simple_routes = sanic_router(route_details=simple_routes)
route_to_call = choice(simple_routes)
request = Request(
"/{}".format(route_to_call[-1]).encode(),
f"/{route_to_call[-1]}".encode(),
{"host": "localhost"},
"v1",
route_to_call[0],
@@ -58,9 +58,9 @@ class TestSanicRouteResolution:
template=route_to_call[-1]
)
print("{} -> {}".format(route_to_call[-1], url))
print(f"{route_to_call[-1]} -> {url}")
request = Request(
"/{}".format(url).encode(),
f"/{url}".encode(),
{"host": "localhost"},
"v1",
route_to_call[0],

View File

@@ -23,10 +23,10 @@ for n in range(6):
setup="from sanic.response import json",
number=100000,
)
print("Took {} seconds".format(time))
print(f"Took {time} seconds")
total_time += time
times += 1
print("Average: {}".format(total_time / times))
print(f"Average: {total_time / times}")
print("Running Old 100,000 times")
times = 0
@@ -37,7 +37,7 @@ for n in range(6):
setup="from sanic.response import json",
number=100000,
)
print("Took {} seconds".format(time))
print(f"Took {time} seconds")
total_time += time
times += 1
print("Average: {}".format(total_time / times))
print(f"Average: {total_time / times}")

View File

@@ -28,7 +28,7 @@ def test(request):
@app.route("/text/<name>/<butt:int>")
def rtext(request, name, butt):
return text("yeehaww {} {}".format(name, butt))
return text(f"yeehaww {name} {butt}")
@app.route("/exception")

View File

@@ -41,7 +41,7 @@ if __name__ == "__main__":
from wsgiref.simple_server import make_server
try:
print("Visit http://localhost:{}/".format(sys.argv[-1]))
print(f"Visit http://localhost:{sys.argv[-1]}/")
make_server("", int(sys.argv[-1]), main).serve_forever()
except KeyboardInterrupt:
pass

View File

@@ -51,7 +51,7 @@ def test_asyncio_server_no_start_serving(app: Sanic):
asyncio_srv_coro = app.create_server(
port=43123,
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
asyncio_server_kwargs={"start_serving": False},
)
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is False
@@ -63,7 +63,7 @@ def test_asyncio_server_start_serving(app: Sanic):
asyncio_srv_coro = app.create_server(
port=43124,
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
asyncio_server_kwargs={"start_serving": False},
)
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is False
@@ -96,7 +96,7 @@ def test_create_server_no_startup(app: Sanic):
asyncio_srv_coro = app.create_server(
port=43124,
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
asyncio_server_kwargs={"start_serving": False},
)
srv = loop.run_until_complete(asyncio_srv_coro)
message = (
@@ -488,7 +488,7 @@ def test_uvloop_cannot_never_called_with_create_server(caplog, monkeypatch):
for app in apps:
srv_coro = app.create_server(
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
asyncio_server_kwargs={"start_serving": False},
)
loop.run_until_complete(srv_coro)
@@ -526,7 +526,7 @@ def test_multiple_uvloop_configs_display_warning(caplog):
for app in (default_uvloop, no_uvloop, yes_uvloop):
srv_coro = app.create_server(
return_asyncio_server=True,
asyncio_server_kwargs=dict(start_serving=False),
asyncio_server_kwargs={"start_serving": False},
)
srv = loop.run_until_complete(srv_coro)
loop.run_until_complete(srv.startup())

View File

@@ -483,7 +483,7 @@ def test_bp_exception_handler_applied(app: Sanic):
@handled.exception(Error)
def handle_error(req, e):
return text("handled {}".format(e))
return text(f"handled {e}")
@handled.route("/ok")
def ok(request):
@@ -513,7 +513,7 @@ def test_bp_exception_handler_not_applied(app: Sanic):
@handled.exception(Error)
def handle_error(req, e):
return text("handled {}".format(e))
return text(f"handled {e}")
@nothandled.route("/notok")
def notok(request):

View File

@@ -545,9 +545,9 @@ def test_guess_mime_logging(
with caplog.at_level(logging.DEBUG, logger="sanic.root"):
guess_mime(fake_request, fallback)
(logmsg,) = [
(logmsg,) = (
r.message for r in caplog.records if r.funcName == "guess_mime"
]
)
assert logmsg == expected

View File

@@ -308,7 +308,7 @@ def test_contextual_exception_context(debug):
assert dl == {"foo": "bar"}
_, response = app.test_client.post("/coffee/text", debug=debug)
lines = list(map(lambda x: x.decode(), response.body.split(b"\n")))
lines = [x.decode() for x in response.body.split(b"\n")]
idx = lines.index("Context") + 1
assert response.status == 418
assert lines[2] == "Sorry, I cannot brew coffee"
@@ -358,7 +358,7 @@ def test_contextual_exception_extra(debug):
assert not dl
_, response = app.test_client.post("/coffee/text", debug=debug)
lines = list(map(lambda x: x.decode(), response.body.split(b"\n")))
lines = [x.decode() for x in response.body.split(b"\n")]
assert response.status == 418
assert lines[2] == "Found bar"
if debug:

View File

@@ -402,7 +402,7 @@ def test_accept_misc():
assert m.header.type == "*"
assert m.header.subtype == "plain"
assert m.header.q == 1.0
assert m.header.params == dict(param="123")
assert m.header.params == {"param": "123"}
# Matches object against another Matched object (by mime and header)
assert m == a.match("text/*")
# Against unsupported type falls back to object id matching

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio

View File

@@ -129,10 +129,10 @@ def scanner(proc, trigger="complete"):
yield line
argv = dict(
script=[sys.executable, "reloader.py"],
module=[sys.executable, "-m", "reloader"],
sanic=[
argv = {
"script": [sys.executable, "reloader.py"],
"module": [sys.executable, "-m", "reloader"],
"sanic": [
sys.executable,
"-m",
"sanic",
@@ -141,14 +141,14 @@ argv = dict(
"--auto-reload",
"reloader.app",
],
)
}
@pytest.mark.parametrize(
"runargs, mode",
[
(dict(port=42202, auto_reload=True), "script"),
(dict(port=42203, auto_reload=True), "module"),
({"port": 42202, "auto_reload": True}, "script"),
({"port": 42203, "auto_reload": True}, "module"),
({}, "sanic"),
],
)
@@ -180,8 +180,8 @@ async def test_reloader_live(runargs, mode):
@pytest.mark.parametrize(
"runargs, mode",
[
(dict(port=42302, auto_reload=True), "script"),
(dict(port=42303, auto_reload=True), "module"),
({"port": 42302, "auto_reload": True}, "script"),
({"port": 42303, "auto_reload": True}, "module"),
({}, "sanic"),
],
)

View File

@@ -573,7 +573,7 @@ def test_streaming_echo():
async def client(app, reader, writer):
# Unfortunately httpx does not support 2-way streaming, so do it by hand.
host = "host: localhost:8000\r\n".encode()
host = b"host: localhost:8000\r\n"
writer.write(
b"POST /echo HTTP/1.1\r\n" + host + b"content-length: 2\r\n"
b"content-type: text/plain; charset=utf-8\r\n"

View File

@@ -2260,7 +2260,7 @@ def test_conflicting_body_methods_overload(app: Sanic):
assert response.json == {
"name": "test_conflicting_body_methods_overload.delete",
"foo": "test",
"body": str("".encode()),
"body": str(b""),
}

View File

@@ -117,7 +117,7 @@ def test_custom_dumps_and_kwargs(json_app: Sanic):
return json_response(JSON_BODY, dumps=custom_dumps, prry="platypus")
_, resp = json_app.test_client.get("/json-custom")
assert resp.body == "custom".encode()
assert resp.body == b"custom"
custom_dumps.assert_called_once_with(JSON_BODY, prry="platypus")
@@ -135,7 +135,7 @@ def test_override_dumps_and_kwargs(json_app: Sanic):
_, resp = json_app.test_client.get("/json-custom")
assert resp.body == "custom2".encode()
assert resp.body == b"custom2"
custom_dumps_1.assert_called_once_with(JSON_BODY, prry="platypus")
custom_dumps_2.assert_called_once_with(JSON_BODY, platypus="prry")

View File

@@ -1124,8 +1124,8 @@ def test_route_invalid_host(app):
return text("pass")
assert str(excinfo.value) == (
"Expected either string or Iterable of " "host strings, not {!r}"
).format(host)
"Expected either string or Iterable of " f"host strings, not {host!r}"
)
def test_route_with_regex_group(app):

View File

@@ -324,7 +324,7 @@ def test_static_content_range_error(app, file_name, static_file_directory):
assert response.status == 416
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
assert response.headers["Content-Range"] == "bytes */%s" % (
assert response.headers["Content-Range"] == "bytes */{}".format(
len(get_file_content(static_file_directory, file_name)),
)

View File

@@ -14,24 +14,24 @@ from sanic.response import text
from sanic.views import HTTPMethodView
URL_FOR_ARGS1 = dict(arg1=["v1", "v2"])
URL_FOR_ARGS1 = {"arg1": ["v1", "v2"]}
URL_FOR_VALUE1 = "/myurl?arg1=v1&arg1=v2"
URL_FOR_ARGS2 = dict(arg1=["v1", "v2"], _anchor="anchor")
URL_FOR_ARGS2 = {"arg1": ["v1", "v2"], "_anchor": "anchor"}
URL_FOR_VALUE2 = "/myurl?arg1=v1&arg1=v2#anchor"
URL_FOR_ARGS3 = dict(
arg1="v1",
_anchor="anchor",
_scheme="http",
_server=f"{test_host}:{test_port}",
_external=True,
)
URL_FOR_ARGS3 = {
"arg1": "v1",
"_anchor": "anchor",
"_scheme": "http",
"_server": f"{test_host}:{test_port}",
"_external": True,
}
URL_FOR_VALUE3 = f"http://{test_host}:{test_port}/myurl?arg1=v1#anchor"
URL_FOR_ARGS4 = dict(
arg1="v1",
_anchor="anchor",
_external=True,
_server=f"http://{test_host}:{test_port}",
)
URL_FOR_ARGS4 = {
"arg1": "v1",
"_anchor": "anchor",
"_external": True,
"_server": f"http://{test_host}:{test_port}",
}
URL_FOR_VALUE4 = f"http://{test_host}:{test_port}/myurl?arg1=v1#anchor"

View File

@@ -465,7 +465,7 @@ def test_static_content_range_error(app, file_name, static_file_directory):
assert response.status == 416
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
assert response.headers["Content-Range"] == "bytes */%s" % (
assert response.headers["Content-Range"] == "bytes */{}".format(
len(get_file_content(static_file_directory, file_name)),
)
@@ -482,6 +482,6 @@ def test_static_content_range_error(app, file_name, static_file_directory):
assert response.status == 416
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
assert response.headers["Content-Range"] == "bytes */%s" % (
assert response.headers["Content-Range"] == "bytes */{}".format(
len(get_file_content(static_file_directory, file_name)),
)

View File

@@ -20,9 +20,8 @@ def run_check(path_location: str) -> str:
process = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
capture_output=True,
text=True,
)
output = process.stdout + process.stderr
return output

View File

@@ -23,12 +23,12 @@ def test_del_state():
def test_iter_state():
result = [item for item in gen_state(one=1, two=2)]
result = list(gen_state(one=1, two=2))
assert result == ["one", "two"]
def test_state_len():
result = [item for item in gen_state(one=1, two=2)]
result = list(gen_state(one=1, two=2))
assert len(result) == 2