Skip to content

Commit fdf2759

Browse files
authored
tests: added geolocation tests (microsoft#128)
1 parent 73442f7 commit fdf2759

File tree

5 files changed

+186
-7
lines changed

5 files changed

+186
-7
lines changed

playwright/browser_context.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
TimeoutSettings,
2828
URLMatch,
2929
URLMatcher,
30+
locals_to_params,
3031
)
3132
from playwright.network import Request, Route, serialize_headers
3233
from playwright.page import BindingCall, Page
@@ -119,15 +120,13 @@ async def clearCookies(self) -> None:
119120
async def grantPermissions(
120121
self, permissions: List[str], origin: str = None
121122
) -> None:
122-
await self._channel.send(
123-
"grantPermissions", dict(permissions=permissions, origin=origin)
124-
)
123+
await self._channel.send("grantPermissions", locals_to_params(locals()))
125124

126125
async def clearPermissions(self) -> None:
127126
await self._channel.send("clearPermissions")
128127

129128
async def setGeolocation(self, geolocation: Optional[Dict]) -> None:
130-
await self._channel.send("setGeolocation", dict(geolocation=geolocation))
129+
await self._channel.send("setGeolocation", locals_to_params(locals()))
131130

132131
async def setExtraHTTPHeaders(self, headers: Dict) -> None:
133132
await self._channel.send(

scripts/documentation_provider.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,13 @@ def print_entry(
7676
if not doc_value and "options" in args:
7777
args = args["options"]["type"]["properties"]
7878
doc_value = args.get(name)
79-
if not doc_value and fqname == "Route.fulfill":
79+
elif not doc_value and fqname == "Route.fulfill":
8080
args = args["response"]["type"]["properties"]
8181
doc_value = args.get(name)
82-
if not doc_value and fqname == "Route.continue":
82+
elif not doc_value and fqname == "Route.continue":
8383
args = args["overrides"]["type"]["properties"]
8484
doc_value = args.get(name)
85-
if not doc_value and fqname == "Page.setViewportSize":
85+
elif not doc_value and fqname == "Page.setViewportSize":
8686
args = args["viewportSize"]["type"]["properties"]
8787
doc_value = args.get(name)
8888
if not doc_value:

tests/assets/geolocation.html

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<script>
2+
window.geolocationPromise = new Promise(resolve => {
3+
navigator.geolocation.getCurrentPosition(position => {
4+
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
5+
});
6+
});
7+
</script>

tests/async/test_geolocation.py

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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+
15+
16+
import asyncio
17+
18+
import pytest
19+
20+
from playwright.async_api import BrowserContext, Page
21+
from playwright.helper import Error
22+
23+
24+
async def test_should_work(page: Page, server, context: BrowserContext):
25+
await context.grantPermissions(["geolocation"])
26+
await page.goto(server.EMPTY_PAGE)
27+
await context.setGeolocation({"longitude": 10, "latitude": 10})
28+
geolocation = await page.evaluate(
29+
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
30+
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
31+
}))"""
32+
)
33+
assert geolocation == {"latitude": 10, "longitude": 10}
34+
35+
36+
async def test_should_throw_when_invalid_longitude(context):
37+
with pytest.raises(Error) as exc:
38+
await context.setGeolocation({"longitude": 200, "latitude": 10})
39+
assert (
40+
"geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed."
41+
in exc.value.message
42+
)
43+
44+
45+
async def test_should_isolate_contexts(page, server, context, browser):
46+
await context.grantPermissions(["geolocation"])
47+
await context.setGeolocation({"longitude": 10, "latitude": 10})
48+
await page.goto(server.EMPTY_PAGE)
49+
50+
context2 = await browser.newContext(
51+
permissions=["geolocation"], geolocation={"longitude": 20, "latitude": 20}
52+
)
53+
54+
page2 = await context2.newPage()
55+
await page2.goto(server.EMPTY_PAGE)
56+
57+
geolocation = await page.evaluate(
58+
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
59+
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
60+
}))"""
61+
)
62+
assert geolocation == {"latitude": 10, "longitude": 10}
63+
64+
geolocation2 = await page2.evaluate(
65+
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
66+
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
67+
}))"""
68+
)
69+
assert geolocation2 == {"latitude": 20, "longitude": 20}
70+
71+
await context2.close()
72+
73+
74+
async def test_should_throw_with_missing_latitude(context):
75+
with pytest.raises(Error) as exc:
76+
await context.setGeolocation({"longitude": 10})
77+
"geolocation.latitude: expected number, got undefined" in exc.value.message
78+
79+
80+
async def test_should_throw_with_missing_longitude_in_default_options(browser):
81+
with pytest.raises(Error) as exc:
82+
context = await browser.newContext(geolocation={"latitude": 10})
83+
await context.close()
84+
assert "geolocation.longitude: expected number, got undefined" in exc.value.message
85+
86+
87+
async def test_should_use_context_options(browser, server):
88+
options = {
89+
"geolocation": {"longitude": 10, "latitude": 10},
90+
"permissions": ["geolocation"],
91+
}
92+
context = await browser.newContext(**options)
93+
page = await context.newPage()
94+
await page.goto(server.EMPTY_PAGE)
95+
96+
geolocation = await page.evaluate(
97+
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
98+
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
99+
}))"""
100+
)
101+
assert geolocation == {"latitude": 10, "longitude": 10}
102+
await context.close()
103+
104+
105+
async def test_watchPosition_should_be_notified(page, server, context):
106+
await context.grantPermissions(["geolocation"])
107+
await page.goto(server.EMPTY_PAGE)
108+
messages = []
109+
page.on("console", lambda message: messages.append(message.text))
110+
111+
await context.setGeolocation({"latitude": 0, "longitude": 0})
112+
await page.evaluate(
113+
"""() => {
114+
navigator.geolocation.watchPosition(pos => {
115+
const coords = pos.coords;
116+
console.log(`lat=${coords.latitude} lng=${coords.longitude}`);
117+
}, err => {});
118+
}"""
119+
)
120+
121+
await context.setGeolocation({"latitude": 0, "longitude": 10})
122+
await page.waitForEvent("console", lambda message: "lat=0 lng=10" in message.text)
123+
await context.setGeolocation({"latitude": 20, "longitude": 30})
124+
await page.waitForEvent("console", lambda message: "lat=20 lng=30" in message.text)
125+
await context.setGeolocation({"latitude": 40, "longitude": 50})
126+
await page.waitForEvent("console", lambda message: "lat=40 lng=50" in message.text)
127+
128+
allMessages = "|".join(messages)
129+
"lat=0 lng=10" in allMessages
130+
"lat=20 lng=30" in allMessages
131+
"lat=40 lng=50" in allMessages
132+
133+
134+
async def test_should_use_context_options_for_popup(page, context, server):
135+
await context.grantPermissions(["geolocation"])
136+
await context.setGeolocation({"longitude": 10, "latitude": 10})
137+
[popup, _] = await asyncio.gather(
138+
page.waitForEvent("popup"),
139+
page.evaluate(
140+
"url => window._popup = window.open(url)",
141+
server.PREFIX + "/geolocation.html",
142+
),
143+
)
144+
await popup.waitForLoadState()
145+
geolocation = await popup.evaluate("() => window.geolocationPromise")
146+
assert geolocation == {"longitude": 10, "latitude": 10}

tests/sync/test_pdf.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
15+
import os
16+
from pathlib import Path
17+
18+
import pytest
19+
20+
from playwright.page import Page
21+
22+
23+
@pytest.mark.only_browser("chromium")
24+
def test_should_be_able_to_save_pdf_file(page: Page, server, tmpdir: Path):
25+
output_file = tmpdir / "foo.png"
26+
page.pdf(path=str(output_file))
27+
assert os.path.getsize(output_file) > 0

0 commit comments

Comments
 (0)