Skip to content

Commit

Permalink
Set ensure_ascii=False on json.dumps() for WebSocket.send_json() (
Browse files Browse the repository at this point in the history
#2341)

Co-authored-by: Marcelo Trylesinski <[email protected]>
  • Loading branch information
xiayouran and Kludex authored Dec 1, 2023
1 parent 811dacc commit a1ee8b4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion starlette/testclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def send_bytes(self, data: bytes) -> None:

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:
Expand Down
2 changes: 1 addition & 1 deletion starlette/websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ async def send_bytes(self, data: bytes) -> None:
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:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
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)
Expand Down

0 comments on commit a1ee8b4

Please sign in to comment.