Skip to content

Commit

Permalink
Resolve headers on different renderers - Issue 2749 (#2774)
Browse files Browse the repository at this point in the history
* Resolve headers on different renderers - Issue 2749

* Make pretty
  • Loading branch information
ahopkins committed Jul 9, 2023
1 parent c17230e commit c21999a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
19 changes: 9 additions & 10 deletions sanic/errorpages.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,10 @@ def render(self) -> HTTPResponse:
self.full
if self.debug and not getattr(self.exception, "quiet", False)
else self.minimal
)
return output()
)()
output.status = self.status
output.headers.update(self.headers)
return output

def minimal(self) -> HTTPResponse: # noqa
"""
Expand Down Expand Up @@ -125,7 +127,7 @@ def full(self) -> HTTPResponse:
request=self.request,
exc=self.exception,
)
return html(page.render(), status=self.status, headers=self.headers)
return html(page.render())

def minimal(self) -> HTTPResponse:
return self.full()
Expand All @@ -146,8 +148,7 @@ def full(self) -> HTTPResponse:
text=self.text,
bar=("=" * len(self.title)),
body=self._generate_body(full=True),
),
status=self.status,
)
)

def minimal(self) -> HTTPResponse:
Expand All @@ -157,9 +158,7 @@ def minimal(self) -> HTTPResponse:
text=self.text,
bar=("=" * len(self.title)),
body=self._generate_body(full=False),
),
status=self.status,
headers=self.headers,
)
)

@property
Expand Down Expand Up @@ -218,11 +217,11 @@ class JSONRenderer(BaseRenderer):

def full(self) -> HTTPResponse:
output = self._generate_output(full=True)
return json(output, status=self.status, dumps=self.dumps)
return json(output, dumps=self.dumps)

def minimal(self) -> HTTPResponse:
output = self._generate_output(full=False)
return json(output, status=self.status, dumps=self.dumps)
return json(output, dumps=self.dumps)

def _generate_output(self, *, full):
output = {
Expand Down
23 changes: 23 additions & 0 deletions tests/test_errorpages.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,26 @@ class FakeObject:
]

assert logmsg == expected


@pytest.mark.parametrize(
"format,expected",
(
("html", "text/html; charset=utf-8"),
("text", "text/plain; charset=utf-8"),
("json", "application/json"),
),
)
def test_exception_header_on_renderers(app: Sanic, format, expected):
app.config.FALLBACK_ERROR_FORMAT = format

@app.get("/test")
def test(request):
raise SanicException(
"test", status_code=400, headers={"exception": "test"}
)

_, response = app.test_client.get("/test")
assert response.status == 400
assert response.headers.get("exception") == "test"
assert response.content_type == expected

0 comments on commit c21999a

Please sign in to comment.