How to use test_sync_download 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_sync.py

Source: test_sync.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 os
16
17import pytest
18
19from playwright.sync_api import Browser, Error, Page, TimeoutError, sync_playwright
20
21
22def test_sync_query_selector(page):
23    page.set_content(
24        """
25    <h1 id="foo">Bar</h1>
26    """
27    )
28    assert (
29        page.query_selector("#foo").inner_text()
30        == page.query_selector("h1").inner_text()
31    )
32
33
34def test_sync_click(page):
35    page.set_content(
36        """
37    <button onclick="window.clicked=true">Bar</button>
38    """
39    )
40    page.click("text=Bar")
41    assert page.evaluate("()=>window.clicked")
42
43
44def test_sync_nested_query_selector(page):
45    page.set_content(
46        """
47    <div id="one">
48        <span class="two">
49            <label>
50                MyValue
51            </label>
52        </span>
53    </div>
54    """
55    )
56    e1 = page.query_selector("#one")
57    e2 = e1.query_selector(".two")
58    e3 = e2.query_selector("label")
59    assert e3.inner_text() == "MyValue"
60
61
62def test_sync_handle_multiple_pages(context):
63    page1 = context.new_page()
64    page2 = context.new_page()
65    assert len(context.pages) == 2
66    page1.set_content("one")
67    page2.set_content("two")
68    assert "one" in page1.content()
69    assert "two" in page2.content()
70    page1.close()
71    assert len(context.pages) == 1
72    page2.close()
73    assert len(context.pages) == 0
74    for page in [page1, page2]:
75        with pytest.raises(Error):
76            page.content()
77
78
79def test_sync_wait_for_event(page: Page, server):
80    with page.expect_event("popup", timeout=10000) as popup:
81        page.evaluate("(url) => window.open(url)", server.EMPTY_PAGE)
82    assert popup.value
83
84
85def test_sync_wait_for_event_raise(page):
86    with pytest.raises(Error):
87        with page.expect_event("popup", timeout=500) as popup:
88            assert False
89        assert popup.value is None
90
91
92def test_sync_make_existing_page_sync(page):
93    page = page
94    assert page.evaluate("() => ({'playwright': true})") == {"playwright": True}
95    page.set_content("<h1>myElement</h1>")
96    page.wait_for_selector("text=myElement")
97
98
99def test_sync_network_events(page, server):
100    server.set_route(
101        "/hello-world",
102        lambda request: (
103            request.setHeader("Content-Type", "text/plain"),
104            request.write(b"Hello world"),
105            request.finish(),
106        ),
107    )
108    page.goto(server.EMPTY_PAGE)
109    messages = []
110    page.on(
111        "request", lambda request: messages.append(f">>{request.method}{request.url}")
112    )
113    page.on(
114        "response",
115        lambda response: messages.append(f"<<{response.status}{response.url}"),
116    )
117    response = page.evaluate("""async ()=> (await fetch("/hello-world")).text()""")
118    assert response == "Hello world"
119    assert messages == [
120        f">>GET{server.PREFIX}/hello-world",
121        f"<<200{server.PREFIX}/hello-world",
122    ]
123
124
125def test_console_should_work(page):
126    messages = []
127    page.once("console", lambda m: messages.append(m))
128    page.evaluate('() => console.log("hello", 5, {foo: "bar"})'),
129    assert len(messages) == 1
130    message = messages[0]
131    assert message.text == "hello 5 [email protected]"
132    assert str(message) == "hello 5 [email protected]"
133    assert message.type == "log"
134    assert message.args[0].json_value() == "hello"
135    assert message.args[1].json_value() == 5
136    assert message.args[2].json_value() == {"foo": "bar"}
137
138
139def test_sync_download(browser: Browser, server):
140    server.set_route(
141        "/downloadWithFilename",
142        lambda request: (
143            request.setHeader("Content-Type", "application/octet-stream"),
144            request.setHeader("Content-Disposition", "attachment; filename=file.txt"),
145            request.write(b"Hello world"),
146            request.finish(),
147        ),
148    )
149    page = browser.new_page(accept_downloads=True)
150    page.set_content(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')
151
152    with page.expect_event("download") as download:
153        page.click("a")
154    assert download.value
155    assert download.value.suggested_filename == "file.txt"
156    path = download.value.path()
157    assert os.path.isfile(path)
158    with open(path, "r") as fd:
159        assert fd.read() == "Hello world"
160    page.close()
161
162
163def test_sync_workers_page_workers(page: Page, server):
164    with page.expect_event("worker") as event_worker:
165        page.goto(server.PREFIX + "/worker/worker.html")
166    assert event_worker.value
167    worker = page.workers[0]
168    assert "worker.js" in worker.url
169
170    assert worker.evaluate('() => self["workerFunction"]()') == "worker function result"
171
172    page.goto(server.EMPTY_PAGE)
173    assert len(page.workers) == 0
174
175
176def test_sync_playwright_multiple_times():
177    with pytest.raises(Error) as exc:
178        with sync_playwright() as pw:
179            assert pw.chromium
180    assert (
181        "It looks like you are using Playwright Sync API inside the asyncio loop."
182        in exc.value.message
183    )
184
185
186def test_sync_set_default_timeout(page):
187    page.set_default_timeout(1)
188    with pytest.raises(TimeoutError) as exc:
189        page.wait_for_function("false")
190    assert "Timeout 1ms exceeded." in exc.value.message
191
192
193def test_close_should_reject_all_promises(context):
194    new_page = context.new_page()
195    with pytest.raises(Error) as exc_info:
196        new_page._gather(
197            lambda: new_page.evaluate("() => new Promise(r => {})"),
198            lambda: new_page.close(),
199        )
200    assert "Protocol error" in exc_info.value.message
201
202
203def test_expect_response_should_work(page: Page, server):
204    with page.expect_response("**/*") as resp:
205        page.goto(server.EMPTY_PAGE)
206    assert resp.value
207    assert resp.value.url == server.EMPTY_PAGE
208    assert resp.value.status == 200
209    assert resp.value.ok
210    assert resp.value.request
211
Full Screen

test_cli.py

Source: test_cli.py Github

copy
1import argparse
2import os
3import subprocess
4import sys
5from glob import glob
6from pathlib import Path
7from unittest.mock import patch
8
9import pytest
10
11from pyproj.__main__ import main
12from pyproj.datadir import append_data_dir, get_data_dir, get_user_data_dir
13from pyproj.sync import _load_grid_geojson
14from test.conftest import grids_available, proj_env, tmp_chdir
15
16PYPROJ_CLI_ENDPONTS = pytest.mark.parametrize(
17    "input_command", [["pyproj"], [sys.executable, "-m", "pyproj"]]
18)
19
20
21@pytest.mark.cli
22@PYPROJ_CLI_ENDPONTS
23def test_main(input_command, tmpdir):
24    with tmp_chdir(str(tmpdir)):
25        output = subprocess.check_output(
26            input_command, stderr=subprocess.STDOUT
27        ).decode("utf-8")
28    assert "pyproj version:" in output
29    assert "PROJ version:" in output
30    assert "-v, --verbose  Show verbose debugging version information." in output
31
32
33@pytest.mark.cli
34@PYPROJ_CLI_ENDPONTS
35@pytest.mark.parametrize("option", ["-v", "--verbose"])
36def test_main__verbose(input_command, option, tmpdir):
37    with tmp_chdir(str(tmpdir)):
38        output = subprocess.check_output(
39            input_command + [option], stderr=subprocess.STDOUT
40        ).decode("utf-8")
41    assert "pyproj:" in output
42    assert "PROJ:" in output
43    assert "data dir" in output
44    assert "user_data_dir" in output
45    assert "System" in output
46    assert "python" in output
47    assert "Python deps" in output
48    assert "-v, --verbose " not in output
49
50
51@pytest.mark.cli
52@PYPROJ_CLI_ENDPONTS
53@pytest.mark.parametrize("option", [["-h"], []])
54def test_sync(input_command, option, tmpdir):
55    with tmp_chdir(str(tmpdir)):
56        output = subprocess.check_output(
57            input_command + ["sync"] + option, stderr=subprocess.STDOUT
58        ).decode("utf-8")
59    assert (
60        "Tool for synchronizing PROJ datum and transformation support data." in output
61    )
62    assert "--bbox" in output
63    assert "--spatial-test" in output
64    assert "--source-id" in output
65    assert "--area-of-use" in output
66    assert "--file" in output
67    assert "--exclude-world-coverage" in output
68    assert "--include-already-downloaded" in output
69    assert "--list-files" in output
70    assert "--system-directory" in output
71    assert "--target-directory" in output
72    assert "-v, --verbose" in output
73
74
75def _check_list_files_header(lines):
76    assert lines[0].rstrip("\r") == "filename | source_id | area_of_use"
77    assert lines[1].rstrip("\r") == "----------------------------------"
78
79
80@pytest.mark.cli
81@pytest.mark.network
82@PYPROJ_CLI_ENDPONTS
83def test_sync__source_id__list(input_command, tmpdir):
84    with tmp_chdir(str(tmpdir)):
85        output = subprocess.check_output(
86            input_command
87            + [
88                "sync",
89                "--source-id",
90                "fr_ign",
91                "--list-files",
92                "--include-already-downloaded",
93            ],
94            stderr=subprocess.STDOUT,
95        ).decode("utf-8")
96    lines = output.strip().split("\n")
97    assert len(lines) > 2
98    _check_list_files_header(lines)
99    for line in lines[2:]:
100        assert "fr_ign" == line.split("|")[1].strip()
101
102
103@pytest.mark.cli
104@pytest.mark.network
105@PYPROJ_CLI_ENDPONTS
106def test_sync__area_of_use__list(input_command, tmpdir):
107    with tmp_chdir(str(tmpdir)):
108        output = subprocess.check_output(
109            input_command
110            + [
111                "sync",
112                "--area-of-use",
113                "France",
114                "--list-files",
115                "--include-already-downloaded",
116            ],
117            stderr=subprocess.STDOUT,
118        ).decode("utf-8")
119    lines = output.strip().split("\n")
120    assert len(lines) > 2
121    _check_list_files_header(lines)
122    for line in lines[2:]:
123        assert "France" in line.split("|")[-1]
124
125
126@pytest.mark.cli
127@pytest.mark.network
128@PYPROJ_CLI_ENDPONTS
129def test_sync__file__list(input_command, tmpdir):
130    with tmp_chdir(str(tmpdir)):
131        output = subprocess.check_output(
132            input_command
133            + [
134                "sync",
135                "--file",
136                "ntf_r93",
137                "--list-files",
138                "--include-already-downloaded",
139            ],
140            stderr=subprocess.STDOUT,
141        ).decode("utf-8")
142    lines = output.strip().split("\n")
143    assert len(lines) > 2
144    _check_list_files_header(lines)
145    for line in lines[2:]:
146        assert "ntf_r93" in line.split("|")[0]
147
148
149@pytest.mark.cli
150@pytest.mark.network
151@PYPROJ_CLI_ENDPONTS
152def test_sync__bbox__list(input_command, tmpdir):
153    with tmp_chdir(str(tmpdir)):
154        output = subprocess.check_output(
155            input_command
156            + [
157                "sync",
158                "--bbox",
159                "2,49,3,50",
160                "--list-files",
161                "--include-already-downloaded",
162            ],
163            stderr=subprocess.STDOUT,
164        ).decode("utf-8")
165    lines = output.strip().split("\n")
166    assert len(lines) > 2
167    _check_list_files_header(lines)
168    assert " | be_ign | " in output
169    assert " | us_nga | " in output
170    assert " | fr_ign | " in output
171
172
173@pytest.mark.cli
174@pytest.mark.network
175@PYPROJ_CLI_ENDPONTS
176def test_sync__bbox__list__exclude_world_coverage(input_command, tmpdir):
177    with tmp_chdir(str(tmpdir)):
178        output = subprocess.check_output(
179            input_command
180            + [
181                "sync",
182                "--bbox",
183                "2,49,3,50",
184                "--exclude-world-coverage",
185                "--list-files",
186                "--include-already-downloaded",
187            ],
188            stderr=subprocess.STDOUT,
189        ).decode("utf-8")
190    lines = output.strip().split("\n")
191    assert len(lines) > 2
192    _check_list_files_header(lines)
193    assert " | be_ign | " in output
194    assert " | us_nga | " not in output
195    assert " | fr_ign | " in output
196
197
198@pytest.mark.cli
199@PYPROJ_CLI_ENDPONTS
200@pytest.mark.parametrize(
201    "extra_arg",
202    [
203        "--list-files",
204        "--source-id",
205        "--area-of-use",
206        "--bbox",
207        "--list-files",
208        "--file",
209    ],
210)
211def test_sync__all__exclusive_error(input_command, extra_arg, tmpdir):
212    with tmp_chdir(str(tmpdir)), pytest.raises(subprocess.CalledProcessError):
213        subprocess.check_output(
214            input_command + ["sync", "--all", extra_arg], stderr=subprocess.STDOUT
215        )
216
217
218@pytest.mark.network
219@patch(
220    "pyproj.__main__.parser.parse_args",
221    return_value=argparse.Namespace(
222        bbox=None,
223        list_files=False,
224        file="ntf_r93",
225        all=False,
226        source_id=None,
227        area_of_use=None,
228        verbose=False,
229        target_directory=None,
230        system_directory=False,
231        spatial_test="intersects",
232        exclude_world_coverage=False,
233        include_already_downloaded=True,
234    ),
235)
236@patch("pyproj.__main__._download_resource_file")
237def test_sync_download(download_mock, parse_args_mock):
238    main()
239    download_mock.assert_called_with(
240        directory=get_user_data_dir(),
241        file_url="https://cdn.proj.org/fr_ign_ntf_r93.tif",
242        sha256="0aa738b3e00fd2d64f8e3cd0e76034d4792374624fa0e133922433c9491bbf2a",
243        short_name="fr_ign_ntf_r93.tif",
244        verbose=False,
245    )
246
247
248@pytest.mark.network
249@patch(
250    "pyproj.__main__.parser.parse_args",
251    return_value=argparse.Namespace(
252        bbox=None,
253        list_files=False,
254        file="ntf_r93",
255        all=False,
256        source_id=None,
257        area_of_use=None,
258        verbose=True,
259        target_directory="test_directory",
260        system_directory=False,
261        spatial_test="intersects",
262        exclude_world_coverage=False,
263        include_already_downloaded=True,
264    ),
265)
266@patch("pyproj.__main__._download_resource_file")
267@patch("pyproj.sync._load_grid_geojson")
268def test_sync_download__directory(
269    load_grid_geojson_mock, download_mock, parse_args_mock
270):
271    load_grid_geojson_mock.return_value = _load_grid_geojson()
272    main()
273    download_mock.assert_called_with(
274        directory="test_directory",
275        file_url="https://cdn.proj.org/fr_ign_ntf_r93.tif",
276        sha256="0aa738b3e00fd2d64f8e3cd0e76034d4792374624fa0e133922433c9491bbf2a",
277        short_name="fr_ign_ntf_r93.tif",
278        verbose=True,
279    )
280    load_grid_geojson_mock.assert_called_with(target_directory="test_directory")
281
282
283@pytest.mark.network
284@patch(
285    "pyproj.__main__.parser.parse_args",
286    return_value=argparse.Namespace(
287        bbox=None,
288        list_files=False,
289        file="ntf_r93",
290        all=False,
291        source_id=None,
292        area_of_use=None,
293        verbose=True,
294        target_directory=None,
295        system_directory=True,
296        spatial_test="intersects",
297        exclude_world_coverage=False,
298        include_already_downloaded=True,
299    ),
300)
301@patch("pyproj.__main__._download_resource_file")
302@patch("pyproj.sync._load_grid_geojson")
303def test_sync_download__system_directory(
304    load_grid_geojson_mock, download_mock, parse_args_mock
305):
306    load_grid_geojson_mock.return_value = _load_grid_geojson()
307    main()
308    datadir = get_data_dir().split(os.path.sep)[0]
309    download_mock.assert_called_with(
310        directory=datadir,
311        file_url="https://cdn.proj.org/fr_ign_ntf_r93.tif",
312        sha256="0aa738b3e00fd2d64f8e3cd0e76034d4792374624fa0e133922433c9491bbf2a",
313        short_name="fr_ign_ntf_r93.tif",
314        verbose=True,
315    )
316    load_grid_geojson_mock.assert_called_with(target_directory=datadir)
317
318
319@pytest.mark.network
320@patch("pyproj.__main__.parser.parse_args")
321def test_sync__download_grids(parse_args_mock, tmp_path, capsys):
322    parse_args_mock.return_value = argparse.Namespace(
323        bbox=None,
324        list_files=False,
325        file="us_noaa_alaska",
326        all=False,
327        source_id=None,
328        area_of_use=None,
329        verbose=True,
330        target_directory=str(tmp_path),
331        system_directory=False,
332        spatial_test="intersects",
333        exclude_world_coverage=False,
334        include_already_downloaded=False,
335    )
336    main()
337    captured = capsys.readouterr()
338    paths = sorted(Path(path).name for path in glob(str(tmp_path.joinpath("*"))))
339    if grids_available("us_noaa_alaska.tif", check_network=False):
340        assert paths == ["files.geojson"]
341        assert captured.out == ""
342    else:
343        assert paths == ["files.geojson", "us_noaa_alaska.tif"]
344        assert captured.out == "Downloading: https://cdn.proj.org/us_noaa_alaska.tif\n"
345    # make sure not downloaded again
346    with proj_env():
347        append_data_dir(str(tmp_path))
348        main()
349        captured = capsys.readouterr()
350        assert captured.out == ""
351
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)