Format with default line-length=88 (was 79 with Sanic).

This commit is contained in:
L. Kärkkäinen
2023-10-25 04:13:13 +01:00
parent e4daf1ab21
commit 1afea39cb2
137 changed files with 540 additions and 1613 deletions

View File

@@ -16,9 +16,7 @@ class TestSanicRouteResolution:
async def test_resolve_route_no_arg_string_path(
self, sanic_router, route_generator, benchmark
):
simple_routes = route_generator.generate_random_direct_route(
max_route_depth=4
)
simple_routes = route_generator.generate_random_direct_route(max_route_depth=4)
router, simple_routes = sanic_router(route_details=simple_routes)
route_to_call = choice(simple_routes)
request = Request(
@@ -52,9 +50,7 @@ class TestSanicRouteResolution:
)
router, typed_routes = sanic_router(route_details=typed_routes)
route_to_call = choice(typed_routes)
url = route_generator.generate_url_for_template(
template=route_to_call[-1]
)
url = route_generator.generate_url_for_template(template=route_to_call[-1])
print(f"{route_to_call[-1]} -> {url}")
request = Request(

View File

@@ -51,9 +51,7 @@ def selfsigned(key, common_name, san):
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=365.25 * 8))
.add_extension(
KeyUsage(
True, False, False, False, False, False, False, False, False
),
KeyUsage(True, False, False, False, False, False, False, False, False),
critical=True,
)
.add_extension(

View File

@@ -13,9 +13,7 @@ class RawClient:
self.port = port
async def connect(self):
self.reader, self.writer = await asyncio.open_connection(
self.host, self.port
)
self.reader, self.writer = await asyncio.open_connection(self.host, self.port)
async def close(self):
self.writer.close()
@@ -39,8 +37,4 @@ class RawClient:
return await self.reader.read(nbytes)
def _clean(self, message: str) -> str:
return (
dedent(message)
.lstrip("\n")
.replace("\n", self.CRLF.decode("utf-8"))
)
return dedent(message).lstrip("\n").replace("\n", self.CRLF.decode("utf-8"))

View File

@@ -42,14 +42,10 @@ async def _handler(request):
TYPE_TO_GENERATOR_MAP = {
"str": lambda: "".join(
[random.choice(string.ascii_lowercase) for _ in range(4)]
),
"str": lambda: "".join([random.choice(string.ascii_lowercase) for _ in range(4)]),
"int": lambda: random.choice(range(1000000)),
"float": lambda: random.random(),
"alpha": lambda: "".join(
[random.choice(string.ascii_lowercase) for _ in range(4)]
),
"alpha": lambda: "".join([random.choice(string.ascii_lowercase) for _ in range(4)]),
"uuid": lambda: str(uuid.uuid1()),
}

View File

@@ -84,9 +84,7 @@ async def test_http_receiver_run_request(app: Sanic, http_request: Request):
app.__class__ = mock_handle
receiver = generate_http_receiver(app, http_request)
receiver.protocol.quic_event_received(
ProtocolNegotiated(alpn_protocol="h3")
)
receiver.protocol.quic_event_received(ProtocolNegotiated(alpn_protocol="h3"))
await receiver.run()
handler.assert_awaited_once_with(receiver.request)
@@ -99,9 +97,7 @@ async def test_http_receiver_run_exception(app: Sanic, http_request: Request):
app.__class__ = mock_handle
receiver = generate_http_receiver(app, http_request)
receiver.protocol.quic_event_received(
ProtocolNegotiated(alpn_protocol="h3")
)
receiver.protocol.quic_event_received(ProtocolNegotiated(alpn_protocol="h3"))
exception = Exception("Oof")
await receiver.run(exception)
handler.assert_awaited_once_with(receiver.request, exception)
@@ -139,9 +135,7 @@ def test_http_receiver_receive_body(app: Sanic, http_request: Request):
receiver.receive_body(b"..")
assert receiver.request.body == b"...."
with pytest.raises(
PayloadTooLarge, match="Request body exceeds the size limit"
):
with pytest.raises(PayloadTooLarge, match="Request body exceeds the size limit"):
receiver.receive_body(b"..")
@@ -176,17 +170,13 @@ async def test_send_headers(app: Sanic, http_request: Request):
send_headers_mock = Mock()
existing_send_headers = H3Connection.send_headers
receiver = generate_http_receiver(app, http_request)
receiver.protocol.quic_event_received(
ProtocolNegotiated(alpn_protocol="h3")
)
receiver.protocol.quic_event_received(ProtocolNegotiated(alpn_protocol="h3"))
http_request._protocol = receiver.protocol
def send_headers(*args, **kwargs):
send_headers_mock(*args, **kwargs)
return existing_send_headers(
receiver.protocol.connection, *args, **kwargs
)
return existing_send_headers(receiver.protocol.connection, *args, **kwargs)
receiver.protocol.connection.send_headers = send_headers
receiver.head_only = False
@@ -310,10 +300,7 @@ def test_request_header_encoding(app):
)
)
assert exc_info.value.status_code == 400
assert (
str(exc_info.value)
== "Header names may only contain US-ASCII characters."
)
assert str(exc_info.value) == "Header names may only contain US-ASCII characters."
def test_request_url_encoding(app):

View File

@@ -5,9 +5,7 @@ import timeit
from sanic.response import json
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, currentdir + "/../../../")

View File

@@ -5,9 +5,7 @@ import sys
from sanic import Sanic
from sanic.response import json
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, currentdir + "/../../../")

View File

@@ -6,9 +6,7 @@ from sanic import Sanic
from sanic.exceptions import ServerError
from sanic.response import json, text
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, currentdir + "/../../../")

View File

@@ -97,9 +97,7 @@ def test_create_server_no_startup(app: Sanic):
asyncio_server_kwargs={"start_serving": False},
)
srv = loop.run_until_complete(asyncio_srv_coro)
message = (
"Cannot run Sanic server without first running await server.startup()"
)
message = "Cannot run Sanic server without first running await server.startup()"
with pytest.raises(SanicException, match=message):
loop.run_until_complete(srv.start_serving())
@@ -212,14 +210,8 @@ def test_app_websocket_parameters(websocket_protocol_mock, app: Sanic):
websocket_protocol_call_args = websocket_protocol_mock.call_args
ws_kwargs = websocket_protocol_call_args[1]
assert ws_kwargs["websocket_max_size"] == app.config.WEBSOCKET_MAX_SIZE
assert (
ws_kwargs["websocket_ping_timeout"]
== app.config.WEBSOCKET_PING_TIMEOUT
)
assert (
ws_kwargs["websocket_ping_interval"]
== app.config.WEBSOCKET_PING_INTERVAL
)
assert ws_kwargs["websocket_ping_timeout"] == app.config.WEBSOCKET_PING_TIMEOUT
assert ws_kwargs["websocket_ping_interval"] == app.config.WEBSOCKET_PING_INTERVAL
def test_handle_request_with_nested_exception(app: Sanic, monkeypatch):
@@ -228,9 +220,7 @@ def test_handle_request_with_nested_exception(app: Sanic, monkeypatch):
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
@app.get("/")
def handler(request):
@@ -247,9 +237,7 @@ def test_handle_request_with_nested_exception_debug(app: Sanic, monkeypatch):
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
@app.get("/")
def handler(request):
@@ -263,15 +251,11 @@ def test_handle_request_with_nested_exception_debug(app: Sanic, monkeypatch):
)
def test_handle_request_with_nested_sanic_exception(
app: Sanic, monkeypatch, caplog
):
def test_handle_request_with_nested_sanic_exception(app: Sanic, monkeypatch, caplog):
def mock_error_handler_response(*args, **kwargs):
raise SanicException("Mock SanicException")
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
@app.get("/")
def handler(request):
@@ -326,9 +310,7 @@ def test_app_registry_wrong_type():
def test_app_registry_name_reuse():
Sanic("test")
Sanic.test_mode = False
with pytest.raises(
SanicException, match='Sanic app name "test" already in use.'
):
with pytest.raises(SanicException, match='Sanic app name "test" already in use.'):
Sanic("test")
Sanic.test_mode = True
Sanic("test")
@@ -361,9 +343,7 @@ def test_get_app_does_not_exist():
def test_get_app_does_not_exist_force_create():
assert isinstance(
Sanic.get_app("does-not-exist", force_create=True), Sanic
)
assert isinstance(Sanic.get_app("does-not-exist", force_create=True), Sanic)
def test_get_app_default():
@@ -372,9 +352,7 @@ def test_get_app_default():
def test_get_app_no_default():
with pytest.raises(
SanicException, match="No Sanic apps have been registered."
):
with pytest.raises(SanicException, match="No Sanic apps have been registered."):
Sanic.get_app()
@@ -383,9 +361,7 @@ def test_get_app_default_ambiguous():
Sanic("test2")
with pytest.raises(
SanicException,
match=re.escape(
'Multiple Sanic apps found, use Sanic.get_app("app_name")'
),
match=re.escape('Multiple Sanic apps found, use Sanic.get_app("app_name")'),
):
Sanic.get_app()
@@ -417,8 +393,7 @@ def test_bad_custom_config():
with pytest.raises(
SanicException,
match=(
"When instantiating Sanic with config, you cannot also pass "
"env_prefix"
"When instantiating Sanic with config, you cannot also pass " "env_prefix"
),
):
Sanic("test", config=1, env_prefix=1)
@@ -500,9 +475,7 @@ def test_uvloop_cannot_never_called_with_create_server(caplog, monkeypatch):
)
counter = Counter([(r[1], r[2]) for r in caplog.record_tuples])
modified = sum(
1 for app in apps if not isinstance(app.config.USE_UVLOOP, Default)
)
modified = sum(1 for app in apps if not isinstance(app.config.USE_UVLOOP, Default))
assert counter[(logging.WARNING, message)] == modified
@@ -559,12 +532,8 @@ def test_no_workers(app: Sanic):
{"auto_reload": True},
),
)
def test_cannot_run_single_process_and_workers_or_auto_reload(
app: Sanic, extra
):
message = (
"Single process cannot be run with multiple workers or auto-reload"
)
def test_cannot_run_single_process_and_workers_or_auto_reload(app: Sanic, extra):
message = "Single process cannot be run with multiple workers or auto-reload"
with pytest.raises(RuntimeError, match=message):
app.run(single_process=True, **extra)

View File

@@ -352,9 +352,7 @@ async def test_websocket_bytes_receive(send, receive, message_stack):
@pytest.mark.asyncio
async def test_websocket_accept_with_no_subprotocols(
send, receive, message_stack
):
async def test_websocket_accept_with_no_subprotocols(send, receive, message_stack):
ws = WebSocketConnection(send, receive)
await ws.accept()

View File

@@ -28,9 +28,7 @@ def test_bp_group_with_additional_route_params(app: Sanic):
blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1")
blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2")
@blueprint_1.route(
"/request_path", methods=frozenset({"PUT", "POST"}), version=2
)
@blueprint_1.route("/request_path", methods=frozenset({"PUT", "POST"}), version=2)
def blueprint_1_v2_method_with_put_and_post(request: Request):
if request.method == "PUT":
return text("PUT_OK")
@@ -46,9 +44,7 @@ def test_bp_group_with_additional_route_params(app: Sanic):
elif request.method == "PATCH":
return text(f"PATCH_{param}")
blueprint_group = Blueprint.group(
blueprint_1, blueprint_2, url_prefix="/api"
)
blueprint_group = Blueprint.group(blueprint_1, blueprint_2, url_prefix="/api")
@blueprint_group.middleware("request")
def authenticate_request(request: Request):
@@ -68,15 +64,11 @@ def test_bp_group_with_additional_route_params(app: Sanic):
app.blueprint(blueprint_group)
header = {"authorization": " ".join(["Basic", AUTH])}
_, response = app.test_client.put(
"/v2/api/bp1/request_path", headers=header
)
_, response = app.test_client.put("/v2/api/bp1/request_path", headers=header)
assert response.text == "PUT_OK"
assert response.headers.get("x-test-middleware") == "value"
_, response = app.test_client.post(
"/v2/api/bp1/request_path", headers=header
)
_, response = app.test_client.post("/v2/api/bp1/request_path", headers=header)
assert response.text == "POST_OK"
_, response = app.test_client.delete("/api/bp2/route/bp2", headers=header)
@@ -109,9 +101,7 @@ def test_bp_group(app: Sanic):
def blueprint_2_error(request: Request):
raise ServerError("Error")
blueprint_group_1 = Blueprint.group(
blueprint_1, blueprint_2, url_prefix="/bp"
)
blueprint_group_1 = Blueprint.group(blueprint_1, blueprint_2, url_prefix="/bp")
blueprint_3 = Blueprint("blueprint_3", url_prefix="/bp3")
@@ -213,9 +203,7 @@ def test_bp_group_list_operations(app: Sanic):
def blueprint_2_default_route(request):
return text("BP2_OK")
blueprint_group_1 = Blueprint.group(
blueprint_1, blueprint_2, url_prefix="/bp"
)
blueprint_group_1 = Blueprint.group(blueprint_1, blueprint_2, url_prefix="/bp")
blueprint_3 = Blueprint("blueprint_2", url_prefix="/bp3")
@@ -247,9 +235,7 @@ def test_bp_group_as_list():
def test_bp_group_as_nested_group():
blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1")
blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2")
blueprint_group_1 = Blueprint.group(
Blueprint.group(blueprint_1, blueprint_2)
)
blueprint_group_1 = Blueprint.group(Blueprint.group(blueprint_1, blueprint_2))
assert len(blueprint_group_1) == 1
@@ -259,9 +245,7 @@ def test_blueprint_group_insert():
)
blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2")
blueprint_3 = Blueprint("blueprint_3", url_prefix=None)
group = BlueprintGroup(
url_prefix="/test", version=1.3, strict_slashes=False
)
group = BlueprintGroup(url_prefix="/test", version=1.3, strict_slashes=False)
group.insert(0, blueprint_1)
group.insert(0, blueprint_2)
group.insert(0, blueprint_3)
@@ -350,12 +334,8 @@ async def test_multiple_nested_bp_group():
bp1.add_route(lambda _: ..., "/", name="route1")
bp2.add_route(lambda _: ..., "/", name="route2")
group_a = Blueprint.group(
bp1, bp2, url_prefix="/group-a", name_prefix="group-a"
)
group_b = Blueprint.group(
bp1, bp2, url_prefix="/group-b", name_prefix="group-b"
)
group_a = Blueprint.group(bp1, bp2, url_prefix="/group-a", name_prefix="group-a")
group_b = Blueprint.group(bp1, bp2, url_prefix="/group-b", name_prefix="group-b")
app = Sanic("PropTest")
app.blueprint(group_a)

View File

@@ -751,9 +751,7 @@ def test_bp_group_with_default_url_prefix(app: Sanic):
def api_v1_info(request):
return text("api_version: v1")
bp_api_v1_group = Blueprint.group(
bp_api_v1, bp_resources_group, url_prefix="/v1"
)
bp_api_v1_group = Blueprint.group(bp_api_v1, bp_resources_group, url_prefix="/v1")
bp_api_group = Blueprint.group(bp_api_v1_group, url_prefix="/api")
app.blueprint(bp_api_group)
@@ -794,9 +792,7 @@ def test_blueprint_middleware_with_args(app: Sanic):
)
assert response.text == "value"
_, response = app.test_client.get(
"/wa", headers={"content-type": "plain/text"}
)
_, response = app.test_client.get("/wa", headers={"content-type": "plain/text"})
assert response.json.get("test") == "value"
@@ -985,13 +981,9 @@ def test_blueprint_group_strict_slashes():
app = Sanic(name="blueprint-group-test")
bp1 = Blueprint(name="bp1", url_prefix=None, strict_slashes=False)
bp2 = Blueprint(
name="bp2", version=3, url_prefix="/bp2", strict_slashes=None
)
bp2 = Blueprint(name="bp2", version=3, url_prefix="/bp2", strict_slashes=None)
bp3 = Blueprint(
name="bp3", version=None, url_prefix="/bp3/", strict_slashes=None
)
bp3 = Blueprint(name="bp3", version=None, url_prefix="/bp3/", strict_slashes=None)
@bp1.get("/r1")
async def bp1_r1(request):

View File

@@ -133,9 +133,7 @@ def test_add_converter_multiple_times(caplog):
def converter():
...
message = (
"Configuration value converter 'converter' has already been registered"
)
message = "Configuration value converter 'converter' has already been registered"
config = Config()
config.register_type(converter)
with caplog.at_level(logging.WARNING):
@@ -306,14 +304,10 @@ async def test_config_access_log_passing_in_create_server(app: Sanic):
async def _request(sanic, loop):
app.stop()
await app.create_server(
port=1341, access_log=False, return_asyncio_server=True
)
await app.create_server(port=1341, access_log=False, return_asyncio_server=True)
assert app.config.ACCESS_LOG is False
await app.create_server(
port=1342, access_log=True, return_asyncio_server=True
)
await app.create_server(port=1342, access_log=True, return_asyncio_server=True)
assert app.config.ACCESS_LOG is True
@@ -334,9 +328,7 @@ def test_config_rewrite_keep_alive():
_test_setting_as_dict = {"TEST_SETTING_VALUE": 1}
_test_setting_as_class = type("C", (), {"TEST_SETTING_VALUE": 1})
_test_setting_as_module = str(
Path(__file__).parent / "static/app_test_config.py"
)
_test_setting_as_module = str(Path(__file__).parent / "static/app_test_config.py")
@pytest.mark.parametrize(

View File

@@ -42,9 +42,7 @@ async def test_cookies_asgi(app):
response.cookies["right_back"] = "at you"
return response
request, response = await app.asgi_client.get(
"/", cookies={"test": "working!"}
)
request, response = await app.asgi_client.get("/", cookies={"test": "working!"})
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get("set-cookie", {}))
@@ -101,9 +99,7 @@ def test_cookie_options(app):
response = text("OK")
response.cookies["test"] = "at you"
response.cookies["test"]["httponly"] = True
response.cookies["test"]["expires"] = datetime.now() + timedelta(
seconds=10
)
response.cookies["test"]["expires"] = datetime.now() + timedelta(seconds=10)
return response
request, response = app.test_client.get("/")
@@ -179,17 +175,11 @@ def test_cookie_max_age(app, max_age):
response.cookies["test"]["max-age"] = max_age
return response
request, response = app.test_client.get(
"/", cookies=cookies, raw_cookies=True
)
request, response = app.test_client.get("/", cookies=cookies, raw_cookies=True)
assert response.status == 200
cookie = response.cookies.get("test")
if (
str(max_age).isdigit()
and int(max_age) == float(max_age)
and int(max_age) != 0
):
if str(max_age).isdigit() and int(max_age) == float(max_age) and int(max_age) != 0:
cookie_expires = datetime.utcfromtimestamp(
response.raw_cookies["test"].expires
).replace(microsecond=0)
@@ -202,9 +192,8 @@ def test_cookie_max_age(app, max_age):
)
assert cookie == "pass"
assert (
cookie_expires == expires
or cookie_expires == expires + timedelta(seconds=-1)
assert cookie_expires == expires or cookie_expires == expires + timedelta(
seconds=-1
)
else:
assert cookie is None
@@ -221,9 +210,7 @@ def test_cookie_bad_max_age(app, max_age):
response.cookies["test"]["max-age"] = max_age
return response
request, response = app.test_client.get(
"/", cookies=cookies, raw_cookies=True
)
request, response = app.test_client.get("/", cookies=cookies, raw_cookies=True)
assert response.status == 500
@@ -239,9 +226,7 @@ def test_cookie_expires(app: Sanic, expires: timedelta):
response.cookies["test"]["expires"] = expires_time
return response
request, response = app.test_client.get(
"/", cookies=cookies, raw_cookies=True
)
request, response = app.test_client.get("/", cookies=cookies, raw_cookies=True)
cookie_expires = datetime.utcfromtimestamp(
response.raw_cookies["test"].expires
@@ -399,17 +384,13 @@ def test_bad_cookie_prarms():
ServerError,
match="Cannot set host_prefix on a cookie unless path='/'",
):
jar.add_cookie(
"foo", "bar", host_prefix=True, secure=True, path="/foo"
)
jar.add_cookie("foo", "bar", host_prefix=True, secure=True, path="/foo")
with pytest.raises(
ServerError,
match="Cannot set host_prefix on a cookie with a defined domain",
):
jar.add_cookie(
"foo", "bar", host_prefix=True, secure=True, domain="foo.bar"
)
jar.add_cookie("foo", "bar", host_prefix=True, secure=True, domain="foo.bar")
with pytest.raises(
ServerError,

View File

@@ -544,9 +544,7 @@ def test_guess_mime_logging(
with caplog.at_level(logging.DEBUG, logger="sanic.root"):
guess_mime(fake_request, fallback)
(logmsg,) = (
r.message for r in caplog.records if r.funcName == "guess_mime"
)
(logmsg,) = (r.message for r in caplog.records if r.funcName == "guess_mime")
assert logmsg == expected
@@ -564,9 +562,7 @@ def test_exception_header_on_renderers(app: Sanic, format, expected):
@app.get("/test")
def test(request):
raise SanicException(
"test", status_code=400, headers={"exception": "test"}
)
raise SanicException("test", status_code=400, headers={"exception": "test"})
_, response = app.test_client.get("/test")
assert response.status == 400

View File

@@ -198,9 +198,7 @@ def test_handled_unhandled_exception(exception_app):
def test_exception_in_exception_handler(exception_app):
"""Test that an exception thrown in an error handler is handled"""
request, response = exception_app.test_client.get(
"/error_in_error_handler_handler"
)
request, response = exception_app.test_client.get("/error_in_error_handler_handler")
assert response.status == 500
assert response.body == b"An error occurred while handling an error"
@@ -284,15 +282,9 @@ def test_contextual_exception_context(debug):
def fail():
raise TeapotError(context={"foo": "bar"})
app.post("/coffee/json", error_format="json", name="json")(
lambda _: fail()
)
app.post("/coffee/html", error_format="html", name="html")(
lambda _: fail()
)
app.post("/coffee/text", error_format="text", name="text")(
lambda _: fail()
)
app.post("/coffee/json", error_format="json", name="json")(lambda _: fail())
app.post("/coffee/html", error_format="html", name="html")(lambda _: fail())
app.post("/coffee/text", error_format="text", name="text")(lambda _: fail())
_, response = app.test_client.post("/coffee/json", debug=debug)
assert response.status == 418
@@ -328,15 +320,9 @@ def test_contextual_exception_extra(debug):
def fail():
raise TeapotError(extra={"foo": "bar"})
app.post("/coffee/json", error_format="json", name="json")(
lambda _: fail()
)
app.post("/coffee/html", error_format="html", name="html")(
lambda _: fail()
)
app.post("/coffee/text", error_format="text", name="text")(
lambda _: fail()
)
app.post("/coffee/json", error_format="json", name="json")(lambda _: fail())
app.post("/coffee/html", error_format="html", name="html")(lambda _: fail())
app.post("/coffee/text", error_format="text", name="text")(lambda _: fail())
_, response = app.test_client.post("/coffee/json", debug=debug)
assert response.status == 418

View File

@@ -133,9 +133,7 @@ def test_inherited_exception_handler(exception_handler_app: Sanic):
def test_chained_exception_handler(exception_handler_app: Sanic):
request, response = exception_handler_app.test_client.get(
"/6/0", debug=True
)
request, response = exception_handler_app.test_client.get("/6/0", debug=True)
assert response.status == 500
soup = BeautifulSoup(response.body, "html.parser")
@@ -182,20 +180,14 @@ def test_exception_handler_lookup(exception_handler_app: Sanic):
assert handler.lookup(ModuleNotFoundError(), None) == import_error_handler
assert handler.lookup(CustomError(), None) == custom_error_handler
assert handler.lookup(ServerError("Error"), None) == server_error_handler
assert (
handler.lookup(CustomServerError("Error"), None)
== server_error_handler
)
assert handler.lookup(CustomServerError("Error"), None) == server_error_handler
# once again to ensure there is no caching bug
assert handler.lookup(ImportError(), None) == import_error_handler
assert handler.lookup(ModuleNotFoundError(), None) == import_error_handler
assert handler.lookup(CustomError(), None) == custom_error_handler
assert handler.lookup(ServerError("Error"), None) == server_error_handler
assert (
handler.lookup(CustomServerError("Error"), None)
== server_error_handler
)
assert handler.lookup(CustomServerError("Error"), None) == server_error_handler
def test_exception_handler_processed_request_middleware(

View File

@@ -62,9 +62,7 @@ def test_extend_cannot_be_called_multiple_times(app: Sanic, sanic_ext):
)
def test_fail_if_not_loaded(app: Sanic):
del sys.modules["sanic_ext"]
with pytest.raises(
RuntimeError, match="Sanic Extensions is not installed.*"
):
with pytest.raises(RuntimeError, match="Sanic Extensions is not installed.*"):
app.extend(built_in_extensions=False)

View File

@@ -8,9 +8,7 @@ from sanic.response import empty
PORT = 42101
def test_no_exceptions_when_cancel_pending_request(
app, caplog: LogCaptureFixture
):
def test_no_exceptions_when_cancel_pending_request(app, caplog: LogCaptureFixture):
app.config.GRACEFUL_SHUTDOWN_TIMEOUT = 1
@app.get("/")

View File

@@ -243,9 +243,7 @@ def test_accept_parsed_against_str():
def test_media_type_matching():
assert headers.MediaType("foo", "bar").match(
headers.MediaType("foo", "bar")
)
assert headers.MediaType("foo", "bar").match(headers.MediaType("foo", "bar"))
assert headers.MediaType("foo", "bar").match("foo/bar")
@@ -365,31 +363,23 @@ def test_accept_ordering(raw):
def test_not_accept_wildcard():
accept = headers.parse_accept("*/*, foo/*, */bar, foo/bar;q=0.1")
assert not accept.match(
"text/html", "foo/foo", "bar/bar", accept_wildcards=False
)
assert not accept.match("text/html", "foo/foo", "bar/bar", accept_wildcards=False)
# Should ignore wildcards in accept but still matches them from mimes
m = accept.match("text/plain", "*/*", accept_wildcards=False)
assert m.mime == "*/*"
assert m.match("*/*")
assert m.header == "foo/bar"
assert not accept.match(
"text/html", "foo/foo", "bar/bar", accept_wildcards=False
)
assert not accept.match("text/html", "foo/foo", "bar/bar", accept_wildcards=False)
def test_accept_misc():
header = (
"foo/bar;q=0.0, */plain;param=123, text/plain, text/*, foo/bar;q=0.5"
)
header = "foo/bar;q=0.0, */plain;param=123, text/plain, text/*, foo/bar;q=0.5"
a = headers.parse_accept(header)
assert repr(a) == (
"[*/plain;param=123, text/plain, text/*, "
"foo/bar;q=0.5, foo/bar;q=0.0]"
"[*/plain;param=123, text/plain, text/*, " "foo/bar;q=0.5, foo/bar;q=0.0]"
) # noqa: E501
assert str(a) == (
"*/plain;param=123, text/plain, text/*, "
"foo/bar;q=0.5, foo/bar;q=0.0"
"*/plain;param=123, text/plain, text/*, " "foo/bar;q=0.5, foo/bar;q=0.0"
) # noqa: E501
# q=1 types don't match foo/bar but match the two others,
# text/* comes first and matches */plain because it

View File

@@ -11,9 +11,7 @@ try:
import ujson
from ujson import dumps as udumps
ujson_version = tuple(
map(int, ujson.__version__.strip(ascii_lowercase).split("."))
)
ujson_version = tuple(map(int, ujson.__version__.strip(ascii_lowercase).split(".")))
NO_UJSON = False
DEFAULT_DUMPS = udumps
@@ -69,15 +67,11 @@ def test_json_response_ujson(payload: Dict[str, Foo]):
response = json(payload)
assert response.body == b'{"foo":{"bar":"bar"}}'
with pytest.raises(
TypeError, match="Object of type Foo is not JSON serializable"
):
with pytest.raises(TypeError, match="Object of type Foo is not JSON serializable"):
json(payload, dumps=sdumps)
Sanic("Test", dumps=sdumps)
with pytest.raises(
TypeError, match="Object of type Foo is not JSON serializable"
):
with pytest.raises(TypeError, match="Object of type Foo is not JSON serializable"):
json(payload)

View File

@@ -72,9 +72,7 @@ def test_keep_alive_timeout_reuse():
port = get_port()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = ReusableClient(
keep_alive_timeout_app_reuse, loop=loop, port=port
)
client = ReusableClient(keep_alive_timeout_app_reuse, loop=loop, port=port)
try:
with client:
headers = {"Connection": "keep-alive"}
@@ -113,14 +111,10 @@ def test_keep_alive_client_timeout():
port = get_port()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = ReusableClient(
keep_alive_app_client_timeout, loop=loop, port=port
)
client = ReusableClient(keep_alive_app_client_timeout, loop=loop, port=port)
with client:
headers = {"Connection": "keep-alive"}
request, response = client.get(
"/1", headers=headers, timeout=1
)
request, response = client.get("/1", headers=headers, timeout=1)
assert response.status == 200
assert response.text == "OK"
@@ -153,14 +147,10 @@ def test_keep_alive_server_timeout():
port = get_port()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = ReusableClient(
keep_alive_app_server_timeout, loop=loop, port=port
)
client = ReusableClient(keep_alive_app_server_timeout, loop=loop, port=port)
with client:
headers = {"Connection": "keep-alive"}
request, response = client.get(
"/1", headers=headers, timeout=60
)
request, response = client.get("/1", headers=headers, timeout=60)
assert response.status == 200
assert response.text == "OK"
@@ -190,9 +180,7 @@ def test_keep_alive_connection_context():
port = get_port()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = ReusableClient(
keep_alive_app_context, loop=loop, port=port
)
client = ReusableClient(keep_alive_app_context, loop=loop, port=port)
with client:
headers = {"Connection": "keep-alive"}
request1, _ = client.post("/ctx", headers=headers)
@@ -203,9 +191,7 @@ def test_keep_alive_connection_context():
assert response.text == "hello"
assert id(request1.conn_info.ctx) == id(request2.conn_info.ctx)
assert (
request1.conn_info.ctx.foo
== request2.conn_info.ctx.foo
== "hello"
request1.conn_info.ctx.foo == request2.conn_info.ctx.foo == "hello"
)
assert request2.protocol.state["requests_count"] == 2
except OSError:

View File

@@ -25,9 +25,7 @@ def test_log(app):
log_stream = StringIO()
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(
format=logging_format, level=logging.DEBUG, stream=log_stream
)
logging.basicConfig(format=logging_format, level=logging.DEBUG, stream=log_stream)
logging.getLogger("asyncio").setLevel(logging.WARNING)
log = logging.getLogger()
rand_string = str(uuid.uuid4())
@@ -47,26 +45,13 @@ def test_logging_defaults():
Sanic("test_logging")
for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
assert (
fmt._fmt
== LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
)
assert fmt._fmt == LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
for fmt in [
h.formatter for h in logging.getLogger("sanic.error").handlers
]:
assert (
fmt._fmt
== LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
)
for fmt in [h.formatter for h in logging.getLogger("sanic.error").handlers]:
assert fmt._fmt == LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
for fmt in [
h.formatter for h in logging.getLogger("sanic.access").handlers
]:
assert (
fmt._fmt
== LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"]
)
for fmt in [h.formatter for h in logging.getLogger("sanic.access").handlers]:
assert fmt._fmt == LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"]
def test_logging_pass_customer_logconfig():
@@ -85,14 +70,10 @@ def test_logging_pass_customer_logconfig():
for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
assert fmt._fmt == modified_config["formatters"]["generic"]["format"]
for fmt in [
h.formatter for h in logging.getLogger("sanic.error").handlers
]:
for fmt in [h.formatter for h in logging.getLogger("sanic.error").handlers]:
assert fmt._fmt == modified_config["formatters"]["generic"]["format"]
for fmt in [
h.formatter for h in logging.getLogger("sanic.access").handlers
]:
for fmt in [h.formatter for h in logging.getLogger("sanic.access").handlers]:
assert fmt._fmt == modified_config["formatters"]["access"]["format"]
@@ -108,9 +89,7 @@ def test_log_connection_lost(app, debug, monkeypatch):
stream = StringIO()
error = logging.getLogger("sanic.error")
error.addHandler(logging.StreamHandler(stream))
monkeypatch.setattr(
sanic.server.protocols.http_protocol, "error_logger", error
)
monkeypatch.setattr(sanic.server.protocols.http_protocol, "error_logger", error)
@app.route("/conn_lost")
async def conn_lost(request):
@@ -234,9 +213,7 @@ def test_verbosity(app, caplog, app_verbosity, log_verbosity, exists):
return text("hello")
with caplog.at_level(logging.INFO):
_ = app.test_client.get(
"/", server_kwargs={"verbosity": app_verbosity}
)
_ = app.test_client.get("/", server_kwargs={"verbosity": app_verbosity})
record = ("sanic.root", logging.INFO, rand_string)

View File

@@ -74,9 +74,7 @@ def test_reload_dirs(app):
app.config.AUTO_RELOAD = True
with patch.object(MOTD, "output") as mock:
app.prepare(
reload_dir="./", auto_reload=True, motd_display={"foo": "bar"}
)
app.prepare(reload_dir="./", auto_reload=True, motd_display={"foo": "bar"})
mock.assert_called()
assert mock.call_args.args[2]["auto-reload"] == f"enabled, {os.getcwd()}"
assert mock.call_args.args[3] == {"foo": "bar"}

View File

@@ -162,11 +162,5 @@ def test_main_process_event(app, caplog):
with caplog.at_level(logging.INFO):
app.run(HOST, PORT, workers=num_workers)
assert (
caplog.record_tuples.count(("sanic.root", 20, "main_process_start"))
== 2
)
assert (
caplog.record_tuples.count(("sanic.root", 20, "main_process_stop"))
== 2
)
assert caplog.record_tuples.count(("sanic.root", 20, "main_process_start")) == 2
assert caplog.record_tuples.count(("sanic.root", 20, "main_process_stop")) == 2

View File

@@ -283,9 +283,7 @@ def test_dynamic_named_route_path():
def test_dynamic_named_route_unhashable():
app = Sanic("app")
@app.route(
"/folder/<unhashable:[A-Za-z0-9/]+>/end/", name="route_unhashable"
)
@app.route("/folder/<unhashable:[A-Za-z0-9/]+>/end/", name="route_unhashable")
async def handler(request, unhashable):
return text("OK")
@@ -366,10 +364,7 @@ def test_dynamic_add_named_route():
return text("OK")
app.add_route(handler, "/folder/<name>", name="route_dynamic")
assert (
app.router.routes_all[("folder", "<name:str>")].name
== "app.route_dynamic"
)
assert app.router.routes_all[("folder", "<name:str>")].name == "app.route_dynamic"
assert app.url_for("route_dynamic", name="test") == "/folder/test"
with pytest.raises(URLBuildError):
app.url_for("handler")

View File

@@ -95,6 +95,4 @@ def test_bad_headers(app):
assert response1.status == 200
assert response2.status == 413
assert (
response1.headers["x-request-id"] != response2.headers["x-request-id"]
)
assert response1.headers["x-request-id"] != response2.headers["x-request-id"]

View File

@@ -220,9 +220,7 @@ def test_reload_listeners():
filename, port=42305, auto_reload=True
)
proc = Popen(
argv["script"], cwd=tmpdir, stdout=PIPE, creationflags=flags
)
proc = Popen(argv["script"], cwd=tmpdir, stdout=PIPE, creationflags=flags)
try:
timeout = Timer(TIMER_DELAY, terminate, [proc])
timeout.start()

View File

@@ -75,9 +75,7 @@ def test_request_id(request_id, expected_type):
async def get(request):
return response.empty()
request, _ = app.test_client.get(
"/", headers={"X-REQUEST-ID": f"{request_id}"}
)
request, _ = app.test_client.get("/", headers={"X-REQUEST-ID": f"{request_id}"})
assert request.id == request_id
assert type(request.id) == expected_type
@@ -168,9 +166,7 @@ def test_request_accept():
assert match.header.mime == "text/plain"
assert match.header.params == {"format": "flowed"}
header_value = (
"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"
)
header_value = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"
request, _ = app.test_client.get(
"/",
headers={"Accept": header_value},

View File

@@ -369,9 +369,7 @@ def test_request_stream_blueprint(app):
result += body.decode("utf-8")
return text(result)
bp.add_route(
post_add_route, "/post/add_route", methods=["POST"], stream=True
)
bp.add_route(post_add_route, "/post/add_route", methods=["POST"], stream=True)
app.blueprint(bp)
request, response = app.test_client.get("/get")

View File

@@ -68,9 +68,7 @@ async def test_url_asgi(app):
request, response = await app.asgi_client.get("/")
if response.body.decode().endswith("/") and not ASGI_BASE_URL.endswith(
"/"
):
if response.body.decode().endswith("/") and not ASGI_BASE_URL.endswith("/"):
response.body[:-1] == ASGI_BASE_URL.encode()
else:
assert response.body == ASGI_BASE_URL.encode()
@@ -387,9 +385,7 @@ def test_token(app, auth_type, token):
if token:
headers = {
"content-type": "application/json",
"Authorization": f"{auth_type} {token}"
if auth_type
else f"{token}",
"Authorization": f"{auth_type} {token}" if auth_type else f"{token}",
}
else:
headers = {"content-type": "application/json"}
@@ -426,9 +422,7 @@ def test_credentials(app, capfd, auth_type, token, username, password):
if token:
headers = {
"content-type": "application/json",
"Authorization": f"{auth_type} {token}"
if auth_type
else f"{token}",
"Authorization": f"{auth_type} {token}" if auth_type else f"{token}",
}
else:
headers = {"content-type": "application/json"}
@@ -649,9 +643,7 @@ async def test_standard_forwarded_asgi(app):
assert response.json == {"for": "127.0.0.2", "proto": "ws"}
# Header present but not matching anything
request, response = await app.asgi_client.get(
"/", headers={"Forwarded": "."}
)
request, response = await app.asgi_client.get("/", headers={"Forwarded": "."})
assert response.json == {}
# Forwarded header present but no matching secret -> use X-headers
@@ -753,9 +745,7 @@ def test_remote_addr_with_two_proxies(app):
assert request.remote_addr == "127.0.0.1"
assert response.body == b"127.0.0.1"
headers = {
"X-Forwarded-For": ", 127.0.2.2, , ,127.0.0.1, , ,,127.0.1.2"
}
headers = {"X-Forwarded-For": ", 127.0.2.2, , ,127.0.0.1, , ,,127.0.1.2"}
request, response = app.test_client.get("/", headers=headers)
assert request.remote_addr == "127.0.0.1"
assert response.body == b"127.0.0.1"
@@ -794,9 +784,7 @@ async def test_remote_addr_with_two_proxies_asgi(app):
assert request.remote_addr == "127.0.0.1"
assert response.body == b"127.0.0.1"
headers = {
"X-Forwarded-For": ", 127.0.2.2, , ,127.0.0.1, , ,,127.0.1.2"
}
headers = {"X-Forwarded-For": ", 127.0.2.2, , ,127.0.0.1, , ,,127.0.1.2"}
request, response = await app.asgi_client.get("/", headers=headers)
assert request.remote_addr == "127.0.0.1"
assert response.body == b"127.0.0.1"
@@ -992,9 +980,7 @@ def test_post_form_urlencoded(app):
payload = "test=OK"
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = app.test_client.post(
"/", data=payload, headers=headers
)
request, response = app.test_client.post("/", data=payload, headers=headers)
assert request.form.get("test") == "OK"
assert request.form.get("test") == "OK" # For request.parsed_form
@@ -1009,9 +995,7 @@ async def test_post_form_urlencoded_asgi(app):
payload = "test=OK"
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
assert request.form.get("test") == "OK"
assert request.form.get("test") == "OK" # For request.parsed_form
@@ -1026,9 +1010,7 @@ def test_post_form_urlencoded_keep_blanks(app):
payload = "test="
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = app.test_client.post(
"/", data=payload, headers=headers
)
request, response = app.test_client.post("/", data=payload, headers=headers)
assert request.form.get("test") == ""
assert request.form.get("test") == "" # For request.parsed_form
@@ -1044,9 +1026,7 @@ async def test_post_form_urlencoded_keep_blanks_asgi(app):
payload = "test="
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
assert request.form.get("test") == ""
assert request.form.get("test") == "" # For request.parsed_form
@@ -1060,9 +1040,7 @@ def test_post_form_urlencoded_drop_blanks(app):
payload = "test="
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = app.test_client.post(
"/", data=payload, headers=headers
)
request, response = app.test_client.post("/", data=payload, headers=headers)
assert "test" not in request.form.keys()
@@ -1076,9 +1054,7 @@ async def test_post_form_urlencoded_drop_blanks_asgi(app):
payload = "test="
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
assert "test" not in request.form.keys()
@@ -1133,9 +1109,7 @@ async def test_post_form_multipart_form_data_asgi(app, payload):
headers = {"content-type": "multipart/form-data; boundary=----sanic"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
assert request.form.get("test") == "OK"
@@ -1200,9 +1174,7 @@ def test_form_with_multiple_values(app):
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = app.test_client.post(
"/", data=payload, headers=headers
)
request, response = app.test_client.post("/", data=payload, headers=headers)
assert request.form.getlist("selectedItems") == ["v1", "v2", "v3"]
@@ -1217,9 +1189,7 @@ async def test_form_with_multiple_values_asgi(app):
headers = {"content-type": "application/x-www-form-urlencoded"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
assert request.form.getlist("selectedItems") == ["v1", "v2", "v3"]
@@ -1445,9 +1415,7 @@ def test_request_multipart_file_without_field_name(app, caplog):
headers = {"content-type": "multipart/form-data; boundary=------sanic"}
request, _ = app.test_client.post(
data=payload, headers=headers, debug=True
)
request, _ = app.test_client.post(data=payload, headers=headers, debug=True)
with caplog.at_level(logging.DEBUG):
request.form
@@ -1484,9 +1452,7 @@ def test_request_multipart_file_duplicate_filed_name(app):
"Content-Type": "multipart/form-data; boundary=e73ffaa8b1b2472b8ec848de833cb05b"
}
request, _ = app.test_client.post(
data=payload, headers=headers, debug=True
)
request, _ = app.test_client.post(data=payload, headers=headers, debug=True)
assert request.form.getlist("file") == [
'{"test":"json"}',
'{"test":"json2"}',
@@ -1607,9 +1573,7 @@ def test_request_parsing_form_failed(app, caplog):
payload = "test=OK"
headers = {"content-type": "multipart/form-data"}
request, response = app.test_client.post(
"/", data=payload, headers=headers
)
request, response = app.test_client.post("/", data=payload, headers=headers)
with caplog.at_level(logging.ERROR):
request.form
@@ -1630,9 +1594,7 @@ async def test_request_parsing_form_failed_asgi(app, caplog):
payload = "test=OK"
headers = {"content-type": "multipart/form-data"}
request, response = await app.asgi_client.post(
"/", data=payload, headers=headers
)
request, response = await app.asgi_client.post("/", data=payload, headers=headers)
with caplog.at_level(logging.ERROR):
request.form
@@ -1743,9 +1705,7 @@ def test_request_query_args_custom_parsing(app):
def handler(request):
return text("pass")
request, response = app.test_client.get(
"/?test1=value1&test2=&test3=value3"
)
request, response = app.test_client.get("/?test1=value1&test2=&test3=value3")
assert request.get_query_args(keep_blank_values=True) == [
("test1", "value1"),
@@ -1762,9 +1722,7 @@ def test_request_query_args_custom_parsing(app):
{"test1": ["value1"], "test2": [""], "test3": ["value3"]}
)
assert request.args == RequestParameters(
{"test1": ["value1"], "test3": ["value3"]}
)
assert request.args == RequestParameters({"test1": ["value1"], "test3": ["value3"]})
assert request.get_args(keep_blank_values=False) == RequestParameters(
{"test1": ["value1"], "test3": ["value3"]}
@@ -1777,9 +1735,7 @@ async def test_request_query_args_custom_parsing_asgi(app):
def handler(request):
return text("pass")
request, response = await app.asgi_client.get(
"/?test1=value1&test2=&test3=value3"
)
request, response = await app.asgi_client.get("/?test1=value1&test2=&test3=value3")
assert request.get_query_args(keep_blank_values=True) == [
("test1", "value1"),
@@ -1796,9 +1752,7 @@ async def test_request_query_args_custom_parsing_asgi(app):
{"test1": ["value1"], "test2": [""], "test3": ["value3"]}
)
assert request.args == RequestParameters(
{"test1": ["value1"], "test3": ["value3"]}
)
assert request.args == RequestParameters({"test1": ["value1"], "test3": ["value3"]})
assert request.get_args(keep_blank_values=False) == RequestParameters(
{"test1": ["value1"], "test3": ["value3"]}
@@ -1907,9 +1861,7 @@ def test_request_server_name_in_host_header(app):
def handler(request):
return text("OK")
request, response = app.test_client.get(
"/", headers={"Host": "my-server:5555"}
)
request, response = app.test_client.get("/", headers={"Host": "my-server:5555"})
assert request.server_name == "my-server"
request, response = app.test_client.get(
@@ -1917,9 +1869,7 @@ def test_request_server_name_in_host_header(app):
)
assert request.server_name == "[2a00:1450:400f:80c::200e]"
request, response = app.test_client.get(
"/", headers={"Host": "mal_formed"}
)
request, response = app.test_client.get("/", headers={"Host": "mal_formed"})
assert request.server_name == ""
@@ -1955,9 +1905,7 @@ def test_request_server_port_in_host_header(app):
def handler(request):
return text("OK")
request, response = app.test_client.get(
"/", headers={"Host": "my-server:5555"}
)
request, response = app.test_client.get("/", headers={"Host": "my-server:5555"})
assert request.server_port == 5555
request, response = app.test_client.get(
@@ -1965,9 +1913,7 @@ def test_request_server_port_in_host_header(app):
)
assert request.server_port == 5555
request, response = app.test_client.get(
"/", headers={"Host": "mal_formed:5555"}
)
request, response = app.test_client.get("/", headers={"Host": "mal_formed:5555"})
if PORT is None:
assert request.server_port != 5555
else:
@@ -2038,13 +1984,8 @@ def test_url_for_with_forwarded_request(app):
},
)
assert app.url_for("view_name") == "/another_view"
assert (
app.url_for("view_name", _external=True)
== "http://my-server/another_view"
)
assert (
request.url_for("view_name") == "https://my-server:6789/another_view"
)
assert app.url_for("view_name", _external=True) == "http://my-server/another_view"
assert request.url_for("view_name") == "https://my-server:6789/another_view"
request, response = app.test_client.get(
"/",
@@ -2159,10 +2100,7 @@ def test_url_for_without_server_name(app):
return text("url-for")
request, response = app.test_client.get("/sample")
assert (
response.json["url"]
== f"http://127.0.0.1:{request.server_port}/url-for"
)
assert response.json["url"] == f"http://127.0.0.1:{request.server_port}/url-for"
def test_safe_method_with_body_ignored(app):
@@ -2219,15 +2157,11 @@ def test_conflicting_body_methods_overload(app: Sanic):
@app.put("/p/", name="two")
@app.put("/p/<foo>", name="three")
async def put(request, foo=None):
return json(
{"name": request.route.name, "body": str(request.body), "foo": foo}
)
return json({"name": request.route.name, "body": str(request.body), "foo": foo})
@app.delete("/p/<foo>")
async def delete(request, foo):
return json(
{"name": request.route.name, "body": str(request.body), "foo": foo}
)
return json({"name": request.route.name, "body": str(request.body), "foo": foo})
payload = {"test": "OK"}
data = str(json_dumps(payload).encode())
@@ -2285,9 +2219,7 @@ def test_handler_overload(app: Sanic):
def handler(request, **kwargs):
return json(kwargs)
_, response = app.test_client.get(
"/long/sub/route/param_a/foo/param_b/bar"
)
_, response = app.test_client.get("/long/sub/route/param_a/foo/param_b/bar")
assert response.status == 200
assert response.json == {
"param_a": "foo",

View File

@@ -127,14 +127,10 @@ def test_response_content_length(app):
)
_, response = app.test_client.get("/response_with_space")
content_length_for_response_with_space = response.headers.get(
"Content-Length"
)
content_length_for_response_with_space = response.headers.get("Content-Length")
_, response = app.test_client.get("/response_without_space")
content_length_for_response_without_space = response.headers.get(
"Content-Length"
)
content_length_for_response_without_space = response.headers.get("Content-Length")
assert (
content_length_for_response_with_space
@@ -289,9 +285,7 @@ def test_stream_response_with_cookies(app):
cookies = CookieJar(headers)
cookies["test"] = "modified"
cookies["test"] = "pass"
response = await request.respond(
content_type="text/csv", headers=headers
)
response = await request.respond(content_type="text/csv", headers=headers)
await response.send("foo,")
await asyncio.sleep(0.001)
@@ -340,9 +334,7 @@ def get_file_last_modified_timestamp(
return (static_file_directory / file_name).stat().st_mtime
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
@pytest.mark.parametrize("status", [200, 401])
def test_file_response(app: Sanic, file_name, static_file_directory, status):
@app.route("/files/<filename>", methods=["GET"])
@@ -369,9 +361,7 @@ def test_file_response(app: Sanic, file_name, static_file_directory, status):
("python.png", "logo.png"),
],
)
def test_file_response_custom_filename(
app: Sanic, source, dest, static_file_directory
):
def test_file_response_custom_filename(app: Sanic, source, dest, static_file_directory):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request, filename):
file_path = os.path.join(static_file_directory, filename)
@@ -381,10 +371,7 @@ def test_file_response_custom_filename(
request, response = app.test_client.get(f"/files/{source}")
assert response.status == 200
assert response.body == get_file_content(static_file_directory, source)
assert (
response.headers["Content-Disposition"]
== f'attachment; filename="{dest}"'
)
assert response.headers["Content-Disposition"] == f'attachment; filename="{dest}"'
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"])
@@ -418,9 +405,7 @@ def test_file_head_response(app: Sanic, file_name, static_file_directory):
)
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_file_stream_response(app: Sanic, file_name, static_file_directory):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request, filename):
@@ -458,16 +443,11 @@ def test_file_stream_response_custom_filename(
request, response = app.test_client.get(f"/files/{source}")
assert response.status == 200
assert response.body == get_file_content(static_file_directory, source)
assert (
response.headers["Content-Disposition"]
== f'attachment; filename="{dest}"'
)
assert response.headers["Content-Disposition"] == f'attachment; filename="{dest}"'
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"])
def test_file_stream_head_response(
app: Sanic, file_name, static_file_directory
):
def test_file_stream_head_response(app: Sanic, file_name, static_file_directory):
@app.route("/files/<filename>", methods=["GET", "HEAD"])
async def file_route(request, filename):
file_path = os.path.join(static_file_directory, filename)
@@ -504,12 +484,8 @@ def test_file_stream_head_response(
)
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize(
"size,start,end", [(1024, 0, 1024), (4096, 1024, 8192)]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
@pytest.mark.parametrize("size,start,end", [(1024, 0, 1024), (4096, 1024, 8192)])
def test_file_stream_response_range(
app: Sanic, file_name, static_file_directory, size, start, end
):
@@ -700,8 +676,7 @@ def send_response_after_eof_should_fail(
)
error_msg2 = (
"Response stream was ended, no more "
"response data is allowed to be sent."
"Response stream was ended, no more " "response data is allowed to be sent."
)
with caplog.at_level(ERROR):
@@ -711,48 +686,30 @@ def send_response_after_eof_should_fail(
assert message_in_records(caplog.records, error_msg2)
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
def test_file_response_headers(
app: Sanic, file_name: str, static_file_directory: str
):
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_file_response_headers(app: Sanic, file_name: str, static_file_directory: str):
test_last_modified = datetime.now()
test_max_age = 10
test_expires = test_last_modified.timestamp() + test_max_age
@app.route("/files/cached/<filename>", methods=["GET"])
def file_route_cache(request: Request, filename: str):
file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
return file(
file_path, max_age=test_max_age, last_modified=test_last_modified
)
file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(file_path, max_age=test_max_age, last_modified=test_last_modified)
@app.route(
"/files/cached_default_last_modified/<filename>", methods=["GET"]
)
def file_route_cache_default_last_modified(
request: Request, filename: str
):
file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
@app.route("/files/cached_default_last_modified/<filename>", methods=["GET"])
def file_route_cache_default_last_modified(request: Request, filename: str):
file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(file_path, max_age=test_max_age)
@app.route("/files/no_cache/<filename>", methods=["GET"])
def file_route_no_cache(request: Request, filename: str):
file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(file_path)
@app.route("/files/no_store/<filename>", methods=["GET"])
def file_route_no_store(request: Request, filename: str):
file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(file_path, no_store=True)
_, response = app.test_client.get(f"/files/cached/{file_name}")
@@ -765,8 +722,7 @@ def test_file_response_headers(
)
assert (
"expires" in headers
and headers.get("expires")[:-6]
== formatdate(test_expires, usegmt=True)[:-6]
and headers.get("expires")[:-6] == formatdate(test_expires, usegmt=True)[:-6]
# [:-6] to allow at most 1 min difference
# It's minimal for cases like:
# Thu, 26 May 2022 05:36:59 GMT
@@ -774,9 +730,9 @@ def test_file_response_headers(
# Thu, 26 May 2022 05:37:00 GMT
)
assert response.status == 200
assert "last-modified" in headers and headers.get(
"last-modified"
) == formatdate(test_last_modified.timestamp(), usegmt=True)
assert "last-modified" in headers and headers.get("last-modified") == formatdate(
test_last_modified.timestamp(), usegmt=True
)
_, response = app.test_client.get(
f"/files/cached_default_last_modified/{file_name}"
@@ -785,23 +741,19 @@ def test_file_response_headers(
static_file_directory, file_name
)
headers = response.headers
assert "last-modified" in headers and headers.get(
"last-modified"
) == formatdate(file_last_modified, usegmt=True)
assert "last-modified" in headers and headers.get("last-modified") == formatdate(
file_last_modified, usegmt=True
)
assert response.status == 200
_, response = app.test_client.get(f"/files/no_cache/{file_name}")
headers = response.headers
assert "cache-control" in headers and "no-cache" == headers.get(
"cache-control"
)
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 "no-store" == headers.get(
"cache-control"
)
assert "cache-control" in headers and "no-store" == headers.get("cache-control")
assert response.status == 200
@@ -849,17 +801,13 @@ def test_file_validate(app: Sanic, static_file_directory: str):
file_path.unlink()
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_file_validating_invalid_header(
app: Sanic, file_name: str, static_file_directory: str
):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request: Request, filename: str):
handler_file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
handler_file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(
handler_file_path,
@@ -884,17 +832,13 @@ def test_file_validating_invalid_header(
assert response.body == get_file_content(static_file_directory, file_name)
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_file_validating_304_response(
app: Sanic, file_name: str, static_file_directory: str
):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request: Request, filename: str):
handler_file_path = (
Path(static_file_directory) / unquote(filename)
).absolute()
handler_file_path = (Path(static_file_directory) / unquote(filename)).absolute()
return file(
handler_file_path,
@@ -914,9 +858,7 @@ def test_file_validating_304_response(
assert response.body == b""
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_file_validating_304_response(
app: Sanic, file_name: str, static_file_directory: str
):
@@ -930,9 +872,7 @@ def test_file_validating_304_response(
_, response = app.test_client.get(
"/static",
headers={
"if-modified-since": formatdate(
last_modified.timestamp(), usegmt=True
)
"if-modified-since": formatdate(last_modified.timestamp(), usegmt=True)
},
)
assert response.status == 304

View File

@@ -163,9 +163,7 @@ def test_matching(path, headers, expected):
request = Request(path, headers, None, "GET", None, app)
try:
app.router.get(
request.path, request.method, request.headers.get("host")
)
app.router.get(request.path, request.method, request.headers.get("host"))
except NotFound:
response = 404
except Exception:
@@ -686,9 +684,7 @@ def test_websocket_route_with_subprotocols(app, subprotocols, expected):
results = ws.subprotocol
assert ws.subprotocol is not None
_, response = SanicTestClient(app).websocket(
"/ws", subprotocols=subprotocols
)
_, response = SanicTestClient(app).websocket("/ws", subprotocols=subprotocols)
assert response.opened is True
assert results == expected
@@ -1287,8 +1283,6 @@ async def test_duplicate_route_error(app):
async def handler_bar(request):
return text("...")
message = (
"Duplicate route names detected: test_duplicate_route_error.duped."
)
message = "Duplicate route names detected: test_duplicate_route_error.duped."
with pytest.raises(ServerError, match=message):
await app._startup()

View File

@@ -108,9 +108,7 @@ async def test_trigger_before_events_create_server(app):
async def init_db(app, loop):
app.ctx.db = MySanicDb()
srv = await app.create_server(
debug=True, return_asyncio_server=True, port=PORT
)
srv = await app.create_server(debug=True, return_asyncio_server=True, port=PORT)
await srv.startup()
await srv.before_start()
@@ -167,9 +165,7 @@ def test_create_server_trigger_events(app):
with closing(socket()) as sock:
sock.bind(("127.0.0.1", 0))
serv_coro = app.create_server(
return_asyncio_server=True, sock=sock, debug=True
)
serv_coro = app.create_server(return_asyncio_server=True, sock=sock, debug=True)
serv_task = asyncio.ensure_future(serv_coro, loop=loop)
server = loop.run_until_complete(serv_task)
loop.run_until_complete(server.startup())
@@ -199,9 +195,7 @@ async def test_missing_startup_raises_exception(app):
async def init_db(app, loop):
...
srv = await app.create_server(
debug=True, return_asyncio_server=True, port=PORT
)
srv = await app.create_server(debug=True, return_asyncio_server=True, port=PORT)
with pytest.raises(SanicException):
await srv.before_start()

View File

@@ -93,9 +93,7 @@ def test_sets_loop_policy_only_when_not_already_set(monkeypatch):
# Existing policy is not uvloop.EventLoopPolicy
get_event_loop_policy = Mock(return_value=None)
monkeypatch.setattr(
loop.asyncio, "get_event_loop_policy", get_event_loop_policy
)
monkeypatch.setattr(loop.asyncio, "get_event_loop_policy", get_event_loop_policy)
with patch("asyncio.set_event_loop_policy") as set_event_loop_policy:
loop.try_use_uvloop()
@@ -106,9 +104,7 @@ def test_sets_loop_policy_only_when_not_already_set(monkeypatch):
# Existing policy is uvloop.EventLoopPolicy
get_event_loop_policy = Mock(return_value=policy)
monkeypatch.setattr(
loop.asyncio, "get_event_loop_policy", get_event_loop_policy
)
monkeypatch.setattr(loop.asyncio, "get_event_loop_policy", get_event_loop_policy)
with patch("asyncio.set_event_loop_policy") as set_event_loop_policy:
loop.try_use_uvloop()

View File

@@ -26,9 +26,7 @@ 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
@@ -443,9 +441,7 @@ async def test_report_exception(app: Sanic):
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

View File

@@ -79,9 +79,7 @@ def hard_link(static_file_directory):
["test.file", "decode me.txt", "python.png", "symlink", "hard_link"],
)
def test_static_file(app, static_file_directory, file_name):
app.static(
"/testing.file", get_file_path(static_file_directory, file_name)
)
app.static("/testing.file", get_file_path(static_file_directory, file_name))
request, response = app.test_client.get("/testing.file")
assert response.status == 200
@@ -239,9 +237,7 @@ def test_static_content_range_correct(app, file_name, static_file_directory):
assert response.status == 206
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
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:20]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -259,9 +255,7 @@ def test_static_content_range_front(app, file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -279,9 +273,7 @@ def test_static_content_range_back(app, file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
-12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[-12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -305,9 +297,7 @@ def test_static_content_range_empty(
assert int(response.headers["Content-Length"]) == len(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(get_file_content(static_file_directory, file_name))
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"])
@@ -329,9 +319,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
):
def test_static_content_range_invalid_unit(app, file_name, static_file_directory):
app.static(
"/testing.file",
get_file_path(static_file_directory, file_name),
@@ -347,9 +335,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
):
def test_static_content_range_invalid_start(app, file_name, static_file_directory):
app.static(
"/testing.file",
get_file_path(static_file_directory, file_name),
@@ -365,9 +351,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
):
def test_static_content_range_invalid_end(app, file_name, static_file_directory):
app.static(
"/testing.file",
get_file_path(static_file_directory, file_name),
@@ -383,9 +367,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
):
def test_static_content_range_invalid_parameters(app, file_name, static_file_directory):
app.static(
"/testing.file",
get_file_path(static_file_directory, file_name),
@@ -399,9 +381,7 @@ def test_static_content_range_invalid_parameters(
assert "Invalid for Content Range parameters" in response.text
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_static_file_specified_host(app, static_file_directory, file_name):
app.static(
"/testing.file",
@@ -441,14 +421,10 @@ def test_static_stream_large_file(
assert response.body == get_file_content(static_file_directory, file_name)
@pytest.mark.parametrize(
"file_name", ["test.file", "decode me.txt", "python.png"]
)
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt", "python.png"])
def test_use_modified_since(app, static_file_directory, file_name):
file_stat = os.stat(get_file_path(static_file_directory, file_name))
modified_since = strftime(
"%a, %d %b %Y %H:%M:%S GMT", gmtime(file_stat.st_mtime)
)
modified_since = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(file_stat.st_mtime))
app.static(
"/testing.file",
@@ -547,32 +523,22 @@ async def test_multiple_statics_error(app, static_file_directory):
app.static("/file", get_file_path(static_file_directory, "test.file"))
app.static("/png", get_file_path(static_file_directory, "python.png"))
message = (
r"Duplicate route names detected: test_multiple_statics_error\.static"
)
message = r"Duplicate route names detected: test_multiple_statics_error\.static"
with pytest.raises(ServerError, match=message):
await app._startup()
def test_multiple_statics(app, static_file_directory):
app.static(
"/file", get_file_path(static_file_directory, "test.file"), name="file"
)
app.static(
"/png", get_file_path(static_file_directory, "python.png"), name="png"
)
app.static("/file", get_file_path(static_file_directory, "test.file"), name="file")
app.static("/png", get_file_path(static_file_directory, "python.png"), name="png")
_, response = app.test_client.get("/file")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.file"
)
assert response.body == get_file_content(static_file_directory, "test.file")
_, response = app.test_client.get("/png")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "python.png"
)
assert response.body == get_file_content(static_file_directory, "python.png")
@pytest.mark.asyncio
@@ -580,25 +546,23 @@ 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 detected: test_resource_type_default_error\.static"
)
with pytest.raises(ServerError, match=message):
await app._startup()
def test_resource_type_default(app, static_file_directory):
app.static("/static", static_file_directory, name="static")
app.static(
"/file", get_file_path(static_file_directory, "test.file"), name="file"
)
app.static("/file", get_file_path(static_file_directory, "test.file"), name="file")
_, response = app.test_client.get("/static")
assert response.status == 404
_, response = app.test_client.get("/file")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.file"
)
assert response.body == get_file_content(static_file_directory, "test.file")
def test_resource_type_file(app, static_file_directory):
@@ -610,9 +574,7 @@ def test_resource_type_file(app, static_file_directory):
_, response = app.test_client.get("/file")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.file"
)
assert response.body == get_file_content(static_file_directory, "test.file")
with pytest.raises(TypeError):
app.static("/static", static_file_directory, resource_type="file")
@@ -623,9 +585,7 @@ def test_resource_type_dir(app, static_file_directory):
_, response = app.test_client.get("/static/test.file")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.file"
)
assert response.body == get_file_content(static_file_directory, "test.file")
with pytest.raises(TypeError):
app.static(
@@ -666,12 +626,8 @@ def test_breakout(app: Sanic, static_file_directory: str):
assert response.status == 404
@pytest.mark.skipif(
sys.platform != "win32", reason="Block backslash on Windows only"
)
def test_double_backslash_prohibited_on_win32(
app: Sanic, static_file_directory: str
):
@pytest.mark.skipif(sys.platform != "win32", reason="Block backslash on Windows only")
def test_double_backslash_prohibited_on_win32(app: Sanic, static_file_directory: str):
app.static("/foo", static_file_directory)
_, response = app.test_client.get("/foo/static/..\\static/test.file")

View File

@@ -31,9 +31,7 @@ def test_static_index_single(app: Sanic, static_file_directory: str):
_, response = app.test_client.get("/static/")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.html"
)
assert response.body == get_file_content(static_file_directory, "test.html")
assert response.headers["Content-Type"] == "text/html"
@@ -53,15 +51,11 @@ def test_static_index_multiple(app: Sanic, static_file_directory: str):
_, response = app.test_client.get("/static/")
assert response.status == 200
assert response.body == get_file_content(
static_file_directory, "test.html"
)
assert response.body == get_file_content(static_file_directory, "test.html")
assert response.headers["Content-Type"] == "text/html"
def test_static_directory_view_and_index(
app: Sanic, static_file_directory: str
):
def test_static_directory_view_and_index(app: Sanic, static_file_directory: str):
app.static(
"/static",
static_file_directory,

View File

@@ -111,9 +111,7 @@ def replace_server_name(hostname):
server_hostname=None,
session=None,
):
return orig_wrap_bio(
self, incoming, outgoing, server_side, hostname, session
)
return orig_wrap_bio(self, incoming, outgoing, server_side, hostname, session)
orig_wrap_bio, ssl.SSLContext.wrap_bio = (
ssl.SSLContext.wrap_bio,
@@ -462,9 +460,7 @@ def test_logger_vhosts(caplog):
single_process=True,
)
logmsg = [
m for s, l, m in caplog.record_tuples if m.startswith("Certificate")
][0]
logmsg = [m for s, l, m in caplog.record_tuples if m.startswith("Certificate")][0]
assert logmsg == (
"Certificate vhosts: localhost, 127.0.0.1, 0:0:0:0:0:0:0:1, "
@@ -495,9 +491,7 @@ def test_mk_cert_creator_is_not_supported(app):
cert_creator = MkcertCreator(app, _default, _default)
with patch("subprocess.run") as run:
run.side_effect = Exception("")
with pytest.raises(
SanicException, match="Sanic is attempting to use mkcert"
):
with pytest.raises(SanicException, match="Sanic is attempting to use mkcert"):
cert_creator.check_supported()
@@ -535,9 +529,7 @@ def test_trustme_creator_is_supported(app, monkeypatch):
def test_trustme_creator_is_not_supported(app, monkeypatch):
monkeypatch.setattr(sanic.http.tls.creators, "TRUSTME_INSTALLED", False)
cert_creator = TrustmeCreator(app, _default, _default)
with pytest.raises(
SanicException, match="Sanic is attempting to use trustme"
):
with pytest.raises(SanicException, match="Sanic is attempting to use trustme"):
cert_creator.check_supported()
@@ -623,12 +615,8 @@ def test_get_ssl_context_only_mkcert(
):
app.state.mode = Mode.DEBUG
app.config.LOCAL_CERT_CREATOR = requirement
monkeypatch.setattr(
sanic.http.tls.creators, "MkcertCreator", MockMkcertCreator
)
monkeypatch.setattr(
sanic.http.tls.creators, "TrustmeCreator", MockTrustmeCreator
)
monkeypatch.setattr(sanic.http.tls.creators, "MkcertCreator", MockMkcertCreator)
monkeypatch.setattr(sanic.http.tls.creators, "TrustmeCreator", MockTrustmeCreator)
MockMkcertCreator.SUPPORTED = mk_supported
MockTrustmeCreator.SUPPORTED = trustme_supported

View File

@@ -23,9 +23,7 @@ from sanic.response import text
pytestmark = pytest.mark.skipif(os.name != "posix", reason="UNIX only")
SOCKPATH = "/tmp/sanictest.sock"
SOCKPATH2 = "/tmp/sanictest2.sock"
httpx_version = tuple(
map(int, httpx.__version__.strip(ascii_lowercase).split("."))
)
httpx_version = tuple(map(int, httpx.__version__.strip(ascii_lowercase).split(".")))
@pytest.fixture(autouse=True)

View File

@@ -35,9 +35,7 @@ URL_FOR_VALUE4 = f"http://{test_host}:{test_port}/myurl?arg1=v1#anchor"
def _generate_handlers_from_names(app, l):
for name in l:
# this is the easiest way to generate functions with dynamic names
exec(
f'@app.route(name)\ndef {name}(request):\n\treturn text("{name}")'
)
exec(f'@app.route(name)\ndef {name}(request):\n\treturn text("{name}")')
@pytest.fixture

View File

@@ -15,10 +15,7 @@ def test_routes_with_host(app):
assert app.url_for("hostindex") == "/"
assert app.url_for("hostpath") == "/path"
assert app.url_for("hostindex", _external=True) == "http://example.com/"
assert (
app.url_for("hostpath", _external=True)
== "http://path.example.com/path"
)
assert app.url_for("hostpath", _external=True) == "http://path.example.com/path"
def test_routes_with_multiple_hosts(app):
@@ -27,9 +24,7 @@ def test_routes_with_multiple_hosts(app):
pass
assert app.url_for("hostindex") == "/"
assert (
app.url_for("hostindex", _host="example.com") == "http://example.com/"
)
assert app.url_for("hostindex", _host="example.com") == "http://example.com/"
with pytest.raises(ValueError) as e:
assert app.url_for("hostindex", _external=True)

View File

@@ -36,9 +36,7 @@ def get_file_content(static_file_directory, file_name):
)
def test_static_file(static_file_directory, file_name):
app = Sanic("qq")
app.static(
"/testing.file", get_file_path(static_file_directory, file_name)
)
app.static("/testing.file", get_file_path(static_file_directory, file_name))
app.static(
"/testing2.file",
get_file_path(static_file_directory, file_name),
@@ -155,16 +153,10 @@ def test_static_directory(file_name, base_uri, static_file_directory):
app.router.reset()
app.blueprint(bp)
uri = app.url_for(
"static", name="test_bp_static.static", filename=file_name
)
uri2 = app.url_for(
"static", name="test_bp_static.static", filename="/" + file_name
)
uri = app.url_for("static", name="test_bp_static.static", filename=file_name)
uri2 = app.url_for("static", name="test_bp_static.static", filename="/" + file_name)
uri4 = app.url_for(
"static", name="test_bp_static.uploads", filename=file_name
)
uri4 = app.url_for("static", name="test_bp_static.uploads", filename=file_name)
uri5 = app.url_for(
"static", name="test_bp_static.uploads", filename="/" + file_name
)
@@ -213,9 +205,7 @@ def test_static_head_request(file_name, static_file_directory):
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
request, response = app.test_client.head(uri)
assert response.status == 200
@@ -253,27 +243,21 @@ def test_static_content_range_correct(file_name, static_file_directory):
assert response.status == 206
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
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:20]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
assert uri == app.url_for("test_bp_static.static")
request, response = app.test_client.get(uri, headers=headers)
assert response.status == 206
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
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:20]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -305,18 +289,14 @@ def test_static_content_range_front(file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
assert uri == app.url_for("test_bp_static.static")
assert uri == app.url_for("test_bp_static.static", filename="any")
@@ -324,9 +304,7 @@ def test_static_content_range_front(file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -358,18 +336,14 @@ def test_static_content_range_back(file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
-12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[-12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
assert uri == app.url_for("test_bp_static.static")
assert uri == app.url_for("test_bp_static.static", filename="any")
@@ -377,9 +351,7 @@ def test_static_content_range_back(file_name, static_file_directory):
assert response.status == 206
assert "Content-Length" in response.headers
assert "Content-Range" in response.headers
static_content = bytes(get_file_content(static_file_directory, file_name))[
-12:
]
static_content = bytes(get_file_content(static_file_directory, file_name))[-12:]
assert int(response.headers["Content-Length"]) == len(static_content)
assert response.body == static_content
@@ -413,16 +385,12 @@ def test_static_content_range_empty(file_name, static_file_directory):
assert int(response.headers["Content-Length"]) == len(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(get_file_content(static_file_directory, file_name))
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
assert uri == app.url_for("test_bp_static.static")
assert uri == app.url_for("test_bp_static.static", filename="any")
@@ -433,9 +401,7 @@ def test_static_content_range_empty(file_name, static_file_directory):
assert int(response.headers["Content-Length"]) == len(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(
get_file_content(static_file_directory, file_name)
)
assert response.body == bytes(get_file_content(static_file_directory, file_name))
@pytest.mark.parametrize("file_name", ["test.file", "decode me.txt"])
@@ -472,9 +438,7 @@ def test_static_content_range_error(app, file_name, static_file_directory):
# blueprint
uri = app.url_for("static", name="test_bp_static.static")
assert uri == "/bp/testing.file"
assert uri == app.url_for(
"static", name="test_bp_static.static", filename="any"
)
assert uri == app.url_for("static", name="test_bp_static.static", filename="any")
assert uri == app.url_for("test_bp_static.static")
assert uri == app.url_for("test_bp_static.static", filename="any")

View File

@@ -5,9 +5,7 @@ from websockets.client import WebSocketClientProtocol
from sanic import Request, Sanic, Websocket
MimicClientType = Callable[
[WebSocketClientProtocol], Coroutine[None, None, Any]
]
MimicClientType = Callable[[WebSocketClientProtocol], Coroutine[None, None, Any]]
@pytest.fixture
@@ -31,9 +29,7 @@ def test_ws_handler(
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"]
@@ -47,8 +43,6 @@ def test_ws_handler_async_for(
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"]

View File

@@ -22,9 +22,7 @@ class CustomRequest(Request[Sanic[CustomConfig, Foo], RequestContext]):
return ctx
app = Sanic(
"test", config=CustomConfig(), ctx=Foo(), request_class=CustomRequest
)
app = Sanic("test", config=CustomConfig(), ctx=Foo(), request_class=CustomRequest)
@app.get("/")

View File

@@ -92,9 +92,7 @@ def run_check(path_location: str) -> str:
),
),
)
def test_check_app_default(
path_location: str, expected: List[Tuple[str, int]]
) -> None:
def test_check_app_default(path_location: str, expected: List[Tuple[str, int]]) -> None:
output = run_check(f"samples/{path_location}")
for text, number in expected:

View File

@@ -127,9 +127,9 @@ def test_state_to_json():
def test_run_inspector_authentication():
inspector = Inspector(
Mock(), {}, {}, "", 0, "super-secret", Default(), Default()
)(False)
inspector = Inspector(Mock(), {}, {}, "", 0, "super-secret", Default(), Default())(
False
)
manager = TestManager(inspector.app)
_, response = manager.test_client.get("/")
assert response.status == 401

View File

@@ -62,9 +62,7 @@ def test_kill(os_mock: Mock):
@patch("sanic.worker.process.os")
@patch("sanic.worker.manager.os")
def test_shutdown_signal_send_kill(
manager_os_mock: Mock, process_os_mock: Mock
):
def test_shutdown_signal_send_kill(manager_os_mock: Mock, process_os_mock: Mock):
process = Mock()
process.pid = 1234
context = Mock()
@@ -124,9 +122,7 @@ def test_monitor_all(zero_downtime):
p2 = Mock()
sub = Mock()
incoming = (
"__ALL_PROCESSES__::STARTUP_FIRST"
if zero_downtime
else "__ALL_PROCESSES__:"
"__ALL_PROCESSES__::STARTUP_FIRST" if zero_downtime else "__ALL_PROCESSES__:"
)
sub.recv.side_effect = [incoming, ""]
context = Mock()
@@ -137,9 +133,7 @@ def test_monitor_all(zero_downtime):
manager.monitor()
restart_order = (
RestartOrder.STARTUP_FIRST
if zero_downtime
else RestartOrder.SHUTDOWN_FIRST
RestartOrder.STARTUP_FIRST if zero_downtime else RestartOrder.SHUTDOWN_FIRST
)
manager.restart.assert_called_once_with(
process_names=None,
@@ -167,9 +161,7 @@ def test_monitor_all_with_files(zero_downtime):
manager.monitor()
restart_order = (
RestartOrder.STARTUP_FIRST
if zero_downtime
else RestartOrder.SHUTDOWN_FIRST
RestartOrder.STARTUP_FIRST if zero_downtime else RestartOrder.SHUTDOWN_FIRST
)
manager.restart.assert_called_once_with(
process_names=None,
@@ -185,9 +177,7 @@ def test_monitor_one_process(zero_downtime):
p2 = Mock()
sub = Mock()
incoming = (
f"{p1.name}:foo,bar:STARTUP_FIRST"
if zero_downtime
else f"{p1.name}:foo,bar"
f"{p1.name}:foo,bar:STARTUP_FIRST" if zero_downtime else f"{p1.name}:foo,bar"
)
sub.recv.side_effect = [incoming, ""]
context = Mock()
@@ -198,9 +188,7 @@ def test_monitor_one_process(zero_downtime):
manager.monitor()
restart_order = (
RestartOrder.STARTUP_FIRST
if zero_downtime
else RestartOrder.SHUTDOWN_FIRST
RestartOrder.STARTUP_FIRST if zero_downtime else RestartOrder.SHUTDOWN_FIRST
)
manager.restart.assert_called_once_with(
process_names=[p1.name],

View File

@@ -154,9 +154,7 @@ def test_reload_delayed(monkeypatch):
monkeypatch.setattr(threading.Thread, "start", orig)
def test_reloader_triggers_start_stop_listeners(
app: Sanic, app_loader: AppLoader
):
def test_reloader_triggers_start_stop_listeners(app: Sanic, app_loader: AppLoader):
results = []
@app.reload_process_start

View File

@@ -43,21 +43,15 @@ def test_state_eq():
def test_state_keys():
assert list(gen_state(one=1, two=2).keys()) == list(
{"one": 1, "two": 2}.keys()
)
assert list(gen_state(one=1, two=2).keys()) == list({"one": 1, "two": 2}.keys())
def test_state_values():
assert list(gen_state(one=1, two=2).values()) == list(
{"one": 1, "two": 2}.values()
)
assert list(gen_state(one=1, two=2).values()) == list({"one": 1, "two": 2}.values())
def test_state_items():
assert list(gen_state(one=1, two=2).items()) == list(
{"one": 1, "two": 2}.items()
)
assert list(gen_state(one=1, two=2).items()) == list({"one": 1, "two": 2}.items())
def test_state_update():

View File

@@ -66,9 +66,7 @@ def test_has_multiplexer(app: Sanic):
Sanic.register_app(app)
with patch("sanic.worker.serve._serve_http_1"):
worker_serve(
**args(app, monitor_publisher=Mock(), worker_state=Mock())
)
worker_serve(**args(app, monitor_publisher=Mock(), worker_state=Mock()))
assert isinstance(app.multiplexer, WorkerMultiplexer)
del environ["SANIC_WORKER_NAME"]
@@ -102,9 +100,7 @@ def test_serve_app_factory(wm: Mock, mock_app):
@patch("sanic.mixins.startup.WorkerManager")
@pytest.mark.parametrize("config", (True, False))
def test_serve_with_inspector(
WorkerManager: Mock, mock_app: Mock, config: bool
):
def test_serve_with_inspector(WorkerManager: Mock, mock_app: Mock, config: bool):
Inspector = Mock()
mock_app.config.INSPECTOR = config
mock_app.inspector_class = Inspector