Skip to content

Commit 47f1a64

Browse files
authored
fix(postData): do not require content type when retrieving post data (microsoft#547)
1 parent a53df88 commit 47f1a64

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

playwright/_impl/_network.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,12 @@ def post_data_json(self) -> Optional[Any]:
8585
if not post_data:
8686
return None
8787
content_type = self.headers["content-type"]
88-
if not content_type:
89-
return None
9088
if content_type == "application/x-www-form-urlencoded":
9189
return dict(parse.parse_qsl(post_data))
92-
return json.loads(post_data)
90+
try:
91+
return json.loads(post_data)
92+
except Exception:
93+
raise Error(f"POST data is not a valid JSON object: {post_data}")
9394

9495
@property
9596
def post_data_buffer(self) -> Optional[bytes]:

tests/async/test_network.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,44 @@ async def test_should_be_undefined_when_there_is_no_post_data(page, server):
279279
assert response.request.post_data_json is None
280280

281281

282+
async def test_should_return_post_data_without_content_type(page, server):
283+
await page.goto(server.EMPTY_PAGE)
284+
async with page.expect_request("**/*") as request_info:
285+
await page.evaluate(
286+
"""({url}) => {
287+
const request = new Request(url, {
288+
method: 'POST',
289+
body: JSON.stringify({ value: 42 }),
290+
});
291+
request.headers.set('content-type', '');
292+
return fetch(request);
293+
}""",
294+
{"url": server.PREFIX + "/title.html"},
295+
)
296+
request = await request_info.value
297+
assert request.post_data_json == {"value": 42}
298+
299+
300+
async def test_should_throw_on_invalid_json_in_post_data(page, server):
301+
await page.goto(server.EMPTY_PAGE)
302+
async with page.expect_request("**/*") as request_info:
303+
await page.evaluate(
304+
"""({url}) => {
305+
const request = new Request(url, {
306+
method: 'POST',
307+
body: '<not a json>',
308+
});
309+
request.headers.set('content-type', '');
310+
return fetch(request);
311+
}""",
312+
{"url": server.PREFIX + "/title.html"},
313+
)
314+
request = await request_info.value
315+
with pytest.raises(Error) as exc_info:
316+
print(request.post_data_json)
317+
assert "POST data is not a valid JSON object: <not a json>" in str(exc_info.value)
318+
319+
282320
async def test_should_work_with_binary_post_data(page, server):
283321
await page.goto(server.EMPTY_PAGE)
284322
server.set_route("/post", lambda req: req.finish())

0 commit comments

Comments
 (0)