/
test_message_logger.py
53 lines (45 loc) 路 2.35 KB
/
test_message_logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import httpx
import pytest
from tests.middleware.test_logging import caplog_for_logger
from uvicorn._logging import TRACE_LOG_LEVEL
from uvicorn.middleware.message_logger import MessageLoggerMiddleware
@pytest.mark.anyio
async def test_message_logger(caplog):
async def app(scope, receive, send):
await receive()
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b"", "more_body": False})
with caplog_for_logger(caplog, "uvicorn.asgi"):
caplog.set_level(TRACE_LOG_LEVEL, logger="uvicorn.asgi")
caplog.set_level(TRACE_LOG_LEVEL)
app = MessageLoggerMiddleware(app)
async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
response = await client.get("/")
assert response.status_code == 200
messages = [record.msg % record.args for record in caplog.records]
assert sum(["ASGI [1] Started" in message for message in messages]) == 1
assert sum(["ASGI [1] Send" in message for message in messages]) == 2
assert sum(["ASGI [1] Receive" in message for message in messages]) == 1
assert sum(["ASGI [1] Completed" in message for message in messages]) == 1
assert (
sum(["ASGI [1] Raised exception" in message for message in messages]) == 0
)
@pytest.mark.anyio
async def test_message_logger_exc(caplog):
async def app(scope, receive, send):
raise RuntimeError()
with caplog_for_logger(caplog, "uvicorn.asgi"):
caplog.set_level(TRACE_LOG_LEVEL, logger="uvicorn.asgi")
caplog.set_level(TRACE_LOG_LEVEL)
app = MessageLoggerMiddleware(app)
async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
with pytest.raises(RuntimeError):
await client.get("/")
messages = [record.msg % record.args for record in caplog.records]
assert sum(["ASGI [1] Started" in message for message in messages]) == 1
assert sum(["ASGI [1] Send" in message for message in messages]) == 0
assert sum(["ASGI [1] Receive" in message for message in messages]) == 0
assert sum(["ASGI [1] Completed" in message for message in messages]) == 0
assert (
sum(["ASGI [1] Raised exception" in message for message in messages]) == 1
)