How to use test_should_report_downloads_with_accept_downloads_true 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_download.py

Source: test_download.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.
14import asyncio
15import os
16from asyncio.futures import Future
17from pathlib import Path
18from typing import Optional
19
20import pytest
21
22from playwright.async_api import Browser, Error, Page
23
24
25def assert_file_content(path, content):
26    with open(path, "r") as fd:
27        assert fd.read() == content
28
29
30@pytest.fixture(autouse=True)
31def after_each_hook(server):
32    def handle_download(request):
33        request.setHeader("Content-Type", "application/octet-stream")
34        request.setHeader("Content-Disposition", "attachment")
35        request.write(b"Hello world")
36        request.finish()
37
38    def handle_download_with_file_name(request):
39        request.setHeader("Content-Type", "application/octet-stream")
40        request.setHeader("Content-Disposition", "attachment; filename=file.txt")
41        request.write(b"Hello world")
42        request.finish()
43
44    server.set_route("/download", handle_download)
45    server.set_route("/downloadWithFilename", handle_download_with_file_name)
46    yield
47
48
49async def test_should_report_downloads_with_accept_downloads_false(page: Page, server):
50    await page.set_content(
51        f'<a href="{server.PREFIX}/downloadWithFilename">download</a>'
52    )
53    async with page.expect_download() as download_info:
54        await page.click("a")
55    download = await download_info.value
56    assert download.url == f"{server.PREFIX}/downloadWithFilename"
57    assert download.suggested_filename == "file.txt"
58    error: Optional[Error] = None
59    try:
60        await download.path()
61    except Error as exc:
62        error = exc
63    assert "accept_downloads" in await download.failure()
64    assert error
65    assert "accept_downloads: True" in error.message
66
67
68async def test_should_report_downloads_with_accept_downloads_true(browser, server):
69    page = await browser.new_page(accept_downloads=True)
70    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
71    async with page.expect_download() as download_info:
72        await page.click("a")
73    download = await download_info.value
74    path = await download.path()
75    assert os.path.isfile(path)
76    assert_file_content(path, "Hello world")
77    await page.close()
78
79
80async def test_should_save_to_user_specified_path(tmpdir: Path, browser, server):
81    page = await browser.new_page(accept_downloads=True)
82    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
83    async with page.expect_download() as download_info:
84        await page.click("a")
85    download = await download_info.value
86    user_path = tmpdir / "download.txt"
87    await download.save_as(user_path)
88    assert user_path.exists()
89    assert user_path.read_text("utf-8") == "Hello world"
90    await page.close()
91
92
93async def test_should_save_to_user_specified_path_without_updating_original_path(
94    tmpdir, browser, server
95):
96    page = await browser.new_page(accept_downloads=True)
97    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
98    async with page.expect_download() as download_info:
99        await page.click("a")
100    download = await download_info.value
101    user_path = tmpdir / "download.txt"
102    await download.save_as(user_path)
103    assert user_path.exists()
104    assert user_path.read_text("utf-8") == "Hello world"
105
106    originalPath = Path(await download.path())
107    assert originalPath.exists()
108    assert originalPath.read_text("utf-8") == "Hello world"
109    await page.close()
110
111
112async def test_should_save_to_two_different_paths_with_multiple_save_as_calls(
113    tmpdir, browser, server
114):
115    page = await browser.new_page(accept_downloads=True)
116    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
117    async with page.expect_download() as download_info:
118        await page.click("a")
119    download = await download_info.value
120    user_path = tmpdir / "download.txt"
121    await download.save_as(user_path)
122    assert user_path.exists()
123    assert user_path.read_text("utf-8") == "Hello world"
124
125    anotheruser_path = tmpdir / "download (2).txt"
126    await download.save_as(anotheruser_path)
127    assert anotheruser_path.exists()
128    assert anotheruser_path.read_text("utf-8") == "Hello world"
129    await page.close()
130
131
132async def test_should_save_to_overwritten_filepath(tmpdir: Path, browser, server):
133    page = await browser.new_page(accept_downloads=True)
134    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
135    async with page.expect_download() as download_info:
136        await page.click("a")
137    download = await download_info.value
138    user_path = tmpdir / "download.txt"
139    await download.save_as(user_path)
140    assert len(list(Path(tmpdir).glob("*.*"))) == 1
141    await download.save_as(user_path)
142    assert len(list(Path(tmpdir).glob("*.*"))) == 1
143    assert user_path.exists()
144    assert user_path.read_text("utf-8") == "Hello world"
145    await page.close()
146
147
148async def test_should_create_subdirectories_when_saving_to_non_existent_user_specified_path(
149    tmpdir, browser, server
150):
151    page = await browser.new_page(accept_downloads=True)
152    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
153    async with page.expect_download() as download_info:
154        await page.click("a")
155    download = await download_info.value
156    nested_path = tmpdir / "these" / "are" / "directories" / "download.txt"
157    await download.save_as(nested_path)
158    assert nested_path.exists()
159    assert nested_path.read_text("utf-8") == "Hello world"
160    await page.close()
161
162
163async def test_should_error_when_saving_with_downloads_disabled(
164    tmpdir, browser, server
165):
166    page = await browser.new_page(accept_downloads=False)
167    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
168    async with page.expect_download() as download_info:
169        await page.click("a")
170    download = await download_info.value
171    user_path = tmpdir / "download.txt"
172    with pytest.raises(Error) as exc:
173        await download.save_as(user_path)
174    assert (
175        "Pass { accept_downloads: True } when you are creating your browser context"
176        in exc.value.message
177    )
178    await page.close()
179
180
181async def test_should_error_when_saving_after_deletion(tmpdir, browser, server):
182    page = await browser.new_page(accept_downloads=True)
183    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
184    async with page.expect_download() as download_info:
185        await page.click("a")
186    download = await download_info.value
187    user_path = tmpdir / "download.txt"
188    await download.delete()
189    with pytest.raises(Error) as exc:
190        await download.save_as(user_path)
191    assert "Download already deleted. Save before deleting." in exc.value.message
192    await page.close()
193
194
195async def test_should_report_non_navigation_downloads(browser, server):
196    # Mac WebKit embedder does not download in this case, although Safari does.
197    def handle_download(request):
198        request.setHeader("Content-Type", "application/octet-stream")
199        request.write(b"Hello world")
200        request.finish()
201
202    server.set_route("/download", handle_download)
203
204    page = await browser.new_page(accept_downloads=True)
205    await page.goto(server.EMPTY_PAGE)
206    await page.set_content(
207        f'<a download="file.txt" href="{server.PREFIX}/download">download</a>'
208    )
209    async with page.expect_download() as download_info:
210        await page.click("a")
211    download = await download_info.value
212    assert download.suggested_filename == "file.txt"
213    path = await download.path()
214    assert os.path.exists(path)
215    assert_file_content(path, "Hello world")
216    await page.close()
217
218
219async def test_report_download_path_within_page_on_download_handler_for_files(
220    browser: Browser, server
221):
222    page = await browser.new_page(accept_downloads=True)
223    on_download_path: Future[str] = asyncio.Future()
224
225    async def on_download(download):
226        on_download_path.set_result(await download.path())
227
228    page.once(
229        "download",
230        lambda res: asyncio.create_task(on_download(res)),
231    )
232    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
233    await page.click("a")
234    path = await on_download_path
235    assert_file_content(path, "Hello world")
236    await page.close()
237
238
239async def test_download_report_download_path_within_page_on_handle_for_blobs(
240    browser, server
241):
242    page = await browser.new_page(accept_downloads=True)
243    on_download_path = asyncio.Future()
244
245    async def on_download(download):
246        on_download_path.set_result(await download.path())
247
248    page.once(
249        "download",
250        lambda res: asyncio.create_task(on_download(res)),
251    )
252
253    await page.goto(server.PREFIX + "/download-blob.html")
254    await page.click("a")
255    path = await on_download_path
256    assert_file_content(path, "Hello world")
257    await page.close()
258
259
260@pytest.mark.only_browser("chromium")
261async def test_should_report_alt_click_downloads(browser, server):
262    # Firefox does not download on alt-click by default.
263    # Our WebKit embedder does not download on alt-click, although Safari does.
264    def handle_download(request):
265        request.setHeader("Content-Type", "application/octet-stream")
266        request.write(b"Hello world")
267        request.finish()
268
269    server.set_route("/download", handle_download)
270
271    page = await browser.new_page(accept_downloads=True)
272    await page.goto(server.EMPTY_PAGE)
273    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
274    async with page.expect_download() as download_info:
275        await page.click("a", modifiers=["Alt"])
276    download = await download_info.value
277    path = await download.path()
278    assert os.path.exists(path)
279    assert_file_content(path, "Hello world")
280    await page.close()
281
282
283async def test_should_report_new_window_downloads(browser, server):
284    # TODO: - the test fails in headful Chromium as the popup page gets closed along
285    # with the session before download completed event arrives.
286    # - WebKit doesn't close the popup page
287    page = await browser.new_page(accept_downloads=True)
288    await page.set_content(
289        f'<a target=_blank href="{server.PREFIX}/download">download</a>'
290    )
291    async with page.expect_download() as download_info:
292        await page.click("a")
293    download = await download_info.value
294    path = await download.path()
295    assert os.path.exists(path)
296    await page.close()
297
298
299async def test_should_delete_file(browser, server):
300    page = await browser.new_page(accept_downloads=True)
301    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
302    async with page.expect_download() as download_info:
303        await page.click("a")
304    download = await download_info.value
305    path = await download.path()
306    assert os.path.exists(path)
307    await download.delete()
308    assert os.path.exists(path) is False
309    await page.close()
310
311
312async def test_should_delete_downloads_on_context_destruction(browser, server):
313    page = await browser.new_page(accept_downloads=True)
314    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
315    async with page.expect_download() as download_info:
316        await page.click("a")
317    download1 = await download_info.value
318    async with page.expect_download() as download_info:
319        await page.click("a")
320    download2 = await download_info.value
321    path1 = await download1.path()
322    path2 = await download2.path()
323    assert os.path.exists(path1)
324    assert os.path.exists(path2)
325    await page.context.close()
326    assert os.path.exists(path1) is False
327    assert os.path.exists(path2) is False
328
329
330async def test_should_delete_downloads_on_browser_gone(browser_factory, server):
331    browser = await browser_factory()
332    page = await browser.new_page(accept_downloads=True)
333    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
334    async with page.expect_download() as download_info:
335        await page.click("a")
336    download1 = await download_info.value
337    async with page.expect_download() as download_info:
338        await page.click("a")
339    download2 = await download_info.value
340    path1 = await download1.path()
341    path2 = await download2.path()
342    assert os.path.exists(path1)
343    assert os.path.exists(path2)
344    await browser.close()
345    assert os.path.exists(path1) is False
346    assert os.path.exists(path2) is False
347    assert os.path.exists(os.path.join(path1, "..")) is False
348
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)