Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge release 21.9.2 #2313

Merged
merged 6 commits into from Nov 17, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion sanic/app.py
Expand Up @@ -1627,7 +1627,9 @@ def signalize(self):
async def _startup(self):
self.signalize()
self.finalize()
ErrorHandler.finalize(self.error_handler)
ErrorHandler.finalize(
self.error_handler, fallback=self.config.FALLBACK_ERROR_FORMAT
)
TouchUp.run(self)

async def _server_event(
Expand Down
9 changes: 8 additions & 1 deletion sanic/handlers.py
Expand Up @@ -38,7 +38,14 @@ def __init__(
self.base = base

@classmethod
def finalize(cls, error_handler):
def finalize(cls, error_handler, fallback: Optional[str] = None):
if (
fallback
and fallback != "auto"
and error_handler.fallback == "auto"
):
error_handler.fallback = fallback

if not isinstance(error_handler, cls):
error_logger.warning(
f"Error handler is non-conforming: {type(error_handler)}"
Expand Down
29 changes: 29 additions & 0 deletions tests/test_errorpages.py
@@ -1,6 +1,7 @@
import pytest

from sanic import Sanic
from sanic.config import Config
from sanic.errorpages import HTMLRenderer, exception_response
from sanic.exceptions import NotFound, SanicException
from sanic.handlers import ErrorHandler
Expand Down Expand Up @@ -313,3 +314,31 @@ def test_setting_fallback_to_non_default_raise_warning(app):
app.config.FALLBACK_ERROR_FORMAT = "json"

assert app.error_handler.fallback == "json"


def test_allow_fallback_error_format_in_config_injection():
class MyConfig(Config):
FALLBACK_ERROR_FORMAT = "text"

app = Sanic("test", config=MyConfig())

@app.route("/error", methods=["GET", "POST"])
def err(request):
raise Exception("something went wrong")

request, response = app.test_client.get("/error")
assert request.app.error_handler.fallback == "text"
assert response.status == 500
assert response.content_type == "text/plain; charset=utf-8"


def test_allow_fallback_error_format_in_config_replacement(app):
class MyConfig(Config):
FALLBACK_ERROR_FORMAT = "text"

app.config = MyConfig()

request, response = app.test_client.get("/error")
assert request.app.error_handler.fallback == "text"
assert response.status == 500
assert response.content_type == "text/plain; charset=utf-8"