Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion playwright/_impl/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -1384,7 +1384,43 @@ def headers_array(self) -> HeadersArray:

def _json_stringify(value: Any) -> str:
# JSON.stringify(value): no spaces, and no escapes for non-ASCII characters.
return json.dumps(value, allow_nan=False, ensure_ascii=False, separators=(",", ":"))
serialized = json.dumps(
value,
allow_nan=False,
ensure_ascii=False,
separators=(",", ":"),
)

# Python permits lone surrogates in strings, but UTF-8 does not.
# Match JSON.stringify(): escape unpaired surrogates and combine valid pairs.
result: List[str] = []
index = 0

while index < len(serialized):
codepoint = ord(serialized[index])

if 0xD800 <= codepoint <= 0xDBFF:
if index + 1 < len(serialized):
next_codepoint = ord(serialized[index + 1])
if 0xDC00 <= next_codepoint <= 0xDFFF:
combined = (
0x10000
+ ((codepoint - 0xD800) << 10)
+ (next_codepoint - 0xDC00)
)
result.append(chr(combined))
index += 2
continue

result.append(f"\\u{codepoint:04x}")
elif 0xDC00 <= codepoint <= 0xDFFF:
result.append(f"\\u{codepoint:04x}")
else:
result.append(serialized[index])

index += 1

return "".join(result)


def _js_typeof(value: Any) -> str:
Expand Down
38 changes: 38 additions & 0 deletions tests/async/python/test_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,41 @@ async def test_response_security_details_none_without_https(
assert response
security_details = await response.security_details()
assert security_details is None


async def test_route_fallback_should_serialize_json_with_surrogates(
page: Page, server: Server
) -> None:
await page.goto(server.EMPTY_PAGE)

post_data = {
"high": "\ud800",
"low": "\udfff",
"pair": "\ud83d\ude00",
"emoji": "😀",
"unicode": "é",
}

async def handler1(route: Route) -> None:
await route.continue_()

async def handler2(route: Route) -> None:
await route.fallback(post_data=post_data)

await page.route("**/*", handler1)
await page.route("**/*", handler2)

with server.expect_request("/sleep.zzz") as request_info:
await page.evaluate(
"() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"
)

expected = (
b'{"high":"\\ud800","low":"\\udfff",'
b'"pair":"\xf0\x9f\x98\x80","emoji":"\xf0\x9f\x98\x80",'
b'"unicode":"\xc3\xa9"}'
)

post_body = request_info.value.post_body
assert post_body is not None
assert post_body == expected