How to use test_should_accept_already_serialized_data_as_bytes_when_content_type_is_application_json method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_fetch_global.py

Source: test_fetch_global.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import asyncio
16import json
17import sys
18from pathlib import Path
19from typing import Any
20
21import pytest
22
23from playwright.async_api import APIResponse, Error, Playwright
24from tests.server import Server
25
26
27@pytest.mark.parametrize(
28    "method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
29)
30async def test_should_work(playwright: Playwright, method: str, server: Server):
31    request = await playwright.request.new_context()
32    response: APIResponse = await getattr(request, method)(
33        server.PREFIX + "/simple.json"
34    )
35    assert response.status == 200
36    assert response.status_text == "OK"
37    assert response.ok is True
38    assert response.url == server.PREFIX + "/simple.json"
39    assert response.headers["content-type"] == "application/json"
40    assert {
41        "name": "Content-Type",
42        "value": "application/json",
43    } in response.headers_array
44    assert await response.text() == ("" if method == "head" else '{"foo": "bar"}\n')
45
46
47async def test_should_dispose_global_request(playwright: Playwright, server: Server):
48    request = await playwright.request.new_context()
49    response = await request.get(server.PREFIX + "/simple.json")
50    assert await response.json() == {"foo": "bar"}
51    await response.dispose()
52    with pytest.raises(Error, match="Response has been disposed"):
53        await response.body()
54
55
56async def test_should_support_global_user_agent_option(
57    playwright: Playwright, server: Server
58):
59    request = await playwright.request.new_context(user_agent="My Agent")
60    response = await request.get(server.PREFIX + "/empty.html")
61    [request, _] = await asyncio.gather(
62        server.wait_for_request("/empty.html"),
63        request.get(server.EMPTY_PAGE),
64    )
65    assert response.ok is True
66    assert response.url == server.EMPTY_PAGE
67    assert request.getHeader("user-agent") == "My Agent"
68
69
70async def test_should_support_global_timeout_option(
71    playwright: Playwright, server: Server
72):
73    request = await playwright.request.new_context(timeout=1)
74    server.set_route("/empty.html", lambda req: None)
75    with pytest.raises(Error, match="Request timed out after 1ms"):
76        await request.get(server.EMPTY_PAGE)
77
78
79async def test_should_propagate_extra_http_headers_with_redirects(
80    playwright: Playwright, server: Server
81):
82    server.set_redirect("/a/redirect1", "/b/c/redirect2")
83    server.set_redirect("/b/c/redirect2", "/simple.json")
84    request = await playwright.request.new_context(
85        extra_http_headers={"My-Secret": "Value"}
86    )
87    [req1, req2, req3, _] = await asyncio.gather(
88        server.wait_for_request("/a/redirect1"),
89        server.wait_for_request("/b/c/redirect2"),
90        server.wait_for_request("/simple.json"),
91        request.get(f"{server.PREFIX}/a/redirect1"),
92    )
93    assert req1.getHeader("my-secret") == "Value"
94    assert req2.getHeader("my-secret") == "Value"
95    assert req3.getHeader("my-secret") == "Value"
96
97
98async def test_should_support_global_http_credentials_option(
99    playwright: Playwright, server: Server
100):
101    server.set_auth("/empty.html", "user", "pass")
102    request1 = await playwright.request.new_context()
103    response1 = await request1.get(server.EMPTY_PAGE)
104    assert response1.status == 401
105    await response1.dispose()
106
107    request2 = await playwright.request.new_context(
108        http_credentials={"username": "user", "password": "pass"}
109    )
110    response2 = await request2.get(server.EMPTY_PAGE)
111    assert response2.status == 200
112    assert response2.ok is True
113    await response2.dispose()
114
115
116async def test_should_return_error_with_wrong_credentials(
117    playwright: Playwright, server: Server
118):
119    server.set_auth("/empty.html", "user", "pass")
120    request = await playwright.request.new_context(
121        http_credentials={"username": "user", "password": "wrong"}
122    )
123    response = await request.get(server.EMPTY_PAGE)
124    assert response.status == 401
125    assert response.ok is False
126
127
128async def test_should_support_global_ignore_https_errors_option(
129    playwright: Playwright, https_server: Server
130):
131    request = await playwright.request.new_context(ignore_https_errors=True)
132    response = await request.get(https_server.EMPTY_PAGE)
133    assert response.status == 200
134    assert response.ok is True
135    assert response.url == https_server.EMPTY_PAGE
136    await response.dispose()
137
138
139async def test_should_resolve_url_relative_to_global_base_url_option(
140    playwright: Playwright, server: Server
141):
142    request = await playwright.request.new_context(base_url=server.PREFIX)
143    response = await request.get("/empty.html")
144    assert response.status == 200
145    assert response.ok is True
146    assert response.url == server.EMPTY_PAGE
147    await response.dispose()
148
149
150async def test_should_use_playwright_as_a_user_agent(
151    playwright: Playwright, server: Server
152):
153    request = await playwright.request.new_context()
154    [server_req, _] = await asyncio.gather(
155        server.wait_for_request("/empty.html"),
156        request.get(server.EMPTY_PAGE),
157    )
158    assert str(server_req.getHeader("User-Agent")).startswith("Playwright/")
159    await request.dispose()
160
161
162async def test_should_return_empty_body(playwright: Playwright, server: Server):
163    request = await playwright.request.new_context()
164    response = await request.get(server.EMPTY_PAGE)
165    body = await response.body()
166    assert len(body) == 0
167    assert await response.text() == ""
168    await request.dispose()
169    with pytest.raises(Error, match="Response has been disposed"):
170        await response.body()
171
172
173async def test_storage_state_should_round_trip_through_file(
174    playwright: Playwright, tmpdir: Path
175):
176    expected = {
177        "cookies": [
178            {
179                "name": "a",
180                "value": "b",
181                "domain": "a.b.one.com",
182                "path": "/",
183                "expires": -1,
184                "httpOnly": False,
185                "secure": False,
186                "sameSite": "Lax",
187            }
188        ],
189        "origins": [],
190    }
191    request = await playwright.request.new_context(storage_state=expected)
192    path = tmpdir / "storage-state.json"
193    actual = await request.storage_state(path=path)
194    assert actual == expected
195
196    written = path.read_text("utf8")
197    assert json.loads(written) == expected
198
199    request2 = await playwright.request.new_context(storage_state=path)
200    state2 = await request2.storage_state()
201    assert state2 == expected
202
203
204serialization_data = [
205    [{"foo": "bar"}],
206    [["foo", "bar", 2021]],
207    ["foo"],
208    [True],
209    [2021],
210]
211
212
213@pytest.mark.parametrize("serialization", serialization_data)
214async def test_should_json_stringify_body_when_content_type_is_application_json(
215    playwright: Playwright, server: Server, serialization: Any
216):
217    request = await playwright.request.new_context()
218    [req, _] = await asyncio.gather(
219        server.wait_for_request("/empty.html"),
220        request.post(
221            server.EMPTY_PAGE,
222            headers={"content-type": "application/json"},
223            data=serialization,
224        ),
225    )
226    body = req.post_body
227    assert body.decode() == json.dumps(serialization, separators=(",", ":"))
228    await request.dispose()
229
230
231@pytest.mark.parametrize("serialization", serialization_data)
232async def test_should_not_double_stringify_body_when_content_type_is_application_json(
233    playwright: Playwright, server: Server, serialization: Any
234):
235    request = await playwright.request.new_context()
236    stringified_value = json.dumps(serialization, separators=(",", ":"))
237    [req, _] = await asyncio.gather(
238        server.wait_for_request("/empty.html"),
239        request.post(
240            server.EMPTY_PAGE,
241            headers={"content-type": "application/json"},
242            data=stringified_value,
243        ),
244    )
245
246    body = req.post_body
247    assert body.decode() == stringified_value
248    await request.dispose()
249
250
251async def test_should_accept_already_serialized_data_as_bytes_when_content_type_is_application_json(
252    playwright: Playwright, server: Server
253):
254    request = await playwright.request.new_context()
255    stringified_value = json.dumps({"foo": "bar"}, separators=(",", ":")).encode()
256    [req, _] = await asyncio.gather(
257        server.wait_for_request("/empty.html"),
258        request.post(
259            server.EMPTY_PAGE,
260            headers={"content-type": "application/json"},
261            data=stringified_value,
262        ),
263    )
264    body = req.post_body
265    assert body == stringified_value
266    await request.dispose()
267
268
269async def test_should_contain_default_user_agent(
270    playwright: Playwright, server: Server
271):
272    request = await playwright.request.new_context()
273    [request, _] = await asyncio.gather(
274        server.wait_for_request("/empty.html"),
275        request.get(server.EMPTY_PAGE),
276    )
277    user_agent = request.getHeader("user-agent")
278    assert "python" in user_agent
279    assert f"{sys.version_info.major}.{sys.version_info.minor}" in user_agent
280
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)