How to use test_should_add_default_headers 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_browser_context.py

Source: test_fetch_browser_context.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
17from urllib.parse import parse_qs
18
19import pytest
20
21from playwright.async_api import BrowserContext, Error, Page
22from tests.server import Server
23
24
25async def test_get_should_work(context: BrowserContext, server: Server):
26    response = await context.request.get(server.PREFIX + "/simple.json")
27    assert response.url == server.PREFIX + "/simple.json"
28    assert response.status == 200
29    assert response.status_text == "OK"
30    assert response.ok is True
31    assert response.headers["content-type"] == "application/json"
32    assert {
33        "name": "Content-Type",
34        "value": "application/json",
35    } in response.headers_array
36    assert await response.text() == '{"foo": "bar"}\n'
37
38
39async def test_fetch_should_work(context: BrowserContext, server: Server):
40    response = await context.request.fetch(server.PREFIX + "/simple.json")
41    assert response.url == server.PREFIX + "/simple.json"
42    assert response.status == 200
43    assert response.status_text == "OK"
44    assert response.ok is True
45    assert response.headers["content-type"] == "application/json"
46    assert {
47        "name": "Content-Type",
48        "value": "application/json",
49    } in response.headers_array
50    assert await response.text() == '{"foo": "bar"}\n'
51
52
53async def test_should_throw_on_network_error(context: BrowserContext, server: Server):
54    server.set_route("/test", lambda request: request.transport.loseConnection())
55    with pytest.raises(Error, match="socket hang up"):
56        await context.request.fetch(server.PREFIX + "/test")
57
58
59async def test_should_add_session_cookies_to_request(
60    context: BrowserContext, server: Server
61):
62    await context.add_cookies(
63        [
64            {
65                "name": "username",
66                "value": "John Doe",
67                "url": server.EMPTY_PAGE,
68                "expires": -1,
69                "httpOnly": False,
70                "secure": False,
71                "sameSite": "Lax",
72            }
73        ]
74    )
75    [server_req, response] = await asyncio.gather(
76        server.wait_for_request("/empty.html"),
77        context.request.get(server.EMPTY_PAGE),
78    )
79    assert server_req.getHeader("Cookie") == "username=John Doe"
80
81
82@pytest.mark.parametrize(
83    "method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
84)
85async def test_should_support_query_params(
86    context: BrowserContext, server: Server, method: str
87):
88    expected_params = {"p1": "v1", "парам2": "знач2"}
89    [server_req, _] = await asyncio.gather(
90        server.wait_for_request("/empty.html"),
91        getattr(context.request, method)(
92            server.EMPTY_PAGE + "?p1=foo", params=expected_params
93        ),
94    )
95    assert server_req.args["p1".encode()][0].decode() == "v1"
96    assert len(server_req.args["p1".encode()]) == 1
97    assert server_req.args["парам2".encode()][0].decode() == "знач2"
98
99
100@pytest.mark.parametrize(
101    "method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
102)
103async def test_should_support_fail_on_status_code(
104    context: BrowserContext, server: Server, method: str
105):
106    with pytest.raises(Error, match="404 Not Found"):
107        await getattr(context.request, method)(
108            server.PREFIX + "/this-does-clearly-not-exist.html",
109            fail_on_status_code=True,
110        )
111
112
113@pytest.mark.parametrize(
114    "method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
115)
116async def test_should_support_ignore_https_errors_option(
117    context: BrowserContext, https_server: Server, method: str
118):
119    response = await getattr(context.request, method)(
120        https_server.EMPTY_PAGE, ignore_https_errors=True
121    )
122    assert response.ok
123    assert response.status == 200
124
125
126async def test_should_not_add_context_cookie_if_cookie_header_passed_as_parameter(
127    context: BrowserContext, server: Server
128):
129    await context.add_cookies(
130        [
131            {
132                "name": "username",
133                "value": "John Doe",
134                "url": server.EMPTY_PAGE,
135                "expires": -1,
136                "httpOnly": False,
137                "secure": False,
138                "sameSite": "Lax",
139            }
140        ]
141    )
142    [server_req, _] = await asyncio.gather(
143        server.wait_for_request("/empty.html"),
144        context.request.get(server.EMPTY_PAGE, headers={"Cookie": "foo=bar"}),
145    )
146    assert server_req.getHeader("Cookie") == "foo=bar"
147
148
149@pytest.mark.parametrize("method", ["delete", "patch", "post", "put"])
150async def test_should_support_post_data(
151    context: BrowserContext, method: str, server: Server
152):
153    async def support_post_data(fetch_data, request_post_data):
154        [request, response] = await asyncio.gather(
155            server.wait_for_request("/simple.json"),
156            getattr(context.request, method)(
157                server.PREFIX + "/simple.json", data=fetch_data
158            ),
159        )
160        assert request.method.decode() == method.upper()
161        assert request.post_body == request_post_data
162        assert response.status == 200
163        assert response.url == server.PREFIX + "/simple.json"
164        assert request.getHeader("Content-Length") == str(len(request.post_body))
165
166    await support_post_data("My request", "My request".encode())
167    await support_post_data(b"My request", "My request".encode())
168    await support_post_data(
169        ["my", "request"], json.dumps(["my", "request"], separators=(",", ":")).encode()
170    )
171    await support_post_data(
172        {"my": "request"}, json.dumps({"my": "request"}, separators=(",", ":")).encode()
173    )
174    with pytest.raises(Error, match="Unsupported 'data' type: <class 'function'>"):
175        await support_post_data(lambda: None, None)
176
177
178async def test_should_support_application_x_www_form_urlencoded(
179    context: BrowserContext, server: Server
180):
181    [request, response] = await asyncio.gather(
182        server.wait_for_request("/empty.html"),
183        context.request.post(
184            server.PREFIX + "/empty.html",
185            form={
186                "firstName": "John",
187                "lastName": "Doe",
188                "file": "f.js",
189            },
190        ),
191    )
192    assert request.method == b"POST"
193    assert request.getHeader("Content-Type") == "application/x-www-form-urlencoded"
194    body = request.post_body.decode()
195    assert request.getHeader("Content-Length") == str(len(body))
196    params = parse_qs(request.post_body)
197    assert params[b"firstName"] == [b"John"]
198    assert params[b"lastName"] == [b"Doe"]
199    assert params[b"file"] == [b"f.js"]
200
201
202async def test_should_support_multipart_form_data(
203    context: BrowserContext, server: Server
204):
205    file = {
206        "name": "f.js",
207        "mimeType": "text/javascript",
208        "buffer": b"var x = 10;\r\n;console.log(x);",
209    }
210    [request, response] = await asyncio.gather(
211        server.wait_for_request("/empty.html"),
212        context.request.post(
213            server.PREFIX + "/empty.html",
214            multipart={
215                "firstName": "John",
216                "lastName": "Doe",
217                "file": file,
218            },
219        ),
220    )
221    assert request.method == b"POST"
222    assert request.getHeader("Content-Type").startswith("multipart/form-data; ")
223    assert request.getHeader("Content-Length") == str(len(request.post_body))
224    assert request.args[b"firstName"] == [b"John"]
225    assert request.args[b"lastName"] == [b"Doe"]
226    assert request.args[b"file"][0] == file["buffer"]
227
228
229async def test_should_add_default_headers(
230    context: BrowserContext, page: Page, server: Server
231):
232    [request, response] = await asyncio.gather(
233        server.wait_for_request("/empty.html"),
234        context.request.get(server.EMPTY_PAGE),
235    )
236    assert request.getHeader("Accept") == "*/*"
237    assert request.getHeader("Accept-Encoding") == "gzip,deflate,br"
238    assert request.getHeader("User-Agent") == await page.evaluate(
239        "() => navigator.userAgent"
240    )
241
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)