From 42af6e1af6be2169615058a310b41fb7a1d0219f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=2E=20K=C3=A4rkk=C3=A4inen?= Date: Wed, 25 Mar 2020 14:35:09 +0200 Subject: [PATCH] Add a check for request body functions and a test for NotImplementedError. --- sanic/app.py | 11 ++++++++++- tests/test_custom_request.py | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/sanic/app.py b/sanic/app.py index bf00f247..a02b40fa 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -22,6 +22,7 @@ from sanic.constants import HTTP_METHODS from sanic.exceptions import SanicException, ServerError, URLBuildError from sanic.handlers import ErrorHandler from sanic.log import LOGGING_CONFIG_DEFAULTS, error_logger, logger +from sanic.request import Request from sanic.response import BaseHTTPResponse, HTTPResponse from sanic.router import Router from sanic.server import ( @@ -61,7 +62,15 @@ class Sanic: ) frame_records = stack()[1] name = getmodulename(frame_records[1]) - + # Check for unsupported function on custom request objects + if request_class and any(hasattr(request_class, m) for m in ( + "body_init", "body_push", "body_finish" + )) and request_class.receive_body is Request.receive_body: + raise NotImplementedError( + "Request methods body_init, body_push and body_finish " + f"are no longer supported. {request_class!r} should " + "implement receive_body. It is okay to implement both APIs.", + ) # logging if configure_logging: logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS) diff --git a/tests/test_custom_request.py b/tests/test_custom_request.py index 8516f998..e1b46d26 100644 --- a/tests/test_custom_request.py +++ b/tests/test_custom_request.py @@ -1,10 +1,17 @@ from io import BytesIO +import pytest + from sanic import Sanic from sanic.request import Request from sanic.response import json_dumps, text +class DeprecCustomRequest(Request): + """Using old API should fail when receive_body is not implemented""" + def body_push(self, data): + pass + class CustomRequest(Request): """Alternative implementation for loading body (non-streaming handlers)""" async def receive_body(self): @@ -13,6 +20,14 @@ class CustomRequest(Request): buffer.write(data) self.body = buffer.getvalue().upper() buffer.close() + # Old API may be implemented but won't be used here + def body_push(self, data): + assert False + + +def test_deprecated_custom_request(): + with pytest.raises(NotImplementedError): + Sanic(request_class=DeprecCustomRequest) def test_custom_request(): app = Sanic(request_class=CustomRequest)