|
1 | 1 | import json
|
2 |
| -from typing import TYPE_CHECKING, Any |
| 2 | +from typing import TYPE_CHECKING, Any, Optional |
3 | 3 |
|
| 4 | +import pytest |
4 | 5 | from starlette.exceptions import HTTPException as StarletteHTTPException
|
5 | 6 |
|
6 |
| -from starlite import HTTPException, Request, Response, Starlite, get |
| 7 | +from starlite import ( |
| 8 | + HTTPException, |
| 9 | + LoggingConfig, |
| 10 | + Request, |
| 11 | + Response, |
| 12 | + Starlite, |
| 13 | + TestClient, |
| 14 | + get, |
| 15 | +) |
7 | 16 | from starlite.middleware.exceptions import ExceptionHandlerMiddleware
|
8 | 17 | from starlite.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
|
9 | 18 | from starlite.testing import create_test_client
|
10 | 19 |
|
11 | 20 | if TYPE_CHECKING:
|
| 21 | + from _pytest.logging import LogCaptureFixture |
| 22 | + |
12 | 23 | from starlite.datastructures import State
|
13 | 24 | from starlite.types import Scope
|
| 25 | + from starlite.types.callable_types import GetLogger |
14 | 26 |
|
15 | 27 |
|
16 | 28 | async def dummy_app(scope: Any, receive: Any, send: Any) -> None:
|
@@ -118,3 +130,35 @@ async def after_exception_hook_handler(exc: Exception, scope: "Scope", state: "S
|
118 | 130 | response = client.get("/test")
|
119 | 131 | assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
|
120 | 132 | assert client.app.state.called
|
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.parametrize( |
| 136 | + "debug,logging_config", |
| 137 | + [ |
| 138 | + (True, LoggingConfig()), |
| 139 | + (False, LoggingConfig()), |
| 140 | + (False, None), |
| 141 | + ], |
| 142 | +) |
| 143 | +def test_exception_handler_middleware_debug_logging( |
| 144 | + get_logger: "GetLogger", caplog: "LogCaptureFixture", debug: bool, logging_config: Optional[LoggingConfig] |
| 145 | +) -> None: |
| 146 | + @get("/test") |
| 147 | + def handler() -> None: |
| 148 | + raise ValueError("Test debug exception") |
| 149 | + |
| 150 | + app = Starlite([handler], logging_config=logging_config, debug=debug) |
| 151 | + |
| 152 | + with caplog.at_level("DEBUG", "starlite"), TestClient(app=app) as client: |
| 153 | + client.app.logger = get_logger("starlite") |
| 154 | + response = client.get("/test") |
| 155 | + assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR |
| 156 | + assert "Test debug exception" in response.text |
| 157 | + |
| 158 | + if debug and logging_config: |
| 159 | + assert len(caplog.records) == 1 |
| 160 | + assert caplog.records[0].levelname == "DEBUG" |
| 161 | + assert "exception raised for request to route" in caplog.records[0].message |
| 162 | + else: |
| 163 | + assert not caplog.records |
| 164 | + assert "exception raised for request to route" not in response.text |
0 commit comments