diff --git a/azure/functions/_http_wsgi.py b/azure/functions/_http_wsgi.py index d108bc54..fdba6d95 100644 --- a/azure/functions/_http_wsgi.py +++ b/azure/functions/_http_wsgi.py @@ -1,6 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. - from typing import Dict, List, Optional, Any import logging from io import BytesIO, StringIO @@ -192,13 +191,16 @@ def _handle(self, req, context): wsgi_request = WsgiRequest(req, context) environ = wsgi_request.to_environ(self._wsgi_error_buffer) wsgi_response = WsgiResponse.from_app(self._app, environ) - self._handle_errors() + self._handle_errors(wsgi_response) return wsgi_response.to_func_response() - def _handle_errors(self): + def _handle_errors(self, wsgi_response): if self._wsgi_error_buffer.tell() > 0: self._wsgi_error_buffer.seek(0) error_message = linesep.join( self._wsgi_error_buffer.readline() ) raise Exception(error_message) + + if wsgi_response._status_code >= 500: + raise Exception(b''.join(wsgi_response._buffer)) diff --git a/tests/test_http_wsgi.py b/tests/test_http_wsgi.py index 5723dfa4..701fc68e 100644 --- a/tests/test_http_wsgi.py +++ b/tests/test_http_wsgi.py @@ -4,6 +4,8 @@ import unittest from io import StringIO, BytesIO +import pytest + import azure.functions as func from azure.functions._abc import TraceContext, RetryContext from azure.functions._http import HttpResponseHeaders @@ -181,6 +183,20 @@ def main(req, context): self.assertEqual(func_response.status_code, 200) self.assertEqual(func_response.get_body(), b'sample string') + def test_middleware_handle_with_server_error_status_code(self): + """Test if the middleware can be used by exposing the .handle method, + specifically when the middleware is used as + def main(req, context): + return WsgiMiddleware(app).handle(req, context) + """ + app = self._generate_wsgi_app(status="500 Internal Server Error", + response_body=b'internal server error') + func_request = self._generate_func_request() + with pytest.raises(Exception) as exec_info: + func_response = WsgiMiddleware(app).handle(func_request) + self.assertEqual(func_response.status_code, 500) + self.assertEqual(exec_info.value.args[0], b'internal server error') + def test_middleware_wrapper(self): """Test if the middleware can be used by exposing the .main property, specifically when the middleware is used as