From a1ee8b4f45594634117a7cee66ad13343fcd3373 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=E5=A4=8F=E6=82=A0=E7=84=B6?= <45480822+xiayouran@users.noreply.github.com> Date: Fri, 1 Dec 2023 21:23:06 +0800 Subject: [PATCH] Set `ensure_ascii=False` on `json.dumps()` for `WebSocket.send_json()` (#2341) Co-authored-by: Marcelo Trylesinski --- starlette/testclient.py | 2 +- starlette/websockets.py | 2 +- tests/test_websockets.py | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/starlette/testclient.py b/starlette/testclient.py index 4a750cd8..60ef322d 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -147,7 +147,7 @@ class WebSocketTestSession: def send_json(self, data: typing.Any, mode: str = "text") -> None: assert mode in ["text", "binary"] - text = json.dumps(data, separators=(",", ":")) + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) if mode == "text": self.send({"type": "websocket.receive", "text": text}) else: diff --git a/starlette/websockets.py b/starlette/websockets.py index 85956085..a34bc133 100644 --- a/starlette/websockets.py +++ b/starlette/websockets.py @@ -168,7 +168,7 @@ class WebSocket(HTTPConnection): async def send_json(self, data: typing.Any, mode: str = "text") -> None: if mode not in {"text", "binary"}: raise RuntimeError('The "mode" argument should be "text" or "binary".') - text = json.dumps(data, separators=(",", ":")) + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) if mode == "text": await self.send({"type": "websocket.send", "text": text}) else: diff --git a/tests/test_websockets.py b/tests/test_websockets.py index 65e16671..2b487633 100644 --- a/tests/test_websockets.py +++ b/tests/test_websockets.py @@ -39,6 +39,24 @@ def test_websocket_binary_json(test_client_factory): assert data == {"test": "data"} +def test_websocket_ensure_unicode_on_send_json( + test_client_factory: Callable[..., TestClient] +): + async def app(scope: Scope, receive: Receive, send: Send) -> None: + websocket = WebSocket(scope, receive=receive, send=send) + + await websocket.accept() + message = await websocket.receive_json(mode="text") + await websocket.send_json(message, mode="text") + await websocket.close() + + client = test_client_factory(app) + with client.websocket_connect("/123?a=abc") as websocket: + websocket.send_json({"test": "数据"}, mode="text") + data = websocket.receive_text() + assert data == '{"test":"数据"}' + + def test_websocket_query_params(test_client_factory): async def app(scope: Scope, receive: Receive, send: Send) -> None: websocket = WebSocket(scope, receive=receive, send=send) -- 2.47.3