Files
live-hub-py/tests/test_middleware_websocket.py
T

93 lines
2.5 KiB
Python

"""纯 ASGI 中间件不能吞掉 WebSocket 生命周期。"""
from __future__ import annotations
import asyncio
from web.backend.main import SecurityHeadersMiddleware
from web.backend.session import SessionRenewalMiddleware
async def _websocket_app(scope, receive, send):
assert scope["type"] == "websocket"
await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": 1000})
def test_websocket_bypasses_http_middleware():
messages: list[dict] = []
async def send(message):
messages.append(message)
async def receive():
return {"type": "websocket.connect"}
scope = {
"type": "websocket",
"path": "/api/douyu/ws/test",
"headers": [],
}
wrapped = SessionRenewalMiddleware(SecurityHeadersMiddleware(_websocket_app))
asyncio.run(wrapped(scope, receive, send))
assert messages == [
{"type": "websocket.accept"},
{"type": "websocket.close", "code": 1000},
]
async def _http_app(scope, receive, send):
assert scope["type"] == "http"
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
(b"cache-control", b"no-store, max-age=0"),
(b"x-frame-options", b"SAMEORIGIN"),
],
}
)
await send({"type": "http.response.body", "body": b"ok"})
def _run_http(path: str) -> dict:
messages: list[dict] = []
async def send(message):
messages.append(message)
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
scope = {
"type": "http",
"method": "GET",
"path": path,
"headers": [],
"scheme": "http",
"server": ("testserver", 80),
"client": ("testclient", 123),
"query_string": b"",
}
asyncio.run(SecurityHeadersMiddleware(_http_app)(scope, receive, send))
return messages[0]
def test_http_response_keeps_application_cache_control():
message = _run_http("/api/accounts")
headers = dict(message["headers"])
assert headers[b"cache-control"] == b"no-store, max-age=0"
assert headers[b"x-frame-options"] == b"DENY"
assert headers[b"x-content-type-options"] == b"nosniff"
def test_asset_response_gets_immutable_cache_control():
message = _run_http("/assets/index-abc123.js")
headers = dict(message["headers"])
assert headers[b"cache-control"] == b"public, max-age=31536000, immutable"
assert headers[b"x-frame-options"] == b"DENY"