]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Set `ensure_ascii=False` on `json.dumps()` for `WebSocket.send_json()` (#2341)
author夏悠然 <45480822+xiayouran@users.noreply.github.com>
Fri, 1 Dec 2023 13:23:06 +0000 (21:23 +0800)
committerGitHub <noreply@github.com>
Fri, 1 Dec 2023 13:23:06 +0000 (13:23 +0000)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
starlette/testclient.py
starlette/websockets.py
tests/test_websockets.py

index 4a750cd8cd8de139e425ee9c13355e44a0c9fb54..60ef322d19dd8cd18055e6cf830ef04a4d93af4b 100644 (file)
@@ -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:
index 85956085731281c22e5b7429c5c1b25bf862b04a..a34bc13391c9bf0f8546a6d186481f2958779c4b 100644 (file)
@@ -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:
index 65e16671debe4607bfd408246ef1f4f74c8b18aa..2b487633eb3ec71816d5e7d2de06ab3bb68b777f 100644 (file)
@@ -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)