diff --git a/playwright/_impl/fetch.py b/playwright/_impl/fetch.py index 0eb073d8f..4c768b90a 100644 --- a/playwright/_impl/fetch.py +++ b/playwright/_impl/fetch.py @@ -26,13 +26,13 @@ - A binary is base64 on the channel. - `x || y` and `!x` on an object are None checks: an empty dict is truthy in JS. - assert(value, message) throws an Error with the message; here it is a raise. -- JSON.stringify() is _json_stringify(), which raises for NaN and Infinity, where - JSON.stringify() writes null. +- JSON.stringify() is _json_stringify(), which converts NaN and Infinity to null. """ import asyncio import base64 import json +import math import os from pathlib import Path from typing import ( @@ -835,10 +835,27 @@ def is_file_payload(value: Any) -> bool: def _json_stringify(value: Any, indent: Optional[int] = None) -> str: - # JSON.stringify(value, undefined, indent): no spaces without an indent, and no - # escapes of non-ASCII characters. NaN and Infinity raise a ValueError. + # JSON.stringify(value, undefined, indent): no spaces without an indent, no + # escapes of non-ASCII characters, and non-finite numbers become null. + + def replace_non_finite_numbers(item: Any) -> Any: + if isinstance(item, float) and not math.isfinite(item): + return None + if isinstance(item, dict): + return { + key: replace_non_finite_numbers(nested_value) + for key, nested_value in item.items() + } + if isinstance(item, list): + return [replace_non_finite_numbers(nested_value) for nested_value in item] + if isinstance(item, tuple): + return tuple( + replace_non_finite_numbers(nested_value) for nested_value in item + ) + return item + return json.dumps( - value, + replace_non_finite_numbers(value), allow_nan=False, ensure_ascii=False, indent=indent, diff --git a/tests/async/library/test_browsercontext_fetch.py b/tests/async/library/test_browsercontext_fetch.py index 4821a97e4..431dab23c 100644 --- a/tests/async/library/test_browsercontext_fetch.py +++ b/tests/async/library/test_browsercontext_fetch.py @@ -1325,6 +1325,30 @@ async def test_FE_157_should_encode_to_application_json_by_default( assert json.loads(body) == data +async def test_fetch_data_should_serialize_non_finite_numbers_as_null( + context: BrowserContext, server: Server +) -> None: + data = { + "nan": float("nan"), + "positiveInfinity": float("inf"), + "negativeInfinity": float("-inf"), + "nested": [float("nan"), {"value": float("inf")}], + } + + with server.expect_request("/empty.html") as request_info: + await context.request.post(server.EMPTY_PAGE, data=data) + + request = request_info.value + assert request.getHeader("content-type") == "application/json" + body = must(request.post_body).decode() + assert json.loads(body) == { + "nan": None, + "positiveInfinity": None, + "negativeInfinity": None, + "nested": [None, {"value": None}], + } + + def multipart_route( assetdir: Path, received: Dict[str, Any] ) -> Callable[[TestServerRequest], None]: