From 1cb1de8df9ae4f62aa362d5f064b65113c4ca230 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Valur=20J=C3=B3nsson?= Date: Wed, 22 Mar 2023 13:16:36 +0000 Subject: [PATCH] Add a similar missing-body test --- tests/protocols/test_websocket.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/protocols/test_websocket.py b/tests/protocols/test_websocket.py index 7a2252983..26e094d9f 100644 --- a/tests/protocols/test_websocket.py +++ b/tests/protocols/test_websocket.py @@ -1133,6 +1133,48 @@ async def websocket_session(url): await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}") +@pytest.mark.anyio +@pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) +@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) +async def test_server_reject_connection_with_missing_body( + ws_protocol_cls, http_protocol_cls, unused_tcp_port: int +): + async def app(scope, receive, send): + assert scope["type"] == "websocket" + assert "websocket.http.response" in scope["extensions"] + + # Pull up first recv message. + message = await receive() + assert message["type"] == "websocket.connect" + + message = { + "type": "websocket.http.response.start", + "status": 404, + "headers": [(b"Content-Length", b"0"), (b"Content-Type", b"text/plain")], + } + await send(message) + # no further message + + async def websocket_session(url): + with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: + async with websockets.client.connect(url): + pass # pragma: no cover + if ws_protocol_cls == WSProtocol: + assert exc_info.value.status_code == 404 + else: + assert exc_info.value.status_code == 500 + + config = Config( + app=app, + ws=ws_protocol_cls, + http=http_protocol_cls, + lifespan="off", + port=unused_tcp_port, + ) + async with run_server(config): + await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}") + + @pytest.mark.anyio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)