From 7c5d8fe7bb50420a59292bed7000bec0222ebcbd Mon Sep 17 00:00:00 2001 From: Andriy Ivaneyko Date: Thu, 7 Dec 2023 22:43:30 -0500 Subject: [PATCH] Introduce ruff execution on the tests folder #2871 --- Makefile | 5 +- tests/conftest.py | 12 ++-- tests/performance/sanic/http_response.py | 2 - tests/performance/sanic/varied_server.py | 19 +++-- tests/test_asgi.py | 3 +- tests/test_blueprint_copy.py | 12 ++-- tests/test_blueprint_group.py | 2 +- tests/test_cancellederror.py | 4 -- tests/test_cookies.py | 2 +- tests/test_errorpages.py | 3 +- tests/test_exceptions_handler.py | 4 +- tests/test_ext_integration.py | 28 ++++---- tests/test_headers.py | 4 +- tests/test_multiprocessing.py | 1 - tests/test_reloader.py | 3 +- tests/test_request_data.py | 3 +- tests/test_request_stream.py | 10 +-- tests/test_requests.py | 76 +++++++++++++------- tests/test_response.py | 14 ++-- tests/test_response_timeout.py | 4 +- tests/test_routes.py | 16 ++--- tests/test_signals.py | 21 +++--- tests/test_static.py | 46 ++++++------ tests/test_tls.py | 3 +- tests/test_url_building.py | 11 +-- tests/test_ws_handlers.py | 24 +++++-- tests/typing/samples/app_custom_config.py | 1 - tests/typing/samples/app_custom_ctx.py | 1 - tests/typing/samples/app_default.py | 1 - tests/typing/samples/app_fully_custom.py | 1 - tests/typing/samples/request_custom_ctx.py | 3 +- tests/typing/samples/request_custom_sanic.py | 3 +- tests/typing/samples/request_fully_custom.py | 4 +- tests/typing/test_typing.py | 1 - tests/worker/test_runner.py | 6 +- 35 files changed, 198 insertions(+), 155 deletions(-) diff --git a/Makefile b/Makefile index f27e956d53..3913155c4c 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,4 @@ +RUFF_FORMATTED_FOLDERS = sanic examples scripts tests .DEFAULT: help .PHONY: help @@ -53,11 +54,11 @@ docker-test: clean .PHONY: fix fix: - ruff check sanic examples scripts --fix + ruff check ${RUFF_FORMATTED_FOLDERS} --fix .PHONY: format format: - ruff format sanic examples scripts + ruff format ${RUFF_FORMATTED_FOLDERS} .PHONY: pretty pretty: fix format diff --git a/tests/conftest.py b/tests/conftest.py index 0e94a0d209..a1b5df7064 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -214,12 +214,12 @@ def ext_instance(): @pytest.fixture(autouse=True) # type: ignore -def sanic_ext(ext_instance): # noqa - sanic_ext = MagicMock(__version__="1.2.3") - sanic_ext.Extend = MagicMock() - sanic_ext.Extend.return_value = ext_instance - sys.modules["sanic_ext"] = sanic_ext - yield sanic_ext +def mock_sanic_ext(ext_instance): # noqa + mock_sanic_ext = MagicMock(__version__="1.2.3") + mock_sanic_ext.Extend = MagicMock() + mock_sanic_ext.Extend.return_value = ext_instance + sys.modules["sanic_ext"] = mock_sanic_ext + yield mock_sanic_ext with suppress(KeyError): del sys.modules["sanic_ext"] diff --git a/tests/performance/sanic/http_response.py b/tests/performance/sanic/http_response.py index 52596e5e18..72525cb924 100644 --- a/tests/performance/sanic/http_response.py +++ b/tests/performance/sanic/http_response.py @@ -3,8 +3,6 @@ import sys import timeit -import asyncpg - from sanic.response import json diff --git a/tests/performance/sanic/varied_server.py b/tests/performance/sanic/varied_server.py index 9b3f16da74..197ebbbb55 100644 --- a/tests/performance/sanic/varied_server.py +++ b/tests/performance/sanic/varied_server.py @@ -22,7 +22,7 @@ async def test(request): @app.route("/sync", methods=["GET", "POST"]) -def test(request): +def test_json_response(request): return json({"test": True}) @@ -37,7 +37,7 @@ def exception(request): @app.route("/exception/async") -async def test(request): +async def test_server_error(request): raise ServerError("asunk") @@ -67,9 +67,16 @@ def query_string(request): # sanic.conn = [] # sanic.redis = [] # for x in range(10): -# sanic.conn.append(await asyncpg.connect(user='postgres', password='zomgdev', database='postgres', host='192.168.99.100')) +# sanic.conn.append(await asyncpg.connect( +# user='postgres', +# password='zomgdev', +# database='postgres', +# host='192.168.99.100' +# )) # for n in range(30): -# connection = await asyncio_redis.Connection.create(host='192.168.99.100', port=6379) +# connection = await asyncio_redis.Connection.create( +# host='192.168.99.100', port=6379 +# ) # sanic.redis.append(connection) @@ -90,7 +97,9 @@ def query_string(request): # try: # values = await app.redis[r].get('my_key') # except asyncio_redis.exceptions.ConnectionLostError: -# app.redis[r] = await asyncio_redis.Connection.create(host='127.0.0.1', port=6379) +# app.redis[r] = await asyncio_redis.Connection.create( +# host='127.0.0.1', port=6379 +# ) # values = await app.redis[r].get('my_key') # r += 1 diff --git a/tests/test_asgi.py b/tests/test_asgi.py index 8fce84af3c..f5de8fdcb2 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -1,4 +1,3 @@ -import asyncio import logging from collections import deque, namedtuple @@ -12,7 +11,7 @@ from sanic import Sanic from sanic.application.state import Mode -from sanic.asgi import ASGIApp, Lifespan, MockTransport +from sanic.asgi import Lifespan, MockTransport from sanic.exceptions import BadRequest, Forbidden, ServiceUnavailable from sanic.request import Request from sanic.response import json, text diff --git a/tests/test_blueprint_copy.py b/tests/test_blueprint_copy.py index 5dd742eaec..eed5d719b5 100644 --- a/tests/test_blueprint_copy.py +++ b/tests/test_blueprint_copy.py @@ -84,7 +84,7 @@ def test_bp_copy_without_route_overwriting(app: Sanic): bpv1 = Blueprint("bp_v1", version=1, url_prefix="my_api") @bpv1.route("/") - async def handler(request: Request): + async def handler_v1(request: Request): return text("v1") app.blueprint(bpv1) @@ -100,7 +100,7 @@ async def handler(request: Request): with pytest.raises(RouteExists, match="Route already registered*"): @bpv2.route("/") - async def handler(request: Request): + async def handler_v2(request: Request): return text("v2") app.blueprint(bpv2) @@ -108,7 +108,7 @@ async def handler(request: Request): with pytest.raises(RouteExists, match="Route already registered*"): @bpv3.route("/") - async def handler(request: Request): + async def handler_v3(request: Request): return text("v3") app.blueprint(bpv3) @@ -118,7 +118,7 @@ def test_bp_copy_with_route_overwriting(app: Sanic): bpv1 = Blueprint("bp_v1", version=1, url_prefix="my_api") @bpv1.route("/") - async def handler(request: Request): + async def handler_v1(request: Request): return text("v1") app.blueprint(bpv1) @@ -129,13 +129,13 @@ async def handler(request: Request): ) @bpv2.route("/") - async def handler(request: Request): + async def handler_v2(request: Request): return text("v2") app.blueprint(bpv2) @bpv3.route("/") - async def handler(request: Request): + async def handler_v3(request: Request): return text("v3") app.blueprint(bpv3) diff --git a/tests/test_blueprint_group.py b/tests/test_blueprint_group.py index 330d5d9a5d..f36d5ee932 100644 --- a/tests/test_blueprint_group.py +++ b/tests/test_blueprint_group.py @@ -22,7 +22,7 @@ def test_bp_group_indexing(app: Sanic): group = Blueprint.group(blueprint_1, blueprint_2) assert group[0] == blueprint_1 - with raises(expected_exception=IndexError) as e: + with raises(expected_exception=IndexError): _ = group[3] diff --git a/tests/test_cancellederror.py b/tests/test_cancellederror.py index b61fd596b8..32d689a2b5 100644 --- a/tests/test_cancellederror.py +++ b/tests/test_cancellederror.py @@ -1,9 +1,5 @@ -import asyncio - from asyncio import CancelledError -import pytest - from sanic import Request, Sanic, json diff --git a/tests/test_cookies.py b/tests/test_cookies.py index 976ddabd57..29e1ec255a 100644 --- a/tests/test_cookies.py +++ b/tests/test_cookies.py @@ -25,7 +25,7 @@ def test_request_cookies(): assert c.getlist("abc") == ["xyz"] assert c.getlist("") == ["bare", "bare2"] assert ( - c.getlist("bare") == None + c.getlist("bare") is None ) # [] might be sensible but we got None for now diff --git a/tests/test_errorpages.py b/tests/test_errorpages.py index 00f459377b..28c04e4109 100644 --- a/tests/test_errorpages.py +++ b/tests/test_errorpages.py @@ -471,7 +471,8 @@ def test_config_fallback_bad_value(app): "", "html", "text/*,*/plain", - "The client accepts text/*, using 'html' from FALLBACK_ERROR_FORMAT", + "The client accepts text/*, using 'html' from" + " FALLBACK_ERROR_FORMAT", ), ( "", diff --git a/tests/test_exceptions_handler.py b/tests/test_exceptions_handler.py index 9c21128757..a5cb597ca8 100644 --- a/tests/test_exceptions_handler.py +++ b/tests/test_exceptions_handler.py @@ -7,7 +7,7 @@ import pytest from bs4 import BeautifulSoup -from pytest import LogCaptureFixture, MonkeyPatch, WarningsRecorder +from pytest import LogCaptureFixture, MonkeyPatch from sanic import Sanic, handlers from sanic.exceptions import BadRequest, Forbidden, NotFound, ServerError @@ -169,7 +169,7 @@ def import_error_handler(): pass try: - ModuleNotFoundError + ModuleNotFoundError # noqa: F823 except Exception: class ModuleNotFoundError(ImportError): diff --git a/tests/test_ext_integration.py b/tests/test_ext_integration.py index 228d7624e5..b3f3e49620 100644 --- a/tests/test_ext_integration.py +++ b/tests/test_ext_integration.py @@ -1,14 +1,12 @@ import sys -from unittest.mock import MagicMock - import pytest from sanic import Sanic try: - import sanic_ext + import sanic_ext # noqa: F401 SANIC_EXT_IN_ENV = True except ImportError: @@ -24,37 +22,37 @@ async def stop(*_): return app -def test_ext_is_loaded(stoppable_app: Sanic, sanic_ext): +def test_ext_is_loaded(stoppable_app: Sanic, mock_sanic_ext): stoppable_app.run(single_process=True) - sanic_ext.Extend.assert_called_once_with(stoppable_app) + mock_sanic_ext.Extend.assert_called_once_with(stoppable_app) -def test_ext_is_not_loaded(stoppable_app: Sanic, sanic_ext): +def test_ext_is_not_loaded(stoppable_app: Sanic, mock_sanic_ext): stoppable_app.config.AUTO_EXTEND = False stoppable_app.run(single_process=True) - sanic_ext.Extend.assert_not_called() + mock_sanic_ext.Extend.assert_not_called() -def test_extend_with_args(stoppable_app: Sanic, sanic_ext): +def test_extend_with_args(stoppable_app: Sanic, mock_sanic_ext): stoppable_app.extend(built_in_extensions=False) stoppable_app.run(single_process=True) - sanic_ext.Extend.assert_called_once_with( + mock_sanic_ext.Extend.assert_called_once_with( stoppable_app, built_in_extensions=False, config=None, extensions=None ) -def test_access_object_sets_up_extension(app: Sanic, sanic_ext): +def test_access_object_sets_up_extension(app: Sanic, mock_sanic_ext): app.ext - sanic_ext.Extend.assert_called_once_with(app) + mock_sanic_ext.Extend.assert_called_once_with(app) -def test_extend_cannot_be_called_multiple_times(app: Sanic, sanic_ext): +def test_extend_cannot_be_called_multiple_times(app: Sanic, mock_sanic_ext): app.extend() message = "Cannot extend Sanic after Sanic Extensions has been setup." with pytest.raises(RuntimeError, match=message): app.extend() - sanic_ext.Extend.assert_called_once_with( + mock_sanic_ext.Extend.assert_called_once_with( app, extensions=None, built_in_extensions=True, config=None ) @@ -71,7 +69,9 @@ def test_fail_if_not_loaded(app: Sanic): app.extend(built_in_extensions=False) -def test_can_access_app_ext_while_running(app: Sanic, sanic_ext, ext_instance): +def test_can_access_app_ext_while_running( + app: Sanic, mock_sanic_ext, ext_instance +): class IceCream: flavor: str diff --git a/tests/test_headers.py b/tests/test_headers.py index 3c07a98f53..ee3404c351 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -59,7 +59,9 @@ def raised_ceiling(): 'form-data; name="foo%22;bar\\"; filename="😀"', ("form-data", {"name": 'foo";bar\\', "filename": "😀"}), # cgi: ('form-data', {'name': 'foo%22;bar"; filename="😀'}) - # werkzeug (pre 2.3.0): ('form-data', {'name': 'foo%22;bar"; filename='}) + # werkzeug (pre 2.3.0): ( + # 'form-data', {'name': 'foo%22;bar"; filename='} + # ) ), ], ) diff --git a/tests/test_multiprocessing.py b/tests/test_multiprocessing.py index 6e5569d1a0..98e1907375 100644 --- a/tests/test_multiprocessing.py +++ b/tests/test_multiprocessing.py @@ -14,7 +14,6 @@ from sanic import Blueprint, text from sanic.compat import use_context from sanic.log import logger -from sanic.server.socket import configure_socket @pytest.mark.skipif( diff --git a/tests/test_reloader.py b/tests/test_reloader.py index ad8c566535..8df46f6455 100644 --- a/tests/test_reloader.py +++ b/tests/test_reloader.py @@ -12,7 +12,8 @@ import pytest -# We need to interrupt the autoreloader without killing it, so that the server gets terminated +# We need to interrupt the autoreloader without killing it, +# so that the server gets terminated # https://stefan.sofa-rockers.org/2013/08/15/handling-sub-process-hierarchies-python-linux-os-x/ try: diff --git a/tests/test_request_data.py b/tests/test_request_data.py index 51f2b230ca..cecf7f3439 100644 --- a/tests/test_request_data.py +++ b/tests/test_request_data.py @@ -59,7 +59,8 @@ def modify(request, response): "has_missing": False, "invalid": "'types.SimpleNamespace' object has no attribute 'missing'", "response_mw_valid": "sanic", - "response_mw_invalid": "'types.SimpleNamespace' object has no attribute 'missing'", + "response_mw_invalid": "'types.SimpleNamespace' object has no" + " attribute 'missing'", } diff --git a/tests/test_request_stream.py b/tests/test_request_stream.py index 1513f87876..a74ef05016 100644 --- a/tests/test_request_stream.py +++ b/tests/test_request_stream.py @@ -572,8 +572,8 @@ async def client_task(app, loop): app.stop() async def client(app, reader, writer): - # Unfortunately httpx does not support 2-way streaming, so do it by hand. - host = f"host: localhost:8000\r\n".encode() + # httpx doesn't support 2-way streaming,so do it by hand. + host = "host: localhost:8000\r\n".encode() 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" @@ -581,7 +581,7 @@ async def client(app, reader, writer): ) # Read response res = b"" - while not b"\r\n\r\n" in res: + while b"\r\n\r\n" not in res: res += await reader.read(4096) assert res.startswith(b"HTTP/1.1 200 OK\r\n") assert res.endswith(b"\r\n\r\n") @@ -589,7 +589,7 @@ async def client(app, reader, writer): async def read_chunk(): nonlocal buffer - while not b"\r\n" in buffer: + while b"\r\n" not in buffer: data = await reader.read(4096) assert data buffer += data @@ -618,6 +618,6 @@ async def read_chunk(): assert res == b"-" res = await read_chunk() - assert res == None + assert res is None app.run(access_log=False, single_process=True) diff --git a/tests/test_requests.py b/tests/test_requests.py index 6719025bc2..f0ec755f33 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -501,7 +501,8 @@ async def handler(request): headers = { "Forwarded": ( 'for=1.1.1.1, for=injected;host="' - ', for="[::2]";proto=https;host=me.tld;path="/app/";secret=mySecret' + ', for="[::2]";proto=https;host=me.tld;' + 'path="/app/";secret=mySecret' ",for=broken;;secret=b0rked" ", for=127.0.0.3;scheme=http;port=1234" ), @@ -616,7 +617,8 @@ async def handler(request): headers = { "Forwarded": ( 'for=1.1.1.1, for=injected;host="' - ', for="[::2]";proto=https;host=me.tld;path="/app/";secret=mySecret' + ', for="[::2]";proto=https;host=me.tld;' + 'path="/app/";secret=mySecret' ",for=broken;;secret=b0rked" ", for=127.0.0.3;scheme=http;port=1234" ), @@ -1250,7 +1252,8 @@ async def get(request): [ ( "------sanic\r\n" - 'Content-Disposition: form-data; filename="filename"; name="test"\r\n' + 'Content-Disposition: form-data; filename="filename"' + '; name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1258,7 +1261,8 @@ async def get(request): ), ( "------sanic\r\n" - 'content-disposition: form-data; filename="filename"; name="test"\r\n' + 'content-disposition: form-data; filename="filename"' + '; name="test"\r\n' "\r\n" 'content-type: application/json; {"field": "value"}\r\n' "------sanic--\r\n", @@ -1282,7 +1286,8 @@ async def get(request): ), ( "------sanic\r\n" - 'Content-Disposition: form-data; filename*="utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' + 'Content-Disposition: form-data; filename*=' + '"utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1290,7 +1295,8 @@ async def get(request): ), ( "------sanic\r\n" - 'content-disposition: form-data; filename*="utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' + 'content-disposition: form-data; filename*=' + '"utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' "\r\n" 'content-type: application/json; {"field": "value"}\r\n' "------sanic--\r\n", @@ -1299,7 +1305,8 @@ async def get(request): # Umlaut using NFC normalization (Windows, Linux, Android) ( "------sanic\r\n" - 'content-disposition: form-data; filename*="utf-8\'\'filename_%C3%A4_test"; name="test"\r\n' + 'content-disposition: form-data; filename*=' + '"utf-8\'\'filename_%C3%A4_test"; name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1308,7 +1315,8 @@ async def get(request): # Umlaut using NFD normalization (MacOS client) ( "------sanic\r\n" - 'content-disposition: form-data; filename*="utf-8\'\'filename_a%CC%88_test"; name="test"\r\n' + 'content-disposition: form-data; filename*=' + '"utf-8\'\'filename_a%CC%88_test"; name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1332,7 +1340,8 @@ async def post(request): [ ( "------sanic\r\n" - 'Content-Disposition: form-data; filename="filename"; name="test"\r\n' + 'Content-Disposition: form-data; filename="filename";' + ' name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1340,7 +1349,8 @@ async def post(request): ), ( "------sanic\r\n" - 'content-disposition: form-data; filename="filename"; name="test"\r\n' + 'content-disposition: form-data; filename="filename";' + ' name="test"\r\n' "\r\n" 'content-type: application/json; {"field": "value"}\r\n' "------sanic--\r\n", @@ -1364,7 +1374,8 @@ async def post(request): ), ( "------sanic\r\n" - 'Content-Disposition: form-data; filename*="utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' + 'Content-Disposition: form-data; filename*=' + '"utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' "\r\n" "OK\r\n" "------sanic--\r\n", @@ -1372,7 +1383,8 @@ async def post(request): ), ( "------sanic\r\n" - 'content-disposition: form-data; filename*="utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' + 'content-disposition: form-data; filename*=' + '"utf-8\'\'filename_%C2%A0_test"; name="test"\r\n' "\r\n" 'content-type: application/json; {"field": "value"}\r\n' "------sanic--\r\n", @@ -1399,7 +1411,8 @@ async def post(request): payload = ( "------sanic\r\n" - 'Content-Disposition: form-data; name="file"; filename="test.json"\r\n' + 'Content-Disposition: form-data; name="file";' + ' filename="test.json"\r\n' "Content-Type: application/json\r\n" "Content-Length: 0" "\r\n" @@ -1421,7 +1434,8 @@ async def post(request): payload = ( "------sanic\r\n" - 'Content-Disposition: form-data; name="file"; filename="test.json"\r\n' + 'Content-Disposition: form-data; name="file";' + ' filename="test.json"\r\n' "Content-Type: application/json\r\n" "Content-Length: 0" "\r\n" @@ -1483,7 +1497,8 @@ async def post(request): ) headers = { - "Content-Type": "multipart/form-data; boundary=e73ffaa8b1b2472b8ec848de833cb05b" + "Content-Type": "multipart/form-data;" + " boundary=e73ffaa8b1b2472b8ec848de833cb05b" } request, _ = app.test_client.post( @@ -1518,7 +1533,8 @@ async def post(request): ) headers = { - "Content-Type": "multipart/form-data; boundary=e73ffaa8b1b2472b8ec848de833cb05b" + "Content-Type": "multipart/form-data;" + " boundary=e73ffaa8b1b2472b8ec848de833cb05b" } request, _ = await app.asgi_client.post("/", data=payload, headers=headers) @@ -1534,9 +1550,11 @@ async def post(request): return text("OK") payload = ( - '------sanic\r\nContent-Disposition: form-data; name="file"; filename="test.json"' + '------sanic\r\nContent-Disposition: form-data; name="file";' + ' filename="test.json"' "\r\nContent-Type: application/json\r\n\r\n\r\n" - '------sanic\r\nContent-Disposition: form-data; name="file"; filename="some_file.pdf"\r\n' + '------sanic\r\nContent-Disposition: form-data; name="file";' + ' filename="some_file.pdf"\r\n' "Content-Type: application/pdf\r\n\r\n\r\n------sanic--" ) headers = {"content-type": "multipart/form-data; boundary=------sanic"} @@ -1554,9 +1572,11 @@ async def post(request): return text("OK") payload = ( - '------sanic\r\nContent-Disposition: form-data; name="file"; filename="test.json"' + '------sanic\r\nContent-Disposition: form-data; name="file";' + ' filename="test.json"' "\r\nContent-Type: application/json\r\n\r\n\r\n" - '------sanic\r\nContent-Disposition: form-data; name="file"; filename="some_file.pdf"\r\n' + '------sanic\r\nContent-Disposition: form-data; name="file";' + ' filename="some_file.pdf"\r\n' "Content-Type: application/pdf\r\n\r\n\r\n------sanic--" ) headers = {"content-type": "multipart/form-data; boundary=------sanic"} @@ -2011,11 +2031,11 @@ def handler(request): app.config.SERVER_NAME = "my-server" # This means default port assert app.url_for("handler", _external=True) == "http://my-server/foo" request, response = app.test_client.get("/foo") - assert request.url_for("handler") == f"http://my-server/foo" + assert request.url_for("handler") == "http://my-server/foo" app.config.SERVER_NAME = "https://my-server/path" request, response = app.test_client.get("/foo") - url = f"https://my-server/path/foo" + url = "https://my-server/path/foo" assert app.url_for("handler", _external=True) == url assert request.url_for("handler") == url @@ -2180,7 +2200,7 @@ async def handler(request): ) assert request.body == b"" - assert request.json == None + assert request.json is None assert response.body == b"OK" @@ -2211,7 +2231,10 @@ async def put(request, foo=None): with pytest.raises( ServerError, - match="Duplicate route names detected: test_conflicting_body_methods_overload_error\.put.*", + match=( + r"Duplicate route names detected:" + r" test_conflicting_body_methods_overload_error\.put.*" + ), ): await app._startup() @@ -2273,7 +2296,10 @@ def handler(request, **kwargs): with pytest.raises( ServerError, - match="Duplicate route names detected: test_handler_overload_error\.handler.*", + match=( + r"Duplicate route names detected:" + r" test_handler_overload_error\.handler.*" + ), ): await app._startup() diff --git a/tests/test_response.py b/tests/test_response.py index db3036eaf8..a9a540817f 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -610,7 +610,7 @@ async def handler3(request: Request): @app.get("/4") async def handler4(request: Request): - response = await request.respond(headers={"one": "one"}) + await request.respond(headers={"one": "one"}) return json({"foo": "bar"}, headers={"one": "two"}) @app.get("/5") @@ -641,10 +641,6 @@ async def handler6(request: Request): "been responded to." ) - error_msg3 = ( - "Response stream was ended, no more " - "response data is allowed to be sent." - ) with caplog.at_level(ERROR): _, response = app.test_client.get("/1") @@ -769,7 +765,7 @@ def file_route_no_store(request: Request, filename: str): assert ( "cache-control" in headers and f"max-age={test_max_age}" in headers.get("cache-control") - and f"public" in headers.get("cache-control") + and "public" in headers.get("cache-control") ) assert ( "expires" in headers @@ -800,14 +796,14 @@ def file_route_no_store(request: Request, filename: str): _, response = app.test_client.get(f"/files/no_cache/{file_name}") headers = response.headers - assert "cache-control" in headers and f"no-cache" == headers.get( + assert "cache-control" in headers and "no-cache" == headers.get( "cache-control" ) assert response.status == 200 _, response = app.test_client.get(f"/files/no_store/{file_name}") headers = response.headers - assert "cache-control" in headers and f"no-store" == headers.get( + assert "cache-control" in headers and "no-store" == headers.get( "cache-control" ) assert response.status == 200 @@ -895,7 +891,7 @@ def file_route(request: Request, filename: str): @pytest.mark.parametrize( "file_name", ["test.file", "decode me.txt", "python.png"] ) -def test_file_validating_304_response( +def test_file_validating_304_response_file_route( app: Sanic, file_name: str, static_file_directory: str ): @app.route("/files/", methods=["GET"]) diff --git a/tests/test_response_timeout.py b/tests/test_response_timeout.py index bd4ccc9be0..20c06b2398 100644 --- a/tests/test_response_timeout.py +++ b/tests/test_response_timeout.py @@ -49,8 +49,8 @@ def response_handler_cancelled_app(): @app.exception(asyncio.CancelledError) def handler_cancelled(request, exception): - # If we get a CancelledError, it means sanic has already sent a response, - # we should not ever have to handle a CancelledError. + # If we get a CancelledError, it means sanic has already sent a + # response, we should not ever have to handle a CancelledError. response_handler_cancelled_app.ctx.flag = True return text("App received CancelledError!", 500) # The client will never receive this response, because the socket diff --git a/tests/test_routes.py b/tests/test_routes.py index cd38161b66..8ec1372dc6 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -650,11 +650,9 @@ async def handler(): @pytest.mark.asyncio -@pytest.mark.parametrize("url", ["/ws", "ws"]) +@pytest.mark.parametrize("url", ["/ws", "/ws/"]) async def test_websocket_route_asgi(app, url): - @app.after_server_start - async def setup_ev(app, _): - app.ctx.ev = asyncio.Event() + app.ctx.ev = asyncio.Event() @app.websocket(url) async def handler(request, ws): @@ -665,7 +663,7 @@ async def check(request): return json({"set": request.app.ctx.ev.is_set()}) _, response = await app.asgi_client.websocket(url) - _, response = await app.asgi_client.get("/") + _, response = await app.asgi_client.get("/ev") assert response.json["set"] @@ -756,7 +754,7 @@ async def handler1(request): @pytest.mark.asyncio -async def test_websocket_route_asgi(app): +async def test_websocket_route_asgi_when_first_and_second_set(app): ev = asyncio.Event() @app.websocket("/test/1", name="test1") @@ -1129,7 +1127,7 @@ def handler(request): def test_route_with_regex_group(app): - @app.route("/path/to/") + @app.route(r"/path/to/") async def handler(request, ext): return text(ext) @@ -1160,7 +1158,7 @@ async def handler(request, ext): def test_route_with_regex_group_ambiguous(app): - @app.route("/path/to/") + @app.route(r"/path/to/") async def handler(request, ext): return text(ext) @@ -1169,7 +1167,7 @@ async def handler(request, ext): assert e.match( re.escape( - "Could not compile pattern file(?:\.)(txt). Try using a named " + r"Could not compile pattern file(?:\.)(txt). Try using a named " "group instead: '(?Pyour_matching_group)'" ) ) diff --git a/tests/test_signals.py b/tests/test_signals.py index 085ba412b6..5b5017b3f0 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -1,7 +1,6 @@ import asyncio from enum import Enum -from inspect import isawaitable from itertools import count import pytest @@ -28,7 +27,9 @@ def test_add_signal_method_handler(app): class TestSanic(Sanic): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.add_signal(self.after_routing_signal_handler, "http.routing.after") + self.add_signal( + self.after_routing_signal_handler, "http.routing.after" + ) def after_routing_signal_handler(self, *args, **kwargs): nonlocal counter @@ -96,11 +97,11 @@ async def test_dispatch_signal_triggers_correct_event(app): # Check for https://github.com/sanic-org/sanic/issues/2826 @app.signal("foo.bar.baz") - def sync_signal(*args): + def sync_signal_baz(*args): pass @app.signal("foo.bar.spam") - def sync_signal(*args): + def sync_signal_spam(*args): pass app.signal_router.finalize() @@ -291,7 +292,9 @@ def sync_signal(*_): app.signal_router.finalize() - event_task = asyncio.create_task(app.event("foo.bar.baz", condition={"one": "two"})) + event_task = asyncio.create_task( + app.event("foo.bar.baz", condition={"one": "two"}) + ) await app.dispatch("foo.bar.baz") await asyncio.sleep(0) assert not event_task.done() @@ -512,7 +515,7 @@ def sync_signal(): @pytest.mark.asyncio -async def test_dispatch_simple_signal_triggers_dynamic(app): +async def test_dispatch_simple_signal_triggers_dynamic_foo(app): counter = 0 @app.signal("") @@ -528,7 +531,7 @@ def sync_signal(foo): @pytest.mark.asyncio -async def test_dispatch_simple_signal_triggers(app): +async def test_dispatch_simple_signal_triggers_foo_bar(app): counter = 0 @app.signal("foo.bar.") @@ -684,7 +687,9 @@ async def handler(request): registered_signal_handlers = [ handler - for handler, *_ in app.signal_router.get(Event.SERVER_EXCEPTION_REPORT.value) + for handler, *_ in app.signal_router.get( + Event.SERVER_EXCEPTION_REPORT.value + ) ] assert catch_any_exception in registered_signal_handlers diff --git a/tests/test_static.py b/tests/test_static.py index 2ee41bfa99..04d54a9771 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -112,7 +112,7 @@ def test_static_file_pathlib(app, static_file_directory, file_name): ], ) def test_static_file_pathlib_relative_path_traversal( - app, static_file_directory, file_name + app, static_file_directory, file_name ): """Get the current working directory and check if it ends with "sanic" """ cwd = Path.cwd() @@ -173,7 +173,7 @@ def test_static_file_content_type(app, static_file_directory, file_name): ], ) def test_static_file_content_type_guessed( - app, static_file_directory, file_name, expected + app, static_file_directory, file_name, expected ): app.static( "/testing.file", @@ -241,8 +241,8 @@ def test_static_content_range_correct(app, file_name, static_file_directory): assert "Content-Length" in response.headers assert "Content-Range" in response.headers static_content = bytes(get_file_content(static_file_directory, file_name))[ - 12:20 - ] + 12:20 + ] assert int(response.headers["Content-Length"]) == len(static_content) assert response.body == static_content @@ -261,8 +261,8 @@ def test_static_content_range_front(app, file_name, static_file_directory): assert "Content-Length" in response.headers assert "Content-Range" in response.headers static_content = bytes(get_file_content(static_file_directory, file_name))[ - 12: - ] + 12: + ] assert int(response.headers["Content-Length"]) == len(static_content) assert response.body == static_content @@ -281,8 +281,8 @@ def test_static_content_range_back(app, file_name, static_file_directory): assert "Content-Length" in response.headers assert "Content-Range" in response.headers static_content = bytes(get_file_content(static_file_directory, file_name))[ - -12: - ] + -12: + ] assert int(response.headers["Content-Length"]) == len(static_content) assert response.body == static_content @@ -290,7 +290,7 @@ def test_static_content_range_back(app, file_name, static_file_directory): @pytest.mark.parametrize("use_modified_since", [True, False]) @pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"]) def test_static_content_range_empty( - app, file_name, static_file_directory, use_modified_since + app, file_name, static_file_directory, use_modified_since ): app.static( "/testing.file", @@ -331,7 +331,7 @@ def test_static_content_range_error(app, file_name, static_file_directory): @pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"]) def test_static_content_range_invalid_unit( - app, file_name, static_file_directory + app, file_name, static_file_directory ): app.static( "/testing.file", @@ -349,7 +349,7 @@ def test_static_content_range_invalid_unit( @pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"]) def test_static_content_range_invalid_start( - app, file_name, static_file_directory + app, file_name, static_file_directory ): app.static( "/testing.file", @@ -367,7 +367,7 @@ def test_static_content_range_invalid_start( @pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"]) def test_static_content_range_invalid_end( - app, file_name, static_file_directory + app, file_name, static_file_directory ): app.static( "/testing.file", @@ -385,7 +385,7 @@ def test_static_content_range_invalid_end( @pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"]) def test_static_content_range_invalid_parameters( - app, file_name, static_file_directory + app, file_name, static_file_directory ): app.static( "/testing.file", @@ -422,12 +422,12 @@ def test_static_file_specified_host(app, static_file_directory, file_name): @pytest.mark.parametrize("stream_large_files", [True, 1024]) @pytest.mark.parametrize("file_name", ["test.file", "large.file"]) def test_static_stream_large_file( - app, - static_file_directory, - file_name, - use_modified_since, - stream_large_files, - large_file, + app, + static_file_directory, + file_name, + use_modified_since, + stream_large_files, + large_file, ): app.static( "/testing.file", @@ -581,7 +581,8 @@ async def test_resource_type_default_error(app, static_file_directory): app.static("/static", static_file_directory) app.static("/file", get_file_path(static_file_directory, "test.file")) - message = r"Duplicate route names detected: test_resource_type_default_error\.static" + message = (r"Duplicate route names " + r"detected: test_resource_type_default_error\.static") with pytest.raises(ServerError, match=message): await app._startup() @@ -646,7 +647,8 @@ def test_resource_type_unknown(app, static_file_directory, caplog): reason="Windows does not support double dotted directories", ) def test_dotted_dir_ok( - app: Sanic, static_file_directory: str, double_dotted_directory_file: Path + app: Sanic, static_file_directory: str, + double_dotted_directory_file: Path ): app.static("/foo", static_file_directory) dot_relative_path = str( @@ -671,7 +673,7 @@ def test_breakout(app: Sanic, static_file_directory: str): sys.platform != "win32", reason="Block backslash on Windows only" ) def test_double_backslash_prohibited_on_win32( - app: Sanic, static_file_directory: str + app: Sanic, static_file_directory: str ): app.static("/foo", static_file_directory) diff --git a/tests/test_tls.py b/tests/test_tls.py index 6d2cb981c5..23168822bd 100644 --- a/tests/test_tls.py +++ b/tests/test_tls.py @@ -467,7 +467,8 @@ def stop(*args): ) logmsg = [ - m for s, l, m in caplog.record_tuples if m.startswith("Certificate") + msg for name, levelno, msg in caplog.record_tuples if ( + msg.startswith("Certificate")) ][0] assert logmsg == ( diff --git a/tests/test_url_building.py b/tests/test_url_building.py index 075ee6cdd2..b97836da89 100644 --- a/tests/test_url_building.py +++ b/tests/test_url_building.py @@ -35,8 +35,8 @@ URL_FOR_VALUE4 = f"http://{test_host}:{test_port}/myurl?arg1=v1#anchor" -def _generate_handlers_from_names(app, l): - for name in l: +def _generate_handlers_from_names(app, names): + for name in names: # this is the easiest way to generate functions with dynamic names exec( f'@app.route(name)\ndef {name}(request):\n\treturn text("{name}")' @@ -123,7 +123,7 @@ def fail(request): fail_args = list(string.ascii_lowercase) fail_args.pop() - fail_kwargs = {l: l for l in fail_args} + fail_kwargs = {fail_arg: fail_arg for fail_arg in fail_args} with pytest.raises(URLBuildError) as e: app.url_for("fail", **fail_kwargs) @@ -216,7 +216,8 @@ def fail(request): app.url_for("fail", **failing_kwargs) e.match( 'Value "foo" for parameter `some_number` ' - r"does not match pattern for type `float`: ^-?(?:\d+(?:\.\d*)?|\.\d+)$" + r"does not match pattern for type " + r"`float`: ^-?(?:\d+(?:\.\d*)?|\.\d+)$" ) @@ -230,7 +231,7 @@ def good(request, possibly_neg): u = app.url_for("good", possibly_neg=number) assert u == f"/path/{number}/another-word", u request, response = app.test_client.get(u) - # For ``number``, it has been cast to a float - so a ``3`` becomes a ``3.0`` + # For ``number``,it has been cast to a float - so a ``3`` becomes a ``3.0`` assert response.text == f"this should pass with `{float(number)}`" diff --git a/tests/test_ws_handlers.py b/tests/test_ws_handlers.py index 6236292402..974dcdd110 100644 --- a/tests/test_ws_handlers.py +++ b/tests/test_ws_handlers.py @@ -7,7 +7,9 @@ from sanic import Request, Sanic, Websocket -MimicClientType = Callable[[WebSocketClientProtocol], Coroutine[None, None, Any]] +MimicClientType = Callable[ + [WebSocketClientProtocol], Coroutine[None, None, Any] +] @pytest.fixture @@ -65,7 +67,9 @@ async def ws_echo_handler(request: Request, ws: Websocket): msg = await ws.recv() await ws.send(msg) - _, ws_proxy = app.test_client.websocket("/ws", mimic=simple_ws_mimic_client) + _, ws_proxy = app.test_client.websocket( + "/ws", mimic=simple_ws_mimic_client + ) assert ws_proxy.client_sent == ["test 1", "test 2", ""] assert ws_proxy.client_received == ["test 1", "test 2"] @@ -79,7 +83,9 @@ async def ws_echo_handler(request: Request, ws: Websocket): async for msg in ws: await ws.send(msg) - _, ws_proxy = app.test_client.websocket("/ws", mimic=simple_ws_mimic_client) + _, ws_proxy = app.test_client.websocket( + "/ws", mimic=simple_ws_mimic_client + ) assert ws_proxy.client_sent == ["test 1", "test 2", ""] assert ws_proxy.client_received == ["test 1", "test 2"] @@ -103,7 +109,9 @@ async def ws_url_handler(request: Request, ws: Websocket): await ws.recv() app.config.FORWARDED_SECRET = proxy - app.config.SERVER_NAME = "https://example.com" if proxy == "servername" else "" + app.config.SERVER_NAME = ( + "https://example.com" if proxy == "servername" else "" + ) _, ws_proxy = app.test_client.websocket( "/ws", mimic=simple_ws_mimic_client, @@ -125,7 +133,9 @@ def test_ws_signals( signalapp(app) app.ctx.seq = [] - _, ws_proxy = app.test_client.websocket("/ws", mimic=simple_ws_mimic_client) + _, ws_proxy = app.test_client.websocket( + "/ws", mimic=simple_ws_mimic_client + ) assert ws_proxy.client_received == ["before: test 1", "after: test 2"] assert app.ctx.seq == ["before", "ws", "after"] @@ -137,6 +147,8 @@ def test_ws_signals_exception( signalapp(app) app.ctx.seq = [] - _, ws_proxy = app.test_client.websocket("/wserror", mimic=simple_ws_mimic_client) + _, ws_proxy = app.test_client.websocket( + "/wserror", mimic=simple_ws_mimic_client + ) assert ws_proxy.client_received == ["before: test 1", "exception: test 2"] assert app.ctx.seq == ["before", "wserror", "exception"] diff --git a/tests/typing/samples/app_custom_config.py b/tests/typing/samples/app_custom_config.py index 5f10e7a902..ccc43b4b1a 100644 --- a/tests/typing/samples/app_custom_config.py +++ b/tests/typing/samples/app_custom_config.py @@ -7,4 +7,3 @@ class CustomConfig(Config): app = Sanic("test", config=CustomConfig()) -reveal_type(app) diff --git a/tests/typing/samples/app_custom_ctx.py b/tests/typing/samples/app_custom_ctx.py index fb0dc1bb86..01c4d4474a 100644 --- a/tests/typing/samples/app_custom_ctx.py +++ b/tests/typing/samples/app_custom_ctx.py @@ -6,4 +6,3 @@ class Foo: app = Sanic("test", ctx=Foo()) -reveal_type(app) diff --git a/tests/typing/samples/app_default.py b/tests/typing/samples/app_default.py index 34524c50e9..37dae7c4cf 100644 --- a/tests/typing/samples/app_default.py +++ b/tests/typing/samples/app_default.py @@ -2,4 +2,3 @@ app = Sanic("test") -reveal_type(app) diff --git a/tests/typing/samples/app_fully_custom.py b/tests/typing/samples/app_fully_custom.py index 197f1e0320..8e39a9225e 100644 --- a/tests/typing/samples/app_fully_custom.py +++ b/tests/typing/samples/app_fully_custom.py @@ -11,4 +11,3 @@ class Foo: app = Sanic("test", config=CustomConfig(), ctx=Foo()) -reveal_type(app) diff --git a/tests/typing/samples/request_custom_ctx.py b/tests/typing/samples/request_custom_ctx.py index 5fa4fe6a42..03313a95a7 100644 --- a/tests/typing/samples/request_custom_ctx.py +++ b/tests/typing/samples/request_custom_ctx.py @@ -13,5 +13,4 @@ class Foo: @app.get("/") async def handler(request: Request[Sanic[Config, SimpleNamespace], Foo]): - reveal_type(request.ctx) - reveal_type(request.app) + ... diff --git a/tests/typing/samples/request_custom_sanic.py b/tests/typing/samples/request_custom_sanic.py index cda4ae36fb..887ebcf765 100644 --- a/tests/typing/samples/request_custom_sanic.py +++ b/tests/typing/samples/request_custom_sanic.py @@ -15,5 +15,4 @@ class CustomConfig(Config): async def handler( request: Request[Sanic[CustomConfig, SimpleNamespace], SimpleNamespace], ): - reveal_type(request.ctx) - reveal_type(request.app) + ... diff --git a/tests/typing/samples/request_fully_custom.py b/tests/typing/samples/request_fully_custom.py index e2ec4b31e1..8b02bf0140 100644 --- a/tests/typing/samples/request_fully_custom.py +++ b/tests/typing/samples/request_fully_custom.py @@ -29,6 +29,4 @@ def make_context() -> RequestContext: @app.get("/") async def handler(request: CustomRequest): - reveal_type(request) - reveal_type(request.ctx) - reveal_type(request.app) + ... diff --git a/tests/typing/test_typing.py b/tests/typing/test_typing.py index 5ebba2669b..bdb7bf5643 100644 --- a/tests/typing/test_typing.py +++ b/tests/typing/test_typing.py @@ -1,7 +1,6 @@ # flake8: noqa: E501 import subprocess -import sys from pathlib import Path from typing import List, Tuple diff --git a/tests/worker/test_runner.py b/tests/worker/test_runner.py index 8a087e0e24..7949829d98 100644 --- a/tests/worker/test_runner.py +++ b/tests/worker/test_runner.py @@ -37,7 +37,11 @@ def test_run_server_forever(remove_unix_socket: Mock, do_cleanup: bool): with pytest.raises(KeyboardInterrupt): _run_server_forever( - loop, before_stop, after_stop, cleanup if do_cleanup else None, unix + loop, + before_stop, + after_stop, + cleanup if do_cleanup else None, + unix, ) loop.run_forever.assert_called_once_with()