同步完整源码 - 2026-05-24
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
import asyncio
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Generator, List
|
||||
|
||||
import pytest
|
||||
from greenlet import greenlet
|
||||
|
||||
from playwright._impl._driver import compute_driver_executable
|
||||
from playwright.sync_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
BrowserType,
|
||||
FrameLocator,
|
||||
Locator,
|
||||
Page,
|
||||
Playwright,
|
||||
Selectors,
|
||||
sync_playwright,
|
||||
)
|
||||
from tests.server import HTTPServer
|
||||
|
||||
from .utils import Utils
|
||||
from .utils import utils as utils_object
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def utils() -> Generator[Utils, None, None]:
|
||||
yield utils_object
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def playwright() -> Generator[Playwright, None, None]:
|
||||
with sync_playwright() as p:
|
||||
yield p
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def browser_type(
|
||||
playwright: Playwright, browser_name: str
|
||||
) -> Generator[BrowserType, None, None]:
|
||||
browser_type = None
|
||||
if browser_name == "chromium":
|
||||
browser_type = playwright.chromium
|
||||
elif browser_name == "firefox":
|
||||
browser_type = playwright.firefox
|
||||
elif browser_name == "webkit":
|
||||
browser_type = playwright.webkit
|
||||
assert browser_type, f"Unkown browser name '{browser_name}'"
|
||||
yield browser_type
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def browser(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> Generator[Browser, None, None]:
|
||||
browser = browser_type.launch(**launch_arguments)
|
||||
yield browser
|
||||
browser.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def context(browser: Browser) -> Generator[BrowserContext, None, None]:
|
||||
context = browser.new_context()
|
||||
yield context
|
||||
context.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(context: BrowserContext) -> Generator[Page, None, None]:
|
||||
page = context.new_page()
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def selectors(playwright: Playwright) -> Selectors:
|
||||
return playwright.selectors
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sync_gather(playwright: Playwright) -> Generator[Callable, None, None]:
|
||||
def _sync_gather_impl(*actions: Callable) -> List[Any]:
|
||||
g_self = greenlet.getcurrent()
|
||||
results: Dict[Callable, Any] = {}
|
||||
exceptions: List[Exception] = []
|
||||
|
||||
def action_wrapper(action: Callable) -> Callable:
|
||||
def body() -> Any:
|
||||
try:
|
||||
results[action] = action()
|
||||
except Exception as e:
|
||||
results[action] = e
|
||||
exceptions.append(e)
|
||||
g_self.switch()
|
||||
|
||||
return body
|
||||
|
||||
async def task() -> None:
|
||||
for action in actions:
|
||||
g = greenlet(action_wrapper(action))
|
||||
g.switch()
|
||||
|
||||
asyncio.create_task(task())
|
||||
|
||||
while len(results) < len(actions):
|
||||
playwright._dispatcher_fiber.switch()
|
||||
|
||||
if exceptions:
|
||||
raise exceptions[0]
|
||||
|
||||
return list(map(lambda action: results[action], actions))
|
||||
|
||||
yield _sync_gather_impl
|
||||
|
||||
|
||||
class TraceViewerPage:
|
||||
def __init__(self, page: Page):
|
||||
self.page = page
|
||||
|
||||
@property
|
||||
def actions_tree(self) -> Locator:
|
||||
return self.page.get_by_test_id("actions-tree")
|
||||
|
||||
@property
|
||||
def action_titles(self) -> Locator:
|
||||
return self.page.locator(".action-title")
|
||||
|
||||
@property
|
||||
def stack_frames(self) -> Locator:
|
||||
return self.page.get_by_role("listbox", name="Stack trace").get_by_role(
|
||||
"option"
|
||||
)
|
||||
|
||||
def select_action(self, title: str, ordinal: int = 0) -> None:
|
||||
self.page.locator(".action-title", has_text=title).nth(ordinal).click()
|
||||
|
||||
def select_snapshot(self, name: str) -> None:
|
||||
self.page.click(f'.snapshot-tab .tabbed-pane-tab-label:has-text("{name}")')
|
||||
|
||||
def snapshot_frame(
|
||||
self, action_name: str, ordinal: int = 0, has_subframe: bool = False
|
||||
) -> FrameLocator:
|
||||
self.select_action(action_name, ordinal)
|
||||
expected_frames = 4 if has_subframe else 3
|
||||
while len(self.page.frames) < expected_frames:
|
||||
self.page.wait_for_event("frameattached")
|
||||
return self.page.frame_locator("iframe.snapshot-visible[name=snapshot]")
|
||||
|
||||
def show_source_tab(self) -> None:
|
||||
self.page.click("text='Source'")
|
||||
|
||||
def expand_action(self, title: str, ordinal: int = 0) -> None:
|
||||
self.actions_tree.locator(".tree-view-entry", has_text=title).nth(
|
||||
ordinal
|
||||
).locator(".codicon-chevron-right").click()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def show_trace_viewer(browser: Browser) -> Generator[Callable, None, None]:
|
||||
"""Fixture that provides a function to show trace viewer for a trace file."""
|
||||
|
||||
@contextmanager
|
||||
def _show_trace_viewer(
|
||||
trace_path: Path,
|
||||
) -> Generator[TraceViewerPage, None, None]:
|
||||
trace_viewer_path = (
|
||||
Path(compute_driver_executable()[0]) / "../package/lib/vite/traceViewer"
|
||||
).resolve()
|
||||
|
||||
server = HTTPServer()
|
||||
server.start(trace_viewer_path)
|
||||
server.set_route("/trace.zip", lambda request: request.serve_file(trace_path))
|
||||
|
||||
page = browser.new_page()
|
||||
|
||||
try:
|
||||
page.goto(f"{server.PREFIX}/index.html?trace={server.PREFIX}/trace.zip")
|
||||
yield TraceViewerPage(page)
|
||||
finally:
|
||||
page.close()
|
||||
server.stop()
|
||||
|
||||
yield _show_trace_viewer
|
||||
@@ -0,0 +1,95 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, Error, Page
|
||||
|
||||
|
||||
def test_add_init_script_evaluate_before_anything_else_on_the_page(page: Page) -> None:
|
||||
page.add_init_script("window.injected = 123")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_work_with_a_path(page: Page, assetdir: Path) -> None:
|
||||
page.add_init_script(path=assetdir / "injectedfile.js")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_work_with_content(page: Page) -> None:
|
||||
page.add_init_script("window.injected = 123")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_throw_without_path_and_content(page: Page) -> None:
|
||||
with pytest.raises(
|
||||
Error, match="Either path or script parameter must be specified"
|
||||
):
|
||||
page.add_init_script({"foo": "bar"}) # type: ignore
|
||||
|
||||
|
||||
def test_add_init_script_work_with_browser_context_scripts(
|
||||
page: Page, context: BrowserContext
|
||||
) -> None:
|
||||
context.add_init_script("window.temp = 123")
|
||||
page = context.new_page()
|
||||
page.add_init_script("window.injected = window.temp")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_work_with_browser_context_scripts_with_a_path(
|
||||
page: Page, context: BrowserContext, assetdir: Path
|
||||
) -> None:
|
||||
context.add_init_script(path=assetdir / "injectedfile.js")
|
||||
page = context.new_page()
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_work_with_browser_context_scripts_for_already_created_pages(
|
||||
page: Page, context: BrowserContext
|
||||
) -> None:
|
||||
context.add_init_script("window.temp = 123")
|
||||
page.add_init_script("window.injected = window.temp")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
def test_add_init_script_support_multiple_scripts(page: Page) -> None:
|
||||
page.add_init_script("window.script1 = 1")
|
||||
page.add_init_script("window.script2 = 2")
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.script1") == 1
|
||||
assert page.evaluate("window.script2") == 2
|
||||
|
||||
|
||||
def test_should_work_with_trailing_comments(page: Page) -> None:
|
||||
page.add_init_script("// comment")
|
||||
page.add_init_script("window.secret = 42;")
|
||||
page.goto("data:text/html,<html></html>")
|
||||
assert page.evaluate("secret") == 42
|
||||
|
||||
|
||||
def test_add_init_script_returns_disposable(page: Page) -> None:
|
||||
with page.add_init_script("window.injected = 123"):
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") == 123
|
||||
page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert page.evaluate("window.result") is None
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from playwright.sync_api import Browser, BrowserType
|
||||
|
||||
|
||||
def test_should_return_browser_type(
|
||||
browser: Browser, browser_type: BrowserType
|
||||
) -> None:
|
||||
assert browser.browser_type is browser_type
|
||||
|
||||
|
||||
def test_bind_should_return_endpoint_and_allow_unbind(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = browser_type.launch(**launch_arguments)
|
||||
try:
|
||||
result = browser.bind("test-server")
|
||||
assert "endpoint" in result
|
||||
assert isinstance(result["endpoint"], str)
|
||||
assert len(result["endpoint"]) > 0
|
||||
browser.unbind()
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
|
||||
def test_should_fire_context_event_on_new_context(browser: Browser) -> None:
|
||||
events = []
|
||||
browser.on("context", lambda ctx: events.append(ctx))
|
||||
context = browser.new_context()
|
||||
try:
|
||||
assert events == [context]
|
||||
finally:
|
||||
context.close()
|
||||
@@ -0,0 +1,258 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Dict, Generator, Optional, cast
|
||||
|
||||
import OpenSSL.crypto
|
||||
import OpenSSL.SSL
|
||||
import pytest
|
||||
from twisted.internet import reactor as _twisted_reactor
|
||||
from twisted.internet import ssl
|
||||
from twisted.internet.selectreactor import SelectReactor
|
||||
from twisted.web import resource, server
|
||||
from twisted.web.http import Request
|
||||
|
||||
from playwright.sync_api import Browser, BrowserType, Playwright, expect
|
||||
|
||||
reactor = cast(SelectReactor, _twisted_reactor)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function", autouse=True)
|
||||
def _skip_webkit_darwin(browser_name: str) -> None:
|
||||
if browser_name == "webkit" and sys.platform == "darwin":
|
||||
pytest.skip("WebKit does not proxy localhost on macOS")
|
||||
|
||||
|
||||
class HttpsResource(resource.Resource):
|
||||
serverCertificate: ssl.PrivateCertificate
|
||||
isLeaf = True
|
||||
|
||||
def _verify_cert_chain(self, cert: Optional[OpenSSL.crypto.X509]) -> bool:
|
||||
if not cert:
|
||||
return False
|
||||
store = OpenSSL.crypto.X509Store()
|
||||
store.add_cert(self.serverCertificate.original)
|
||||
store_ctx = OpenSSL.crypto.X509StoreContext(store, cert)
|
||||
try:
|
||||
store_ctx.verify_certificate()
|
||||
return True
|
||||
except OpenSSL.crypto.X509StoreContextError:
|
||||
return False
|
||||
|
||||
def render_GET(self, request: Request) -> bytes:
|
||||
tls_socket: OpenSSL.SSL.Connection = request.transport.getHandle() # type: ignore
|
||||
cert = tls_socket.get_peer_certificate()
|
||||
parts = []
|
||||
|
||||
if self._verify_cert_chain(cert):
|
||||
request.setResponseCode(200)
|
||||
parts.append(
|
||||
{
|
||||
"key": "message",
|
||||
"value": f"Hello {cert.get_subject().CN}, your certificate was issued by {cert.get_issuer().CN}!", # type: ignore
|
||||
}
|
||||
)
|
||||
elif cert and cert.get_subject():
|
||||
request.setResponseCode(403)
|
||||
parts.append(
|
||||
{
|
||||
"key": "message",
|
||||
"value": f"Sorry {cert.get_subject().CN}, certificates from {cert.get_issuer().CN} are not welcome here.",
|
||||
}
|
||||
)
|
||||
else:
|
||||
request.setResponseCode(401)
|
||||
parts.append(
|
||||
{
|
||||
"key": "message",
|
||||
"value": "Sorry, but you need to provide a client certificate to continue.",
|
||||
}
|
||||
)
|
||||
return b"".join(
|
||||
[
|
||||
f'<div data-testid="{part["key"]}">{part["value"]}</div>'.encode()
|
||||
for part in parts
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _client_certificate_server(assetdir: Path) -> Generator[None, None, None]:
|
||||
certAuthCert = ssl.Certificate.loadPEM(
|
||||
(assetdir / "client-certificates/server/server_cert.pem").read_text()
|
||||
)
|
||||
serverCert = ssl.PrivateCertificate.loadPEM(
|
||||
(assetdir / "client-certificates/server/server_key.pem").read_text()
|
||||
+ (assetdir / "client-certificates/server/server_cert.pem").read_text()
|
||||
)
|
||||
|
||||
contextFactory = serverCert.options(certAuthCert)
|
||||
contextFactory.requireCertificate = False
|
||||
resource = HttpsResource()
|
||||
resource.serverCertificate = serverCert
|
||||
site = server.Site(resource)
|
||||
|
||||
def _run() -> None:
|
||||
reactor.listenSSL(8000, site, contextFactory)
|
||||
|
||||
thread = threading.Thread(target=_run)
|
||||
thread.start()
|
||||
yield
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_should_throw_with_untrusted_client_certs(
|
||||
playwright: Playwright, assetdir: Path
|
||||
) -> None:
|
||||
serverURL = "https://localhost:8000/"
|
||||
request = playwright.request.new_context(
|
||||
# TODO: Remove this once we can pass a custom CA.
|
||||
ignore_https_errors=True,
|
||||
client_certificates=[
|
||||
{
|
||||
"origin": serverURL,
|
||||
"certPath": assetdir
|
||||
/ "client-certificates/client/self-signed/cert.pem",
|
||||
"keyPath": assetdir / "client-certificates/client/self-signed/key.pem",
|
||||
}
|
||||
],
|
||||
)
|
||||
with pytest.raises(Exception, match="alert unknown ca"):
|
||||
request.get(serverURL)
|
||||
request.dispose()
|
||||
|
||||
|
||||
def test_should_work_with_new_context(browser: Browser, assetdir: Path) -> None:
|
||||
context = browser.new_context(
|
||||
# TODO: Remove this once we can pass a custom CA.
|
||||
ignore_https_errors=True,
|
||||
client_certificates=[
|
||||
{
|
||||
"origin": "https://127.0.0.1:8000",
|
||||
"certPath": assetdir / "client-certificates/client/trusted/cert.pem",
|
||||
"keyPath": assetdir / "client-certificates/client/trusted/key.pem",
|
||||
}
|
||||
],
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://localhost:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
page.goto("https://127.0.0.1:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
|
||||
response = page.context.request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in response.text()
|
||||
)
|
||||
response = page.context.request.get("https://127.0.0.1:8000")
|
||||
assert "Hello Alice, your certificate was issued by localhost!" in response.text()
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_work_with_new_context_passing_as_content(
|
||||
browser: Browser, assetdir: Path
|
||||
) -> None:
|
||||
context = browser.new_context(
|
||||
# TODO: Remove this once we can pass a custom CA.
|
||||
ignore_https_errors=True,
|
||||
client_certificates=[
|
||||
{
|
||||
"origin": "https://127.0.0.1:8000",
|
||||
"cert": (
|
||||
assetdir / "client-certificates/client/trusted/cert.pem"
|
||||
).read_bytes(),
|
||||
"key": (
|
||||
assetdir / "client-certificates/client/trusted/key.pem"
|
||||
).read_bytes(),
|
||||
}
|
||||
],
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://localhost:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
page.goto("https://127.0.0.1:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
|
||||
response = page.context.request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in response.text()
|
||||
)
|
||||
response = page.context.request.get("https://127.0.0.1:8000")
|
||||
assert "Hello Alice, your certificate was issued by localhost!" in response.text()
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_work_with_new_persistent_context(
|
||||
browser_type: BrowserType, assetdir: Path, launch_arguments: Dict
|
||||
) -> None:
|
||||
context = browser_type.launch_persistent_context(
|
||||
"",
|
||||
**launch_arguments,
|
||||
# TODO: Remove this once we can pass a custom CA.
|
||||
ignore_https_errors=True,
|
||||
client_certificates=[
|
||||
{
|
||||
"origin": "https://127.0.0.1:8000",
|
||||
"certPath": assetdir / "client-certificates/client/trusted/cert.pem",
|
||||
"keyPath": assetdir / "client-certificates/client/trusted/key.pem",
|
||||
}
|
||||
],
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://localhost:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
page.goto("https://127.0.0.1:8000")
|
||||
expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_work_with_global_api_request_context(
|
||||
playwright: Playwright, assetdir: Path
|
||||
) -> None:
|
||||
request = playwright.request.new_context(
|
||||
# TODO: Remove this once we can pass a custom CA.
|
||||
ignore_https_errors=True,
|
||||
client_certificates=[
|
||||
{
|
||||
"origin": "https://127.0.0.1:8000",
|
||||
"certPath": assetdir / "client-certificates/client/trusted/cert.pem",
|
||||
"keyPath": assetdir / "client-certificates/client/trusted/key.pem",
|
||||
}
|
||||
],
|
||||
)
|
||||
response = request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in response.text()
|
||||
)
|
||||
response = request.get("https://127.0.0.1:8000")
|
||||
assert "Hello Alice, your certificate was issued by localhost!" in response.text()
|
||||
request.dispose()
|
||||
@@ -0,0 +1,318 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, Dialog, Page
|
||||
|
||||
from ..server import Server, TestServerRequest
|
||||
|
||||
|
||||
def test_console_event_should_work(page: Page) -> None:
|
||||
with page.context.expect_console_message() as console_info:
|
||||
page.evaluate("() => console.log('hello')")
|
||||
message = console_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == page
|
||||
|
||||
|
||||
def test_console_event_should_work_in_popup(page: Page) -> None:
|
||||
with page.context.expect_console_message() as console_info:
|
||||
with page.expect_popup() as popup_info:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open('');
|
||||
win.console.log('hello');
|
||||
}"""
|
||||
)
|
||||
message = console_info.value
|
||||
popup = popup_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_console_event_should_work_in_popup_2(page: Page, browser_name: str) -> None:
|
||||
with page.context.expect_console_message(
|
||||
lambda msg: msg.type == "log"
|
||||
) as console_info:
|
||||
with page.context.expect_page() as page_info:
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
const win = window.open('javascript:console.log("hello")');
|
||||
await new Promise(f => setTimeout(f, 0));
|
||||
win.close();
|
||||
}"""
|
||||
)
|
||||
message = console_info.value
|
||||
popup = page_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_console_event_should_work_in_immediately_closed_popup(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
with page.context.expect_console_message(
|
||||
lambda msg: msg.type == "log"
|
||||
) as console_info:
|
||||
with page.context.expect_page() as page_info:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open('');
|
||||
win.console.log('hello');
|
||||
win.close();
|
||||
}"""
|
||||
)
|
||||
message = console_info.value
|
||||
popup = page_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
def test_dialog_event_should_work1(page: Page) -> None:
|
||||
dialog1: Optional[Dialog] = None
|
||||
|
||||
def handle_page_dialog(dialog: Dialog) -> None:
|
||||
nonlocal dialog1
|
||||
dialog1 = dialog
|
||||
dialog.accept("hello")
|
||||
|
||||
page.on("dialog", handle_page_dialog)
|
||||
|
||||
dialog2: Optional[Dialog] = None
|
||||
|
||||
def handle_context_dialog(dialog: Dialog) -> None:
|
||||
nonlocal dialog2
|
||||
dialog2 = dialog
|
||||
|
||||
page.context.on("dialog", handle_context_dialog)
|
||||
|
||||
assert page.evaluate("() => prompt('hey?')") == "hello"
|
||||
assert dialog1
|
||||
assert dialog1 == dialog2
|
||||
assert dialog1.message == "hey?"
|
||||
assert dialog1.page == page
|
||||
|
||||
|
||||
def test_dialog_event_should_work_in_popup1(page: Page) -> None:
|
||||
dialog: Optional[Dialog] = None
|
||||
|
||||
def handle_dialog(d: Dialog) -> None:
|
||||
nonlocal dialog
|
||||
dialog = d
|
||||
dialog.accept("hello")
|
||||
|
||||
page.context.on("dialog", handle_dialog)
|
||||
|
||||
with page.expect_popup() as popup_info:
|
||||
assert page.evaluate("() => window.open('').prompt('hey?')") == "hello"
|
||||
popup = popup_info.value
|
||||
assert dialog
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page == popup
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_dialog_event_should_work_in_popup_2(page: Page, browser_name: str) -> None:
|
||||
def handle_dialog(dialog: Dialog) -> None:
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page is None
|
||||
dialog.accept("hello")
|
||||
|
||||
page.context.on("dialog", handle_dialog)
|
||||
|
||||
assert page.evaluate("() => window.open('javascript:prompt(\"hey?\")')")
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_dialog_event_should_work_in_immdiately_closed_popup(page: Page) -> None:
|
||||
popup = None
|
||||
|
||||
def handle_popup(p: Page) -> None:
|
||||
nonlocal popup
|
||||
popup = p
|
||||
|
||||
page.on("popup", handle_popup)
|
||||
|
||||
with page.context.expect_console_message() as console_info:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open();
|
||||
win.console.log('hello');
|
||||
win.close();
|
||||
}"""
|
||||
)
|
||||
message = console_info.value
|
||||
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
def test_dialog_event_should_work_with_inline_script_tag(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
def handle_route(request: TestServerRequest) -> None:
|
||||
request.setHeader("content-type", "text/html")
|
||||
request.write(b"<script>window.result = prompt('hey?')</script>")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/popup.html", handle_route)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.set_content("<a href='popup.html' target=_blank>Click me</a>")
|
||||
|
||||
with (
|
||||
page.context.expect_event("dialog") as dialog_info,
|
||||
page.expect_popup() as popup_info,
|
||||
):
|
||||
page.click("a")
|
||||
|
||||
dialog: Dialog = dialog_info.value
|
||||
popup: Page = popup_info.value
|
||||
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page == popup
|
||||
dialog.accept("hello")
|
||||
assert popup.evaluate("window.result") == "hello"
|
||||
|
||||
|
||||
def test_console_event_should_work_with_context_manager(page: Page) -> None:
|
||||
with page.context.expect_console_message() as cm_info:
|
||||
page.evaluate("() => console.log('hello')")
|
||||
message = cm_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == page
|
||||
|
||||
|
||||
def test_weberror_event_should_work(context: BrowserContext, page: Page) -> None:
|
||||
with context.expect_event("weberror") as error_info:
|
||||
page.goto('data:text/html,<script>throw new Error("Test")</script>')
|
||||
error = error_info.value
|
||||
assert error.page == page
|
||||
assert error.error.message == "Test"
|
||||
|
||||
|
||||
def test_weberror_event_should_include_location(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
def handle_error_js(request: TestServerRequest) -> None:
|
||||
request.setHeader("content-type", "application/javascript")
|
||||
request.write(
|
||||
b"""
|
||||
function foo() {
|
||||
throw new Error('boom');
|
||||
}
|
||||
foo();
|
||||
"""
|
||||
)
|
||||
request.finish()
|
||||
|
||||
def handle_error_html(request: TestServerRequest) -> None:
|
||||
request.setHeader("content-type", "text/html")
|
||||
request.write(b'<script src="/error.js"></script>')
|
||||
request.finish()
|
||||
|
||||
server.set_route("/error.js", handle_error_js)
|
||||
server.set_route("/error.html", handle_error_html)
|
||||
|
||||
with context.expect_event("weberror") as error_info:
|
||||
page.goto(server.PREFIX + "/error.html")
|
||||
web_error = error_info.value
|
||||
location = web_error.location
|
||||
assert location["url"] == f"{server.PREFIX}/error.js"
|
||||
assert location["line"] == 2
|
||||
assert location["column"] > 0
|
||||
|
||||
|
||||
def test_pageload_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
with context.expect_event("pageload") as info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert info.value == page
|
||||
|
||||
|
||||
def test_framenavigated_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
with context.expect_event("framenavigated") as info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
frame = info.value
|
||||
assert frame == page.main_frame
|
||||
assert frame.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
def test_pageclose_event_should_work(context: BrowserContext) -> None:
|
||||
page = context.new_page()
|
||||
with context.expect_event("pageclose") as info:
|
||||
page.close()
|
||||
assert info.value == page
|
||||
|
||||
|
||||
def test_frameattached_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with context.expect_event("frameattached") as info:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = 'about:blank';
|
||||
document.body.appendChild(iframe);
|
||||
}"""
|
||||
)
|
||||
assert info.value.parent_frame == page.main_frame
|
||||
|
||||
|
||||
def test_framedetached_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.id = 'x';
|
||||
iframe.src = 'about:blank';
|
||||
document.body.appendChild(iframe);
|
||||
}"""
|
||||
)
|
||||
page.wait_for_selector("iframe")
|
||||
with context.expect_event("framedetached") as info:
|
||||
page.evaluate("() => document.getElementById('x').remove()")
|
||||
assert info.value.parent_frame == page.main_frame
|
||||
|
||||
|
||||
def test_download_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.setHeader("Content-Disposition", "attachment; filename=file.txt")
|
||||
request.write(b"Hello world")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/download", handle_download)
|
||||
page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
with context.expect_event("download") as info:
|
||||
page.click("a")
|
||||
download = info.value
|
||||
assert download.suggested_filename == "file.txt"
|
||||
assert download.page == page
|
||||
@@ -0,0 +1,359 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Callable, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, Error, Page, Request, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def _append_with_return_value(values: List, value: Any) -> Any:
|
||||
values.append(value)
|
||||
|
||||
|
||||
def test_should_work(page: Page, context: BrowserContext, server: Server) -> None:
|
||||
context.route("**/*", lambda route: route.fallback())
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_should_fall_back(page: Page, context: BrowserContext, server: Server) -> None:
|
||||
intercepted: List[int] = []
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 1),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 2),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 3),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
def test_should_fall_back_async_delayed(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
def create_handler(i: int) -> Callable[[Route], None]:
|
||||
def handler(route: Route) -> None:
|
||||
intercepted.append(i)
|
||||
page.wait_for_timeout(500)
|
||||
route.fallback()
|
||||
|
||||
return handler
|
||||
|
||||
context.route("**/empty.html", create_handler(1))
|
||||
context.route("**/empty.html", create_handler(2))
|
||||
context.route("**/empty.html", create_handler(3))
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
def test_should_chain_once(page: Page, context: BrowserContext, server: Server) -> None:
|
||||
context.route(
|
||||
"**/madeup.txt",
|
||||
lambda route: route.fulfill(status=200, body="fulfilled one"),
|
||||
times=1,
|
||||
)
|
||||
context.route("**/madeup.txt", lambda route: route.fallback(), times=1)
|
||||
|
||||
resp = page.goto(server.PREFIX + "/madeup.txt")
|
||||
assert resp
|
||||
body = resp.body()
|
||||
assert body == b"fulfilled one"
|
||||
|
||||
|
||||
def test_should_not_chain_fulfill(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
failed = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
context.route("**/empty.html", handler)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.fulfill(status=200, body="fulfilled"),
|
||||
)
|
||||
context.route("**/empty.html", lambda route: route.fallback())
|
||||
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
body = response.body()
|
||||
assert body == b"fulfilled"
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
def test_should_not_chain_abort(
|
||||
page: Page,
|
||||
context: BrowserContext,
|
||||
server: Server,
|
||||
is_webkit: bool,
|
||||
is_firefox: bool,
|
||||
) -> None:
|
||||
failed = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
context.route("**/empty.html", handler)
|
||||
context.route("**/empty.html", lambda route: route.abort())
|
||||
context.route("**/empty.html", lambda route: route.fallback())
|
||||
|
||||
with pytest.raises(Error) as excinfo:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
if is_webkit:
|
||||
assert "Blocked by Web Inspector" in excinfo.value.message
|
||||
elif is_firefox:
|
||||
assert "NS_ERROR_FAILURE" in excinfo.value.message
|
||||
else:
|
||||
assert "net::ERR_FAILED" in excinfo.value.message
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
def test_should_fall_back_after_exception(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
context.route("**/empty.html", lambda route: route.continue_())
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
try:
|
||||
route.fulfill(response=47) # type: ignore
|
||||
except Exception:
|
||||
route.fallback()
|
||||
|
||||
context.route("**/empty.html", handler)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_should_amend_http_headers(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
values = []
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
values.append(route.request.headers.get("foo"))
|
||||
values.append(route.request.header_value("FOO"))
|
||||
route.continue_()
|
||||
|
||||
context.route("**/sleep.zzz", handler)
|
||||
|
||||
def handler_with_header_mods(route: Route) -> None:
|
||||
route.fallback(headers={**route.request.headers, "FOO": "bar"})
|
||||
|
||||
context.route("**/*", handler_with_header_mods)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz')")
|
||||
values.append(server_request_info.value.getHeader("foo"))
|
||||
assert values == ["bar", "bar", "bar"]
|
||||
|
||||
|
||||
def test_should_delete_header_with_undefined_value(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
server.set_route(
|
||||
"/something",
|
||||
lambda r: (
|
||||
r.setHeader("Acces-Control-Allow-Origin", "*"),
|
||||
r.write(b"done"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
intercepted_request = []
|
||||
|
||||
def capture_and_continue(route: Route, request: Request) -> None:
|
||||
intercepted_request.append(request)
|
||||
route.continue_()
|
||||
|
||||
context.route("**/*", capture_and_continue)
|
||||
|
||||
def delete_foo_header(route: Route, request: Request) -> None:
|
||||
headers = request.all_headers()
|
||||
del headers["foo"]
|
||||
route.fallback(headers=headers)
|
||||
|
||||
context.route(server.PREFIX + "/something", delete_foo_header)
|
||||
with server.expect_request("/something") as server_req_info:
|
||||
text = page.evaluate(
|
||||
"""
|
||||
async url => {
|
||||
const data = await fetch(url, {
|
||||
headers: {
|
||||
foo: 'a',
|
||||
bar: 'b',
|
||||
}
|
||||
});
|
||||
return data.text();
|
||||
}
|
||||
""",
|
||||
server.PREFIX + "/something",
|
||||
)
|
||||
server_req = server_req_info.value
|
||||
assert text == "done"
|
||||
assert not intercepted_request[0].headers.get("foo")
|
||||
assert intercepted_request[0].headers.get("bar") == "b"
|
||||
assert not server_req.getHeader("foo")
|
||||
assert server_req.getHeader("bar") == "b"
|
||||
|
||||
|
||||
def test_should_amend_method(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
method: List[str] = []
|
||||
context.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(method, route.request.method),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
context.route("**/*", lambda route: route.fallback(method="POST"))
|
||||
|
||||
with server.expect_request("/sleep.zzz") as request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz')")
|
||||
request = request_info.value
|
||||
assert method == ["POST"]
|
||||
assert request.method == b"POST"
|
||||
|
||||
|
||||
def test_should_override_request_url(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
url: List[str] = []
|
||||
context.route(
|
||||
"**/global-var.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(url, route.request.url),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
context.route(
|
||||
"**/foo",
|
||||
lambda route: route.fallback(url=server.PREFIX + "/global-var.html"),
|
||||
)
|
||||
|
||||
with server.expect_request("/global-var.html") as server_request_info:
|
||||
with page.expect_event("response") as response_info:
|
||||
page.goto(server.PREFIX + "/foo")
|
||||
server_request = server_request_info.value
|
||||
response = response_info.value
|
||||
assert url == [server.PREFIX + "/global-var.html"]
|
||||
assert response.url == server.PREFIX + "/global-var.html"
|
||||
assert response.request.url == server.PREFIX + "/global-var.html"
|
||||
assert page.evaluate("() => window['globalVar']") == 123
|
||||
assert server_request.uri == b"/global-var.html"
|
||||
assert server_request.method == b"GET"
|
||||
|
||||
|
||||
def test_should_amend_post_data(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
post_data: List[str] = []
|
||||
context.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(post_data, route.request.post_data),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
context.route("**/*", lambda route: route.fallback(post_data="doggo"))
|
||||
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })")
|
||||
server_request = server_request_info.value
|
||||
assert post_data == ["doggo"]
|
||||
assert server_request.post_body == b"doggo"
|
||||
|
||||
|
||||
def test_should_amend_binary_post_data(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
post_data_buffer: List[str] = []
|
||||
context.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(post_data_buffer, route.request.post_data),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
context.route(
|
||||
"**/*", lambda route: route.fallback(post_data=b"\x00\x01\x02\x03\x04")
|
||||
)
|
||||
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })")
|
||||
server_request = server_request_info.value
|
||||
# FIXME: should this be bytes?
|
||||
assert post_data_buffer == ["\x00\x01\x02\x03\x04"]
|
||||
assert server_request.method == b"POST"
|
||||
assert server_request.post_body == b"\x00\x01\x02\x03\x04"
|
||||
|
||||
|
||||
def test_should_chain_fallback_into_page(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted: List[int] = []
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 1), route.fallback()),
|
||||
)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 2), route.fallback()),
|
||||
)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 3), route.fallback()),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 4), route.fallback()),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 5), route.fallback()),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (_append_with_return_value(intercepted, 6), route.fallback()),
|
||||
)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [6, 5, 4, 3, 2, 1]
|
||||
@@ -0,0 +1,136 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.sync_api import BrowserContext, Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_fulfill_intercepted_response(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(
|
||||
response=response,
|
||||
status=201,
|
||||
headers={"foo": "bar"},
|
||||
content_type="text/plain",
|
||||
body="Yo, page!",
|
||||
)
|
||||
|
||||
context.route("**/*", handle)
|
||||
response = page.goto(server.PREFIX + "/empty.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.headers["foo"] == "bar"
|
||||
assert response.headers["content-type"] == "text/plain"
|
||||
assert page.evaluate("() => document.body.textContent") == "Yo, page!"
|
||||
|
||||
|
||||
def test_should_fulfill_response_with_empty_body(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(
|
||||
response=response, status=201, body="", headers={"content-length": "0"}
|
||||
)
|
||||
|
||||
context.route("**/*", handle)
|
||||
response = page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == ""
|
||||
|
||||
|
||||
def test_should_override_with_defaults_when_intercepted_response_not_provided(
|
||||
page: Page, context: BrowserContext, server: Server, browser_name: str
|
||||
) -> None:
|
||||
def server_handler(request: http.Request) -> None:
|
||||
request.setHeader("foo", "bar")
|
||||
request.write("my content".encode())
|
||||
request.finish()
|
||||
|
||||
server.set_route("/empty.html", server_handler)
|
||||
|
||||
def handle(route: Route) -> None:
|
||||
page.request.fetch(route.request)
|
||||
route.fulfill(status=201)
|
||||
|
||||
context.route("**/*", handle)
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == ""
|
||||
if browser_name == "webkit":
|
||||
assert response.headers == {"content-type": "text/plain"}
|
||||
else:
|
||||
assert response.headers == {}
|
||||
|
||||
|
||||
def test_should_fulfill_with_any_response(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
def server_handler(request: http.Request) -> None:
|
||||
request.setHeader("foo", "bar")
|
||||
request.write("Woo-hoo".encode())
|
||||
request.finish()
|
||||
|
||||
server.set_route("/sample", server_handler)
|
||||
sample_response = page.request.get(server.PREFIX + "/sample")
|
||||
context.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(
|
||||
response=sample_response, status=201, content_type="text/plain"
|
||||
),
|
||||
)
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == "Woo-hoo"
|
||||
assert response.headers["foo"] == "bar"
|
||||
|
||||
|
||||
def test_should_support_fulfill_after_intercept(
|
||||
page: Page, context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
def handle_route(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(response=response)
|
||||
|
||||
context.route("**", handle_route)
|
||||
with server.expect_request("/title.html") as request_info:
|
||||
response = page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
request = request_info.value
|
||||
assert request.uri.decode() == "/title.html"
|
||||
original = (assetdir / "title.html").read_text()
|
||||
assert response.text() == original
|
||||
|
||||
|
||||
def test_should_show_exception_after_fulfill(page: Page, server: Server) -> None:
|
||||
def _handle(route: Route) -> None:
|
||||
route.continue_()
|
||||
raise Exception("Exception text!?")
|
||||
|
||||
page.route("*/**", _handle)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
# Any next API call should throw because handler did throw during previous goto()
|
||||
with pytest.raises(Exception, match="Exception text!?"):
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
@@ -0,0 +1,37 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from playwright.sync_api import Browser
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_allow_service_workers_by_default(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
|
||||
page.evaluate("() => window.activationPromise")
|
||||
context.close()
|
||||
|
||||
|
||||
def test_block_blocks_service_worker_registration(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = browser.new_context(service_workers="block")
|
||||
page = context.new_page()
|
||||
with page.expect_console_message(
|
||||
lambda m: "Service Worker registration blocked by Playwright" == m.text
|
||||
):
|
||||
page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
|
||||
context.close()
|
||||
@@ -0,0 +1,174 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import Browser, BrowserContext, Page, StorageState
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_capture_local_storage(context: BrowserContext) -> None:
|
||||
page1 = context.new_page()
|
||||
page1.route("**/*", lambda route: route.fulfill(body="<html></html>"))
|
||||
page1.goto("https://www.example.com")
|
||||
page1.evaluate("localStorage['name1'] = 'value1'")
|
||||
page1.goto("https://www.domain.com")
|
||||
page1.evaluate("localStorage['name2'] = 'value2'")
|
||||
|
||||
state = context.storage_state()
|
||||
origins = state["origins"]
|
||||
assert origins
|
||||
assert len(origins) == 2
|
||||
assert origins[0] == {
|
||||
"origin": "https://www.domain.com",
|
||||
"localStorage": [{"name": "name2", "value": "value2"}],
|
||||
}
|
||||
assert origins[1] == {
|
||||
"origin": "https://www.example.com",
|
||||
"localStorage": [{"name": "name1", "value": "value1"}],
|
||||
}
|
||||
|
||||
|
||||
def test_should_set_local_storage(browser: Browser) -> None:
|
||||
storage_state: StorageState = {
|
||||
"origins": [
|
||||
{
|
||||
"origin": "https://www.example.com",
|
||||
"localStorage": [{"name": "name1", "value": "value1"}],
|
||||
}
|
||||
]
|
||||
}
|
||||
# We intentionally hide the indexed_db part in our API for now
|
||||
storage_state["origins"][0]["indexedDB"] = [ # type: ignore
|
||||
{
|
||||
"name": "db",
|
||||
"version": 42,
|
||||
"stores": [
|
||||
{
|
||||
"name": "store",
|
||||
"autoIncrement": False,
|
||||
"records": [{"key": "bar", "value": "foo"}],
|
||||
"indexes": [],
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
context = browser.new_context(storage_state=storage_state)
|
||||
|
||||
page = context.new_page()
|
||||
page.route("**/*", lambda route: route.fulfill(body="<html></html>"))
|
||||
page.goto("https://www.example.com")
|
||||
local_storage = page.evaluate("window.localStorage")
|
||||
assert local_storage == {"name1": "value1"}
|
||||
|
||||
indexed_db = page.evaluate(
|
||||
"""async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const openRequest = indexedDB.open('db', 42);
|
||||
openRequest.addEventListener('success', () => {
|
||||
const db = openRequest.result;
|
||||
const transaction = db.transaction('store', 'readonly');
|
||||
const getRequest = transaction.objectStore('store').get('bar');
|
||||
getRequest.addEventListener('success', () => resolve(getRequest.result));
|
||||
getRequest.addEventListener('error', () => reject(getRequest.error));
|
||||
});
|
||||
openRequest.addEventListener('error', () => reject(openRequest.error));
|
||||
});
|
||||
}"""
|
||||
)
|
||||
assert indexed_db == "foo"
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_round_trip_through_the_file(
|
||||
browser: Browser, context: BrowserContext, tmp_path: Path
|
||||
) -> None:
|
||||
page1 = context.new_page()
|
||||
page1.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(body="<html></html>"),
|
||||
)
|
||||
page1.goto("https://www.example.com")
|
||||
page1.evaluate(
|
||||
"""() => {
|
||||
localStorage["name1"] = "value1"
|
||||
document.cookie = "username=John Doe"
|
||||
return document.cookie
|
||||
}"""
|
||||
)
|
||||
|
||||
path = tmp_path / "storage-state.json"
|
||||
state = context.storage_state(path=path)
|
||||
with open(path, "r") as f:
|
||||
written = json.load(f)
|
||||
assert state == written
|
||||
|
||||
context2 = browser.new_context(storage_state=path)
|
||||
page2 = context2.new_page()
|
||||
page2.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(body="<html></html>"),
|
||||
)
|
||||
page2.goto("https://www.example.com")
|
||||
local_storage = page2.evaluate("window.localStorage")
|
||||
assert local_storage == {"name1": "value1"}
|
||||
cookie = page2.evaluate("document.cookie")
|
||||
assert cookie == "username=John Doe"
|
||||
context2.close()
|
||||
|
||||
|
||||
def test_should_serialise_indexed_db(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
await new Promise((resolve, reject) => {
|
||||
const openRequest = indexedDB.open('db', 42);
|
||||
openRequest.onupgradeneeded = () => {
|
||||
openRequest.result.createObjectStore('store');
|
||||
};
|
||||
openRequest.onsuccess = () => {
|
||||
const request = openRequest.result.transaction('store', 'readwrite')
|
||||
.objectStore('store')
|
||||
.put('foo', 'bar');
|
||||
request.addEventListener('success', resolve);
|
||||
request.addEventListener('error', reject);
|
||||
};
|
||||
});
|
||||
}"""
|
||||
)
|
||||
assert page.context.storage_state() == {"cookies": [], "origins": []}
|
||||
assert page.context.storage_state(indexed_db=True) == {
|
||||
"cookies": [],
|
||||
"origins": [
|
||||
{
|
||||
"origin": f"http://localhost:{server.PORT}",
|
||||
"localStorage": [],
|
||||
"indexedDB": [
|
||||
{
|
||||
"name": "db",
|
||||
"version": 42,
|
||||
"stores": [
|
||||
{
|
||||
"name": "store",
|
||||
"autoIncrement": False,
|
||||
"records": [{"key": "bar", "value": "foo"}],
|
||||
"indexes": [],
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserType, Error, Playwright, Route
|
||||
from tests.conftest import RemoteServer
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_browser_type_connect_slow_mo(
|
||||
server: Server, browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = browser_type.connect(remote_server.ws_endpoint, slow_mo=100)
|
||||
browser_context = browser.new_context()
|
||||
t1 = time.monotonic()
|
||||
page = browser_context.new_page()
|
||||
assert page.evaluate("11 * 11") == 121
|
||||
assert (time.monotonic() - t1) >= 0.2
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
browser.close()
|
||||
|
||||
|
||||
def test_browser_type_connect_should_be_able_to_reconnect_to_a_browser(
|
||||
server: Server, browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = browser_type.connect(remote_server.ws_endpoint)
|
||||
browser_context = browser.new_context()
|
||||
assert len(browser_context.pages) == 0
|
||||
page = browser_context.new_page()
|
||||
assert len(browser_context.pages) == 1
|
||||
assert page.evaluate("11 * 11") == 121
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
browser.close()
|
||||
|
||||
browser = browser_type.connect(remote_server.ws_endpoint)
|
||||
browser_context = browser.new_context()
|
||||
page = browser_context.new_page()
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
browser.close()
|
||||
|
||||
|
||||
def test_browser_type_connect_should_be_able_to_connect_two_browsers_at_the_same_time(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser1 = browser_type.connect(remote_server.ws_endpoint)
|
||||
assert len(browser1.contexts) == 0
|
||||
browser1.new_context()
|
||||
assert len(browser1.contexts) == 1
|
||||
|
||||
browser2 = browser_type.connect(remote_server.ws_endpoint)
|
||||
assert len(browser2.contexts) == 0
|
||||
browser2.new_context()
|
||||
assert len(browser2.contexts) == 1
|
||||
assert len(browser1.contexts) == 1
|
||||
|
||||
browser1.close()
|
||||
page2 = browser2.new_page()
|
||||
# original browser should still work
|
||||
assert page2.evaluate("7 * 6") == 42
|
||||
|
||||
browser2.close()
|
||||
|
||||
|
||||
def test_browser_type_connect_disconnected_event_should_be_emitted_when_browser_is_closed_or_server_is_closed(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser1 = browser_type.connect(remote.ws_endpoint)
|
||||
browser2 = browser_type.connect(remote.ws_endpoint)
|
||||
|
||||
disconnected1 = []
|
||||
disconnected2 = []
|
||||
browser1.on("disconnected", lambda browser: disconnected1.append(True))
|
||||
browser2.on("disconnected", lambda browser: disconnected2.append(True))
|
||||
|
||||
page2 = browser2.new_page()
|
||||
|
||||
browser1.close()
|
||||
assert len(disconnected1) == 1
|
||||
assert len(disconnected2) == 0
|
||||
|
||||
remote.kill()
|
||||
assert len(disconnected1) == 1
|
||||
|
||||
with pytest.raises(Error):
|
||||
# Tickle connection so that it gets a chance to dispatch disconnect event.
|
||||
page2.title()
|
||||
assert len(disconnected2) == 1
|
||||
|
||||
|
||||
def test_browser_type_disconnected_event_should_have_browser_as_argument(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = browser_type.connect(remote_server.ws_endpoint)
|
||||
event_payloads = []
|
||||
browser.on("disconnected", lambda b: event_payloads.append(b))
|
||||
browser.close()
|
||||
assert event_payloads[0] == browser
|
||||
|
||||
|
||||
def test_browser_type_connect_set_browser_connected_state(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = browser_type.connect(remote_server.ws_endpoint)
|
||||
assert browser.is_connected()
|
||||
browser.close()
|
||||
assert browser.is_connected() is False
|
||||
|
||||
|
||||
def test_browser_type_connect_should_throw_when_used_after_is_connected_returns_false(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = browser_type.connect(remote_server.ws_endpoint)
|
||||
page = browser.new_page()
|
||||
|
||||
remote_server.kill()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.evaluate("1 + 1")
|
||||
assert "has been closed" in exc_info.value.message
|
||||
assert browser.is_connected() is False
|
||||
|
||||
|
||||
def test_browser_type_connect_should_forward_close_events_to_pages(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser = browser_type.connect(remote.ws_endpoint)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
|
||||
events = []
|
||||
browser.on("disconnected", lambda browser: events.append("browser::disconnected"))
|
||||
context.on("close", lambda context: events.append("context::close"))
|
||||
page.on("close", lambda page: events.append("page::close"))
|
||||
|
||||
browser.close()
|
||||
assert events == ["page::close", "context::close", "browser::disconnected"]
|
||||
remote.kill()
|
||||
assert events == ["page::close", "context::close", "browser::disconnected"]
|
||||
|
||||
|
||||
def test_browser_type_connect_should_forward_close_events_on_remote_kill(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser = browser_type.connect(remote.ws_endpoint)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
|
||||
events = []
|
||||
browser.on("disconnected", lambda context: events.append("browser::disconnected"))
|
||||
context.on("close", lambda context: events.append("context::close"))
|
||||
page.on("close", lambda page: events.append("page::close"))
|
||||
remote.kill()
|
||||
with pytest.raises(Error):
|
||||
page.title()
|
||||
assert events == ["page::close", "context::close", "browser::disconnected"]
|
||||
|
||||
|
||||
def test_connect_to_closed_server_without_hangs(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
remote_server.kill()
|
||||
with pytest.raises(Error) as exc:
|
||||
browser_type.connect(remote_server.ws_endpoint)
|
||||
assert "WebSocket error: " in exc.value.message
|
||||
|
||||
|
||||
def test_browser_type_connect_should_fulfill_with_global_fetch_result(
|
||||
browser_type: BrowserType,
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
playwright: Playwright,
|
||||
server: Server,
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser = browser_type.connect(remote.ws_endpoint)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
|
||||
def handle_request(route: Route) -> None:
|
||||
request = playwright.request.new_context()
|
||||
response = request.get(server.PREFIX + "/simple.json")
|
||||
return route.fulfill(response=response)
|
||||
|
||||
page.route("**/*", handle_request)
|
||||
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert response.json() == {"foo": "bar"}
|
||||
|
||||
remote.kill()
|
||||
|
||||
|
||||
def test_set_input_files_should_preserve_last_modified_timestamp(
|
||||
browser_type: BrowserType,
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser = browser_type.connect(remote.ws_endpoint)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
|
||||
page.set_content("<input type=file multiple=true/>")
|
||||
input = page.locator("input")
|
||||
files: Any = ["file-to-upload.txt", "file-to-upload-2.txt"]
|
||||
input.set_input_files([assetdir / file for file in files])
|
||||
assert input.evaluate("input => [...input.files].map(f => f.name)") == files
|
||||
timestamps = input.evaluate("input => [...input.files].map(f => f.lastModified)")
|
||||
expected_timestamps = [os.path.getmtime(assetdir / file) * 1000 for file in files]
|
||||
|
||||
# On Linux browser sometimes reduces the timestamp by 1ms: 1696272058110.0715 -> 1696272058109 or even
|
||||
# rounds it to seconds in WebKit: 1696272058110 -> 1696272058000.
|
||||
for i in range(len(timestamps)):
|
||||
assert abs(timestamps[i] - expected_timestamps[i]) < 1000
|
||||
@@ -0,0 +1,35 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserType
|
||||
from tests.server import find_free_port
|
||||
|
||||
pytestmark = pytest.mark.only_browser("chromium")
|
||||
|
||||
|
||||
def test_connect_to_an_existing_cdp_session(
|
||||
launch_arguments: Dict, browser_type: BrowserType
|
||||
) -> None:
|
||||
port = find_free_port()
|
||||
browser_server = browser_type.launch(
|
||||
**launch_arguments, args=[f"--remote-debugging-port={port}"]
|
||||
)
|
||||
cdp_browser = browser_type.connect_over_cdp(f"http://127.0.0.1:{port}")
|
||||
assert len(cdp_browser.contexts) == 1
|
||||
cdp_browser.close()
|
||||
browser_server.close()
|
||||
@@ -0,0 +1,80 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, Error, Page
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_work(page: Page) -> None:
|
||||
client = page.context.new_cdp_session(page)
|
||||
events = []
|
||||
client.on("Runtime.consoleAPICalled", lambda params: events.append(params))
|
||||
client.send("Runtime.enable")
|
||||
result = client.send(
|
||||
"Runtime.evaluate",
|
||||
{"expression": "window.foo = 'bar'; console.log('log'); 'result'"},
|
||||
)
|
||||
assert result == {"result": {"type": "string", "value": "result"}}
|
||||
foo = page.evaluate("() => window.foo")
|
||||
assert foo == "bar"
|
||||
assert events[0]["args"][0]["value"] == "log"
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_receive_events(page: Page, server: Server) -> None:
|
||||
client = page.context.new_cdp_session(page)
|
||||
client.send("Network.enable")
|
||||
events = []
|
||||
client.on("Network.requestWillBeSent", lambda event: events.append(event))
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert len(events) == 1
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_be_able_to_detach_session(page: Page) -> None:
|
||||
client = page.context.new_cdp_session(page)
|
||||
client.send("Runtime.enable")
|
||||
eval_response = client.send(
|
||||
"Runtime.evaluate", {"expression": "1 + 2", "returnByValue": True}
|
||||
)
|
||||
assert eval_response["result"]["value"] == 3
|
||||
client.detach()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
client.send("Runtime.evaluate", {"expression": "3 + 1", "returnByValue": True})
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc_info.value.message
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_not_break_page_close(browser: Browser) -> None:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
session = page.context.new_cdp_session(page)
|
||||
session.detach()
|
||||
page.close()
|
||||
context.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_detach_when_page_closes(browser: Browser) -> None:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
session = context.new_cdp_session(page)
|
||||
page.close()
|
||||
with pytest.raises(Error):
|
||||
session.detach()
|
||||
context.close()
|
||||
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
def test_check_the_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
page.check("input")
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_not_check_the_checked_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
page.check("input")
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_uncheck_the_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
page.uncheck("input")
|
||||
assert page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
def test_not_uncheck_the_unchecked_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
page.uncheck("input")
|
||||
assert page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
def test_check_the_box_by_label(page: Page) -> None:
|
||||
page.set_content(
|
||||
'<label for="checkbox"><input id="checkbox" type="checkbox"></input></label>'
|
||||
)
|
||||
page.check("label")
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_check_the_box_outside_label(page: Page) -> None:
|
||||
page.set_content(
|
||||
'<label for="checkbox">Text</label><div><input id="checkbox" type="checkbox"></input></div>'
|
||||
)
|
||||
page.check("label")
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_check_the_box_inside_label_without_id(page: Page) -> None:
|
||||
page.set_content(
|
||||
'<label>Text<span><input id="checkbox" type="checkbox"></input></span></label>'
|
||||
)
|
||||
page.check("label")
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_check_radio(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<input type='radio'>one</input>
|
||||
<input id='two' type='radio'>two</input>
|
||||
<input type='radio'>three</input>"""
|
||||
)
|
||||
page.check("#two")
|
||||
assert page.evaluate("two.checked")
|
||||
|
||||
|
||||
def test_check_the_box_by_aria_role(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<div role='checkbox' id='checkbox'>CHECKBOX</div>
|
||||
<script>
|
||||
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true'))
|
||||
</script>"""
|
||||
)
|
||||
page.check("div")
|
||||
assert page.evaluate("checkbox.getAttribute ('aria-checked')")
|
||||
@@ -0,0 +1,159 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import ConsoleMessage, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_console_should_work(page: Page, browser_name: str) -> None:
|
||||
messages: List[ConsoleMessage] = []
|
||||
page.once("console", lambda m: messages.append(m))
|
||||
with page.expect_console_message():
|
||||
page.evaluate('() => console.log("hello", 5, {foo: "bar"})')
|
||||
assert len(messages) == 1
|
||||
message = messages[0]
|
||||
if browser_name != "firefox":
|
||||
assert message.text == "hello 5 {foo: bar}"
|
||||
assert str(message) == "hello 5 {foo: bar}"
|
||||
else:
|
||||
assert message.text == "hello 5 JSHandle@object"
|
||||
assert str(message) == "hello 5 JSHandle@object"
|
||||
assert message.type == "log"
|
||||
assert message.args[0].json_value() == "hello"
|
||||
assert message.args[1].json_value() == 5
|
||||
assert message.args[2].json_value() == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_console_should_emit_same_log_twice(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m.text))
|
||||
page.evaluate('() => { for (let i = 0; i < 2; ++i ) console.log("hello"); } ')
|
||||
assert messages == ["hello", "hello"]
|
||||
|
||||
|
||||
def test_console_should_use_text_for__str__(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m))
|
||||
page.evaluate('() => console.log("Hello world")')
|
||||
assert len(messages) == 1
|
||||
assert str(messages[0]) == "Hello world"
|
||||
|
||||
|
||||
def test_console_should_work_for_different_console_api_calls(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m))
|
||||
# All console events will be reported before 'page.evaluate' is finished.
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
// A pair of time/timeEnd generates only one Console API call.
|
||||
console.time('calling console.time');
|
||||
console.timeEnd('calling console.time');
|
||||
console.trace('calling console.trace');
|
||||
console.dir('calling console.dir');
|
||||
console.warn('calling console.warn');
|
||||
console.error('calling console.error');
|
||||
console.log(Promise.resolve('should not wait until resolved!'));
|
||||
}"""
|
||||
)
|
||||
assert list(map(lambda msg: msg.type, messages)) == [
|
||||
"timeEnd",
|
||||
"trace",
|
||||
"dir",
|
||||
"warning",
|
||||
"error",
|
||||
"log",
|
||||
]
|
||||
|
||||
assert "calling console.time" in messages[0].text
|
||||
assert list(map(lambda msg: msg.text, messages[1:])) == [
|
||||
"calling console.trace",
|
||||
"calling console.dir",
|
||||
"calling console.warn",
|
||||
"calling console.error",
|
||||
"Promise",
|
||||
]
|
||||
|
||||
|
||||
def test_console_should_not_fail_for_window_object(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
messages = []
|
||||
page.once("console", lambda m: messages.append(m))
|
||||
with page.expect_console_message():
|
||||
page.evaluate("() => console.error(window)")
|
||||
assert len(messages) == 1
|
||||
if browser_name != "firefox":
|
||||
assert messages[0].text == "Window"
|
||||
else:
|
||||
assert messages[0].text == "JSHandle@object"
|
||||
|
||||
|
||||
# Upstream issue https://bugs.webkit.org/show_bug.cgi?id=229515
|
||||
@pytest.mark.skip_browser("webkit")
|
||||
def test_console_should_trigger_correct_Log(page: Page, server: Server) -> None:
|
||||
page.goto("about:blank")
|
||||
with page.expect_console_message() as message:
|
||||
page.evaluate("url => fetch(url).catch(e => {})", server.EMPTY_PAGE)
|
||||
assert (
|
||||
"Access-Control-Allow-Origin" in message.value.text
|
||||
or "CORS" in message.value.text
|
||||
)
|
||||
assert message.value.type == "error"
|
||||
|
||||
|
||||
def test_console_should_have_location_for_console_api_calls(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with page.expect_console_message() as message_info:
|
||||
page.goto(server.PREFIX + "/consolelog.html")
|
||||
message = message_info.value
|
||||
assert message.text == "yellow"
|
||||
assert message.type == "log"
|
||||
location = message.location
|
||||
# Engines have different column notion.
|
||||
assert location["url"] == server.PREFIX + "/consolelog.html"
|
||||
assert location["lineNumber"] == 7
|
||||
# Added in 1.60: location now also exposes line/column aliases for parity with WebError.location.
|
||||
assert location["line"] == 7
|
||||
assert location["column"] == location["columnNumber"]
|
||||
|
||||
|
||||
def test_console_should_not_throw_when_there_are_console_messages_in_detached_iframes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with page.expect_popup() as popup:
|
||||
page.evaluate(
|
||||
"""async() => {
|
||||
// 1. Create a popup that Playwright is not connected to.
|
||||
const win = window.open('');
|
||||
window._popup = win;
|
||||
if (window.document.readyState !== 'complete')
|
||||
new Promise(f => window.addEventListener('load', f));
|
||||
// 2. In this popup, create an iframe that console.logs a message.
|
||||
win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;
|
||||
const frame = win.document.querySelector('iframe');
|
||||
if (!frame.contentDocument || frame.contentDocument.readyState !== 'complete')
|
||||
new Promise(f => frame.addEventListener('load', f));
|
||||
// 3. After that, remove the iframe.
|
||||
frame.remove();
|
||||
}"""
|
||||
)
|
||||
# 4. Connect to the popup and make sure it doesn't throw.
|
||||
assert popup.value.evaluate("1 + 1") == 2
|
||||
@@ -0,0 +1,36 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, BrowserType
|
||||
|
||||
|
||||
def test_context_managers(browser_type: BrowserType, launch_arguments: Dict) -> None:
|
||||
with browser_type.launch(**launch_arguments) as browser:
|
||||
with browser.new_context() as context:
|
||||
with context.new_page():
|
||||
assert len(context.pages) == 1
|
||||
assert len(context.pages) == 0
|
||||
assert len(browser.contexts) == 1
|
||||
assert len(browser.contexts) == 0
|
||||
assert not browser.is_connected()
|
||||
|
||||
|
||||
def test_context_managers_not_hang(context: BrowserContext) -> None:
|
||||
with pytest.raises(Exception, match="Oops!"):
|
||||
with context.new_page():
|
||||
raise Exception("Oops!")
|
||||
@@ -0,0 +1,20 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import BrowserContext
|
||||
|
||||
|
||||
def test_should_expose_debugger_property(context: BrowserContext) -> None:
|
||||
assert context.debugger is context.debugger
|
||||
assert context.debugger.paused_details is None
|
||||
@@ -0,0 +1,671 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, Error, Page
|
||||
from tests.server import Server
|
||||
from tests.sync.utils import Utils
|
||||
|
||||
|
||||
def test_bounding_box(page: Page, server: Server) -> None:
|
||||
page.set_viewport_size({"width": 500, "height": 500})
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
element_handle = page.query_selector(".box:nth-of-type(13)")
|
||||
assert element_handle
|
||||
box = element_handle.bounding_box()
|
||||
assert box == {"x": 100, "y": 50, "width": 50, "height": 50}
|
||||
|
||||
|
||||
def test_bounding_box_handle_nested_frames(page: Page, server: Server) -> None:
|
||||
page.set_viewport_size({"width": 500, "height": 500})
|
||||
page.goto(server.PREFIX + "/frames/nested-frames.html")
|
||||
nested_frame = page.frame(name="dos")
|
||||
assert nested_frame
|
||||
element_handle = nested_frame.query_selector("div")
|
||||
assert element_handle
|
||||
box = element_handle.bounding_box()
|
||||
assert box == {"x": 24, "y": 224, "width": 268, "height": 18}
|
||||
|
||||
|
||||
def test_bounding_box_return_null_for_invisible_elements(page: Page) -> None:
|
||||
page.set_content('<div style="display:none">hi</div>')
|
||||
element = page.query_selector("div")
|
||||
assert element
|
||||
assert element.bounding_box() is None
|
||||
|
||||
|
||||
def test_bounding_box_force_a_layout(page: Page) -> None:
|
||||
page.set_viewport_size({"width": 500, "height": 500})
|
||||
page.set_content('<div style="width: 100px; height: 100px">hello</div>')
|
||||
element_handle = page.query_selector("div")
|
||||
assert element_handle
|
||||
page.evaluate('element => element.style.height = "200px"', element_handle)
|
||||
box = element_handle.bounding_box()
|
||||
assert box == {"x": 8, "y": 8, "width": 100, "height": 200}
|
||||
|
||||
|
||||
def test_bounding_box_with_SVG_nodes(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
|
||||
<rect id="theRect" x="30" y="50" width="200" height="300"></rect>
|
||||
</svg>"""
|
||||
)
|
||||
element = page.query_selector("#therect")
|
||||
assert element
|
||||
pw_bounding_box = element.bounding_box()
|
||||
web_bounding_box = page.evaluate(
|
||||
"""e => {
|
||||
rect = e.getBoundingClientRect()
|
||||
return {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
|
||||
}""",
|
||||
element,
|
||||
)
|
||||
assert pw_bounding_box == web_bounding_box
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_bounding_box_with_page_scale(browser: Browser, server: Server) -> None:
|
||||
context = browser.new_context(
|
||||
viewport={"width": 400, "height": 400}, is_mobile=True
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
button.evaluate(
|
||||
"""button => {
|
||||
document.body.style.margin = '0'
|
||||
button.style.borderWidth = '0'
|
||||
button.style.width = '200px'
|
||||
button.style.height = '20px'
|
||||
button.style.marginLeft = '17px'
|
||||
button.style.marginTop = '23px'
|
||||
}"""
|
||||
)
|
||||
|
||||
box = button.bounding_box()
|
||||
assert box
|
||||
assert round(box["x"] * 100) == 17 * 100
|
||||
assert round(box["y"] * 100) == 23 * 100
|
||||
assert round(box["width"] * 100) == 200 * 100
|
||||
assert round(box["height"] * 100) == 20 * 100
|
||||
context.close()
|
||||
|
||||
|
||||
def test_bounding_box_when_inline_box_child_is_outside_of_viewport(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<style>
|
||||
i {
|
||||
position: absolute
|
||||
top: -1000px
|
||||
}
|
||||
body {
|
||||
margin: 0
|
||||
font-size: 12px
|
||||
}
|
||||
</style>
|
||||
<span><i>woof</i><b>doggo</b></span>
|
||||
"""
|
||||
)
|
||||
handle = page.query_selector("span")
|
||||
assert handle
|
||||
box = handle.bounding_box()
|
||||
assert handle
|
||||
web_bounding_box = handle.evaluate(
|
||||
"""e => {
|
||||
rect = e.getBoundingClientRect();
|
||||
return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
|
||||
}"""
|
||||
)
|
||||
|
||||
def roundbox(b: Any) -> Dict:
|
||||
return {
|
||||
"x": round(b["x"] * 100),
|
||||
"y": round(b["y"] * 100),
|
||||
"width": round(b["width"] * 100),
|
||||
"height": round(b["height"] * 100),
|
||||
}
|
||||
|
||||
assert roundbox(box) == roundbox(web_bounding_box)
|
||||
|
||||
|
||||
def test_content_frame(page: Page, server: Server, utils: Utils) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
element_handle = page.query_selector("#frame1")
|
||||
assert element_handle
|
||||
frame = element_handle.content_frame()
|
||||
assert frame == page.frames[1]
|
||||
|
||||
|
||||
def test_content_frame_for_non_iframes(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = frame.evaluate_handle("document.body").as_element()
|
||||
assert element_handle
|
||||
assert element_handle.content_frame() is None
|
||||
|
||||
|
||||
def test_content_frame_for_document_element(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = frame.evaluate_handle("document.documentElement").as_element()
|
||||
assert element_handle
|
||||
assert element_handle.content_frame() is None
|
||||
|
||||
|
||||
def test_owner_frame(page: Page, server: Server, utils: Utils) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = frame.evaluate_handle("document.body").as_element()
|
||||
assert element_handle
|
||||
assert element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
def test_owner_frame_for_cross_process_iframes(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html")
|
||||
frame = page.frames[1]
|
||||
element_handle = frame.evaluate_handle("document.body").as_element()
|
||||
assert element_handle
|
||||
assert element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
def test_owner_frame_for_document(page: Page, server: Server, utils: Utils) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = frame.evaluate_handle("document").as_element()
|
||||
assert element_handle
|
||||
assert element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
def test_owner_frame_for_iframe_elements(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.main_frame
|
||||
element_handle = frame.evaluate_handle(
|
||||
'document.querySelector("#frame1")'
|
||||
).as_element()
|
||||
assert element_handle
|
||||
assert element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
def test_owner_frame_for_cross_frame_evaluations(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.main_frame
|
||||
element_handle = frame.evaluate_handle(
|
||||
'document.querySelector("#frame1").contentWindow.document.body'
|
||||
).as_element()
|
||||
assert element_handle
|
||||
assert element_handle.owner_frame() == frame.child_frames[0]
|
||||
|
||||
|
||||
def test_owner_frame_for_detached_elements(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
div_handle = page.evaluate_handle(
|
||||
"""() => {
|
||||
div = document.createElement('div');
|
||||
document.body.appendChild(div);
|
||||
return div;
|
||||
}"""
|
||||
).as_element()
|
||||
assert div_handle
|
||||
|
||||
assert div_handle.owner_frame() == page.main_frame
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
div = document.querySelector('div')
|
||||
document.body.removeChild(div)
|
||||
}"""
|
||||
)
|
||||
assert div_handle.owner_frame() == page.main_frame
|
||||
|
||||
|
||||
def test_click(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
button.click()
|
||||
assert page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
def test_click_with_node_removed(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
page.evaluate('delete window["Node"]')
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
button.click()
|
||||
assert page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
def test_click_for_shadow_dom_v1(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/shadow.html")
|
||||
button_handle = page.evaluate_handle("button").as_element()
|
||||
assert button_handle
|
||||
button_handle.click()
|
||||
assert page.evaluate("clicked")
|
||||
|
||||
|
||||
def test_click_for_TextNodes(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
buttonTextNode = page.evaluate_handle(
|
||||
'document.querySelector("button").firstChild'
|
||||
).as_element()
|
||||
assert buttonTextNode
|
||||
buttonTextNode.click()
|
||||
assert page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
def test_click_throw_for_detached_nodes(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
page.evaluate("button => button.remove()", button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
button.click()
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
def test_click_throw_for_hidden_nodes_with_force(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
page.evaluate('button => button.style.display = "none"', button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
button.click(force=True)
|
||||
assert "Element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
def test_click_throw_for_recursively_hidden_nodes_with_force(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
page.evaluate('button => button.parentElement.style.display = "none"', button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
button.click(force=True)
|
||||
assert "Element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
def test_click_throw_for__br__elements_with_force(page: Page) -> None:
|
||||
page.set_content("hello<br>goodbye")
|
||||
br = page.query_selector("br")
|
||||
assert br
|
||||
with pytest.raises(Error) as exc_info:
|
||||
br.click(force=True)
|
||||
assert "Element is outside of the viewport" in exc_info.value.message
|
||||
|
||||
|
||||
def test_double_click_the_button(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.double = false;
|
||||
button = document.querySelector('button');
|
||||
button.addEventListener('dblclick', event => {
|
||||
window.double = true;
|
||||
});
|
||||
}"""
|
||||
)
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
button.dblclick()
|
||||
assert page.evaluate("double")
|
||||
assert page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
def test_hover(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/scrollable.html")
|
||||
button = page.query_selector("#button-6")
|
||||
assert button
|
||||
button.hover()
|
||||
assert page.evaluate('document.querySelector("button:hover").id') == "button-6"
|
||||
|
||||
|
||||
def test_hover_when_node_is_removed(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/scrollable.html")
|
||||
page.evaluate('delete window["Node"]')
|
||||
button = page.query_selector("#button-6")
|
||||
assert button
|
||||
button.hover()
|
||||
assert page.evaluate('document.querySelector("button:hover").id') == "button-6"
|
||||
|
||||
|
||||
def test_scroll(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/offscreenbuttons.html")
|
||||
for i in range(11):
|
||||
button = page.query_selector(f"#btn{i}")
|
||||
assert button
|
||||
before = button.evaluate(
|
||||
"""button => {
|
||||
return button.getBoundingClientRect().right - window.innerWidth
|
||||
}"""
|
||||
)
|
||||
|
||||
assert before == 10 * i
|
||||
button.scroll_into_view_if_needed()
|
||||
after = button.evaluate(
|
||||
"""button => {
|
||||
return button.getBoundingClientRect().right - window.innerWidth
|
||||
}"""
|
||||
)
|
||||
|
||||
assert after <= 0
|
||||
page.evaluate("() => window.scrollTo(0, 0)")
|
||||
|
||||
|
||||
def test_scroll_should_throw_for_detached_element(page: Page) -> None:
|
||||
page.set_content("<div>Hello</div>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
div.evaluate("div => div.remove()")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
div.scroll_into_view_if_needed()
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
def test_should_timeout_waiting_for_visible(page: Page) -> None:
|
||||
page.set_content('<div style="display:none">Hello</div>')
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
with pytest.raises(Error) as exc_info:
|
||||
div.scroll_into_view_if_needed(timeout=3000)
|
||||
assert "element is not visible" in exc_info.value.message
|
||||
assert "retrying scroll into view action" in exc_info.value.message
|
||||
|
||||
|
||||
def test_fill_input(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
handle = page.query_selector("input")
|
||||
assert handle
|
||||
handle.fill("some value")
|
||||
assert page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
def test_fill_input_when_Node_is_removed(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
page.evaluate('delete window["Node"]')
|
||||
handle = page.query_selector("input")
|
||||
assert handle
|
||||
handle.fill("some value")
|
||||
assert page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
def test_select_textarea(
|
||||
page: Page, server: Server, is_firefox: bool, is_webkit: bool
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = page.query_selector("textarea")
|
||||
assert textarea
|
||||
textarea.evaluate('textarea => textarea.value = "some value"')
|
||||
textarea.select_text()
|
||||
if is_firefox or is_webkit:
|
||||
assert textarea.evaluate("el => el.selectionStart") == 0
|
||||
assert textarea.evaluate("el => el.selectionEnd") == 10
|
||||
else:
|
||||
assert page.evaluate("() => window.getSelection().toString()") == "some value"
|
||||
|
||||
|
||||
def test_select_input(
|
||||
page: Page, server: Server, is_firefox: bool, is_webkit: bool
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
input = page.query_selector("input")
|
||||
assert input
|
||||
input.evaluate('input => input.value = "some value"')
|
||||
input.select_text()
|
||||
if is_firefox or is_webkit:
|
||||
assert input.evaluate("el => el.selectionStart") == 0
|
||||
assert input.evaluate("el => el.selectionEnd") == 10
|
||||
else:
|
||||
assert page.evaluate("() => window.getSelection().toString()") == "some value"
|
||||
|
||||
|
||||
def test_select_text_select_plain_div(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
div = page.query_selector("div.plain")
|
||||
assert div
|
||||
div.select_text()
|
||||
assert page.evaluate("() => window.getSelection().toString()") == "Plain div"
|
||||
|
||||
|
||||
def test_select_text_timeout_waiting_for_invisible_element(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = page.query_selector("textarea")
|
||||
assert textarea
|
||||
textarea.evaluate('e => e.style.display = "none"')
|
||||
with pytest.raises(Error) as exc_info:
|
||||
textarea.select_text(timeout=3000)
|
||||
assert "element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
def test_a_nice_preview(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/dom.html")
|
||||
outer = page.query_selector("#outer")
|
||||
inner = page.query_selector("#inner")
|
||||
assert inner
|
||||
check = page.query_selector("#check")
|
||||
text = inner.evaluate_handle("e => e.firstChild")
|
||||
page.evaluate("1") # Give them a chance to calculate the preview.
|
||||
assert str(outer) == 'JSHandle@<div id="outer" name="value">…</div>'
|
||||
assert str(inner) == 'JSHandle@<div id="inner">Text,↵more text</div>'
|
||||
assert str(text) == "JSHandle@#text=Text,↵more text"
|
||||
assert (
|
||||
str(check) == 'JSHandle@<input checked id="check" foo="bar"" type="checkbox"/>'
|
||||
)
|
||||
|
||||
|
||||
def test_get_attribute(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = page.query_selector("#outer")
|
||||
assert handle
|
||||
assert handle.get_attribute("name") == "value"
|
||||
assert page.get_attribute("#outer", "name") == "value"
|
||||
|
||||
|
||||
def test_inner_html(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = page.query_selector("#outer")
|
||||
assert handle
|
||||
assert handle.inner_html() == '<div id="inner">Text,\nmore text</div>'
|
||||
assert page.inner_html("#outer") == '<div id="inner">Text,\nmore text</div>'
|
||||
|
||||
|
||||
def test_inner_text(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = page.query_selector("#inner")
|
||||
assert handle
|
||||
assert handle.inner_text() == "Text, more text"
|
||||
assert page.inner_text("#inner") == "Text, more text"
|
||||
|
||||
|
||||
def test_inner_text_should_throw(page: Page) -> None:
|
||||
page.set_content("<svg>text</svg>")
|
||||
with pytest.raises(Error) as exc_info1:
|
||||
page.inner_text("svg")
|
||||
assert " Node is not an HTMLElement" in exc_info1.value.message
|
||||
|
||||
handle = page.query_selector("svg")
|
||||
assert handle
|
||||
with pytest.raises(Error) as exc_info2:
|
||||
handle.inner_text()
|
||||
assert " Node is not an HTMLElement" in exc_info2.value.message
|
||||
|
||||
|
||||
def test_text_content(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = page.query_selector("#inner")
|
||||
assert handle
|
||||
assert handle.text_content() == "Text,\nmore text"
|
||||
assert page.text_content("#inner") == "Text,\nmore text"
|
||||
|
||||
|
||||
def test_check_the_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
input = page.query_selector("input")
|
||||
assert input
|
||||
input.check()
|
||||
assert page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
def test_uncheck_the_box(page: Page) -> None:
|
||||
page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
input = page.query_selector("input")
|
||||
assert input
|
||||
input.uncheck()
|
||||
assert page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
def test_select_single_option(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
select = page.query_selector("select")
|
||||
assert select
|
||||
select.select_option(value="blue")
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
def test_focus_a_button(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/button.html")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
assert button.evaluate("button => document.activeElement === button") is False
|
||||
button.focus()
|
||||
assert button.evaluate("button => document.activeElement === button")
|
||||
|
||||
|
||||
def test_is_visible_and_is_hidden_should_work(page: Page) -> None:
|
||||
page.set_content("<div>Hi</div><span></span>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
assert div.is_visible()
|
||||
assert div.is_hidden() is False
|
||||
assert page.is_visible("div")
|
||||
assert page.is_hidden("div") is False
|
||||
span = page.query_selector("span")
|
||||
assert span
|
||||
assert span.is_visible() is False
|
||||
assert span.is_hidden()
|
||||
assert page.is_visible("span") is False
|
||||
assert page.is_hidden("span")
|
||||
|
||||
|
||||
def test_is_enabled_and_is_disabled_should_work(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<button disabled>button1</button>
|
||||
<button>button2</button>
|
||||
<div>div</div>
|
||||
"""
|
||||
)
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
assert div.is_enabled()
|
||||
assert div.is_disabled() is False
|
||||
assert page.is_enabled("div")
|
||||
assert page.is_disabled("div") is False
|
||||
button1 = page.query_selector(":text('button1')")
|
||||
assert button1
|
||||
assert button1.is_enabled() is False
|
||||
assert button1.is_disabled()
|
||||
assert page.is_enabled(":text('button1')") is False
|
||||
assert page.is_disabled(":text('button1')")
|
||||
button2 = page.query_selector(":text('button2')")
|
||||
assert button2
|
||||
assert button2.is_enabled()
|
||||
assert button2.is_disabled() is False
|
||||
assert page.is_enabled(":text('button2')")
|
||||
assert page.is_disabled(":text('button2')") is False
|
||||
|
||||
|
||||
def test_is_editable_should_work(page: Page) -> None:
|
||||
page.set_content("<input id=input1 disabled><textarea></textarea><input id=input2>")
|
||||
page.eval_on_selector("textarea", "t => t.readOnly = true")
|
||||
input1 = page.query_selector("#input1")
|
||||
assert input1
|
||||
assert input1.is_editable() is False
|
||||
assert page.is_editable("#input1") is False
|
||||
input2 = page.query_selector("#input2")
|
||||
assert input2
|
||||
assert input2.is_editable()
|
||||
assert page.is_editable("#input2")
|
||||
textarea = page.query_selector("textarea")
|
||||
assert textarea
|
||||
assert textarea.is_editable() is False
|
||||
assert page.is_editable("textarea") is False
|
||||
|
||||
|
||||
def test_is_checked_should_work(page: Page) -> None:
|
||||
page.set_content('<input type="checkbox" checked><div>Not a checkbox</div>')
|
||||
handle = page.query_selector("input")
|
||||
assert handle
|
||||
assert handle.is_checked()
|
||||
assert page.is_checked("input")
|
||||
handle.evaluate("input => input.checked = false")
|
||||
assert handle.is_checked() is False
|
||||
assert page.is_checked("input") is False
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.is_checked("div")
|
||||
assert "Not a checkbox or radio button" in exc_info.value.message
|
||||
|
||||
|
||||
def test_input_value(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
element = page.query_selector("input")
|
||||
assert element
|
||||
element.fill("my-text-content")
|
||||
assert element.input_value() == "my-text-content"
|
||||
|
||||
element.fill("")
|
||||
assert element.input_value() == ""
|
||||
|
||||
|
||||
def test_set_checked(page: Page) -> None:
|
||||
page.set_content("`<input id='checkbox' type='checkbox'></input>`")
|
||||
input = page.query_selector("input")
|
||||
assert input
|
||||
input.set_checked(True)
|
||||
assert page.evaluate("checkbox.checked")
|
||||
input.set_checked(False)
|
||||
assert page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
def test_should_allow_disposing_twice(page: Page) -> None:
|
||||
page.set_content("<section>39</section>")
|
||||
element = page.query_selector("section")
|
||||
assert element
|
||||
element.dispose()
|
||||
element.dispose()
|
||||
@@ -0,0 +1,119 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page
|
||||
|
||||
|
||||
def test_should_wait_for_visible(page: Page) -> None:
|
||||
page.set_content('<div id=div style="display:none">content</div>')
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
page.evaluate('setTimeout(() => div.style.display = "block", 500)')
|
||||
assert div.is_visible() is False
|
||||
div.wait_for_element_state("visible")
|
||||
assert div.is_visible()
|
||||
|
||||
|
||||
def test_should_wait_for_already_visible(page: Page) -> None:
|
||||
page.set_content("<div>content</div>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
div.wait_for_element_state("visible")
|
||||
|
||||
|
||||
def test_should_timeout_waiting_for_visible(page: Page) -> None:
|
||||
page.set_content('<div style="display:none">content</div>')
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
with pytest.raises(Error) as exc_info:
|
||||
div.wait_for_element_state("visible", timeout=1000)
|
||||
assert "Timeout 1000ms exceeded" in exc_info.value.message
|
||||
|
||||
|
||||
def test_should_throw_waiting_for_visible_when_detached(page: Page) -> None:
|
||||
page.set_content('<div id=div style="display:none">content</div>')
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
page.evaluate("setTimeout(() => div.remove(), 500)")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
div.wait_for_element_state("visible")
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
def test_should_wait_for_hidden(page: Page) -> None:
|
||||
page.set_content("<div id=div>content</div>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
page.evaluate('setTimeout(() => div.style.display = "none", 500)')
|
||||
assert div.is_hidden() is False
|
||||
div.wait_for_element_state("hidden")
|
||||
assert div.is_hidden()
|
||||
|
||||
|
||||
def test_should_wait_for_already_hidden(page: Page) -> None:
|
||||
page.set_content("<div></div>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
div.wait_for_element_state("hidden")
|
||||
|
||||
|
||||
def test_should_wait_for_hidden_when_detached(page: Page) -> None:
|
||||
page.set_content("<div id=div>content</div>")
|
||||
div = page.query_selector("div")
|
||||
assert div
|
||||
page.evaluate("setTimeout(() => div.remove(), 500)")
|
||||
div.wait_for_element_state("hidden")
|
||||
assert div.is_hidden()
|
||||
|
||||
|
||||
def test_should_wait_for_enabled_button(page: Page) -> None:
|
||||
page.set_content("<button id=button disabled><span>Target</span></button>")
|
||||
span = page.query_selector("text=Target")
|
||||
assert span
|
||||
assert span.is_enabled() is False
|
||||
page.evaluate("setTimeout(() => button.disabled = false, 500)")
|
||||
span.wait_for_element_state("enabled")
|
||||
assert span.is_enabled()
|
||||
|
||||
|
||||
def test_should_throw_waiting_for_enabled_when_detached(page: Page) -> None:
|
||||
page.set_content("<button id=button disabled>Target</button>")
|
||||
button = page.query_selector("button")
|
||||
assert button
|
||||
page.evaluate("setTimeout(() => button.remove(), 500)")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
button.wait_for_element_state("enabled")
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
def test_should_wait_for_disabled_button(page: Page) -> None:
|
||||
page.set_content("<button id=button><span>Target</span></button>")
|
||||
span = page.query_selector("text=Target")
|
||||
assert span
|
||||
assert span.is_disabled() is False
|
||||
page.evaluate("setTimeout(() => button.disabled = true, 500)")
|
||||
span.wait_for_element_state("disabled")
|
||||
assert span.is_disabled()
|
||||
|
||||
|
||||
def test_should_wait_for_editable_input(page: Page) -> None:
|
||||
page.set_content("<input id=input readonly>")
|
||||
input = page.query_selector("input")
|
||||
assert input
|
||||
page.evaluate("setTimeout(() => input.readOnly = false, 500)")
|
||||
assert input.is_editable() is False
|
||||
input.wait_for_element_state("editable")
|
||||
assert input.is_editable()
|
||||
@@ -0,0 +1,72 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Page, expect
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_to_be_in_viewport_should_work(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<div id=big style="height: 10000px;"></div>
|
||||
<div id=small>foo</div>
|
||||
"""
|
||||
)
|
||||
expect(page.locator("#big")).to_be_in_viewport()
|
||||
expect(page.locator("#small")).not_to_be_in_viewport()
|
||||
page.locator("#small").scroll_into_view_if_needed()
|
||||
expect(page.locator("#small")).to_be_in_viewport()
|
||||
expect(page.locator("#small")).to_be_in_viewport(ratio=1)
|
||||
|
||||
|
||||
def test_to_be_in_viewport_should_respect_ratio_option(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<style>body, div, html { padding: 0; margin: 0; }</style>
|
||||
<div id=big style="height: 400vh;"></div>
|
||||
"""
|
||||
)
|
||||
expect(page.locator("div")).to_be_in_viewport()
|
||||
expect(page.locator("div")).to_be_in_viewport(ratio=0.1)
|
||||
expect(page.locator("div")).to_be_in_viewport(ratio=0.2)
|
||||
|
||||
expect(page.locator("div")).to_be_in_viewport(ratio=0.25)
|
||||
# In this test, element's ratio is 0.25.
|
||||
expect(page.locator("div")).not_to_be_in_viewport(ratio=0.26)
|
||||
|
||||
expect(page.locator("div")).not_to_be_in_viewport(ratio=0.3)
|
||||
expect(page.locator("div")).not_to_be_in_viewport(ratio=0.7)
|
||||
expect(page.locator("div")).not_to_be_in_viewport(ratio=0.8)
|
||||
|
||||
|
||||
def test_to_be_in_viewport_should_have_good_stack(page: Page, server: Server) -> None:
|
||||
with pytest.raises(AssertionError) as exc_info:
|
||||
expect(page.locator("body")).not_to_be_in_viewport(timeout=1000)
|
||||
assert 'unexpected value "viewport ratio' in str(exc_info.value)
|
||||
|
||||
|
||||
def test_to_be_in_viewport_should_report_intersection_even_if_fully_covered_by_other_element(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<h1>hello</h1>
|
||||
<div style="position: relative; height: 10000px; top: -5000px;></div>
|
||||
"""
|
||||
)
|
||||
expect(page.locator("h1")).to_be_in_viewport()
|
||||
@@ -0,0 +1,101 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Generator, List, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, BrowserType
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def launch_persistent_context(
|
||||
browser_type: BrowserType,
|
||||
browser_channel: Optional[str],
|
||||
tmp_path: Path,
|
||||
launch_arguments: Dict[str, Any],
|
||||
is_headless_shell: bool,
|
||||
) -> Generator[Callable[..., BrowserContext], None, None]:
|
||||
if browser_channel and browser_channel.startswith("chrome"):
|
||||
pytest.skip(
|
||||
"--load-extension is not supported in Chrome anymore. https://groups.google.com/a/chromium.org/g/chromium-extensions/c/1-g8EFx2BBY/m/S0ET5wPjCAAJ"
|
||||
)
|
||||
if is_headless_shell:
|
||||
pytest.skip("Headless Shell has no support for extensions")
|
||||
|
||||
contexts: List[BrowserContext] = []
|
||||
|
||||
def launch(extension_path: str, **kwargs: Any) -> BrowserContext:
|
||||
context = browser_type.launch_persistent_context(
|
||||
str(tmp_path),
|
||||
**launch_arguments,
|
||||
**kwargs,
|
||||
args=[
|
||||
f"--disable-extensions-except={extension_path}",
|
||||
f"--load-extension={extension_path}",
|
||||
],
|
||||
)
|
||||
contexts.append(context)
|
||||
return context
|
||||
|
||||
yield launch
|
||||
|
||||
for context in contexts:
|
||||
context.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_give_access_to_the_service_worker(
|
||||
launch_persistent_context: Callable[..., BrowserContext],
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
extension_path = str(assetdir / "extension-mv3-simple")
|
||||
context = launch_persistent_context(extension_path)
|
||||
service_workers = context.service_workers
|
||||
service_worker = (
|
||||
service_workers[0]
|
||||
if len(service_workers)
|
||||
else context.wait_for_event("serviceworker")
|
||||
)
|
||||
assert service_worker
|
||||
assert service_worker in context.service_workers
|
||||
while not service_worker.evaluate("globalThis.MAGIC") == 42:
|
||||
context.pages[0].wait_for_timeout(100)
|
||||
context.close()
|
||||
assert len(context.background_pages) == 0
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_give_access_to_the_service_worker_when_recording_video(
|
||||
launch_persistent_context: Callable[..., BrowserContext],
|
||||
tmp_path: Path,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
extension_path = str(assetdir / "extension-mv3-simple")
|
||||
context = launch_persistent_context(
|
||||
extension_path, record_video_dir=(tmp_path / "videos")
|
||||
)
|
||||
service_workers = context.service_workers
|
||||
service_worker = (
|
||||
service_workers[0]
|
||||
if len(service_workers)
|
||||
else context.wait_for_event("serviceworker")
|
||||
)
|
||||
assert service_worker
|
||||
assert service_worker in context.service_workers
|
||||
while not service_worker.evaluate("globalThis.MAGIC") == 42:
|
||||
context.pages[0].wait_for_timeout(100)
|
||||
context.close()
|
||||
assert len(context.background_pages) == 0
|
||||
@@ -0,0 +1,340 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, cast
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import (
|
||||
BrowserContext,
|
||||
Error,
|
||||
FilePayload,
|
||||
FormData,
|
||||
Page,
|
||||
)
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
def test_get_should_work(context: BrowserContext, server: Server) -> None:
|
||||
response = context.request.get(server.PREFIX + "/simple.json")
|
||||
assert response.url == server.PREFIX + "/simple.json"
|
||||
assert response.status == 200
|
||||
assert response.status_text == "OK"
|
||||
assert response.ok is True
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert {
|
||||
"name": "Content-Type",
|
||||
"value": "application/json",
|
||||
} in response.headers_array
|
||||
assert response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
def test_fetch_should_work(context: BrowserContext, server: Server) -> None:
|
||||
response = context.request.fetch(server.PREFIX + "/simple.json")
|
||||
assert response.url == server.PREFIX + "/simple.json"
|
||||
assert response.status == 200
|
||||
assert response.status_text == "OK"
|
||||
assert response.ok is True
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert {
|
||||
"name": "Content-Type",
|
||||
"value": "application/json",
|
||||
} in response.headers_array
|
||||
assert response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
def test_should_throw_on_network_error(context: BrowserContext, server: Server) -> None:
|
||||
server.set_route("/test", lambda request: request.loseConnection())
|
||||
with pytest.raises(Error, match="socket hang up"):
|
||||
context.request.fetch(server.PREFIX + "/test")
|
||||
|
||||
|
||||
def test_should_add_session_cookies_to_request(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"url": server.EMPTY_PAGE,
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": "Lax",
|
||||
}
|
||||
]
|
||||
)
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.get(server.EMPTY_PAGE)
|
||||
assert server_req.value.getHeader("Cookie") == "username=John Doe"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_support_query_params(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
expected_params = {"p1": "v1", "парам2": "знач2"}
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
getattr(context.request, method)(
|
||||
server.EMPTY_PAGE + "?p1=foo", params=expected_params
|
||||
)
|
||||
assert list(map(lambda x: x.decode(), server_req.value.args["p1".encode()])) == [
|
||||
"foo",
|
||||
"v1",
|
||||
]
|
||||
assert server_req.value.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_support_params_passed_as_object(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
params = {
|
||||
"param1": "value1",
|
||||
"парам2": "знач2",
|
||||
}
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
getattr(context.request, method)(server.EMPTY_PAGE, params=params)
|
||||
assert server_req.value.args["param1".encode()][0].decode() == "value1"
|
||||
assert len(server_req.value.args["param1".encode()]) == 1
|
||||
assert server_req.value.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_support_params_passed_as_strings(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
params = "?param1=value1¶m1=value2&парам2=знач2"
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
getattr(context.request, method)(server.EMPTY_PAGE, params=params)
|
||||
assert list(
|
||||
map(lambda x: x.decode(), server_req.value.args["param1".encode()])
|
||||
) == ["value1", "value2"]
|
||||
assert len(server_req.value.args["param1".encode()]) == 2
|
||||
assert server_req.value.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_support_fail_on_status_code(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
with pytest.raises(Error, match="404 Not Found"):
|
||||
getattr(context.request, method)(
|
||||
server.PREFIX + "/this-does-clearly-not-exist.html",
|
||||
fail_on_status_code=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_support_ignore_https_errors_option(
|
||||
context: BrowserContext, https_server: Server, method: str
|
||||
) -> None:
|
||||
response = getattr(context.request, method)(
|
||||
https_server.EMPTY_PAGE, ignore_https_errors=True
|
||||
)
|
||||
assert response.ok
|
||||
assert response.status == 200
|
||||
|
||||
|
||||
def test_should_not_add_context_cookie_if_cookie_header_passed_as_parameter(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"url": server.EMPTY_PAGE,
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": "Lax",
|
||||
}
|
||||
]
|
||||
)
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.get(server.EMPTY_PAGE, headers={"Cookie": "foo=bar"})
|
||||
assert server_req.value.getHeader("Cookie") == "foo=bar"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["delete", "patch", "post", "put"])
|
||||
def test_should_support_post_data(
|
||||
context: BrowserContext, method: str, server: Server
|
||||
) -> None:
|
||||
def support_post_data(fetch_data: Any, request_post_data: Any) -> None:
|
||||
with server.expect_request("/simple.json") as request:
|
||||
response = getattr(context.request, method)(
|
||||
server.PREFIX + "/simple.json", data=fetch_data
|
||||
)
|
||||
assert request.value.method.decode() == method.upper()
|
||||
assert request.value.post_body == request_post_data
|
||||
assert response.status == 200
|
||||
assert response.url == server.PREFIX + "/simple.json"
|
||||
assert request.value.getHeader("Content-Length") == str(
|
||||
len(must(request.value.post_body))
|
||||
)
|
||||
|
||||
support_post_data("My request", "My request".encode())
|
||||
support_post_data(b"My request", "My request".encode())
|
||||
support_post_data(["my", "request"], json.dumps(["my", "request"]).encode())
|
||||
support_post_data({"my": "request"}, json.dumps({"my": "request"}).encode())
|
||||
with pytest.raises(Error, match="Unsupported 'data' type: <class 'function'>"):
|
||||
support_post_data(lambda: None, None)
|
||||
|
||||
|
||||
def test_should_support_application_x_www_form_urlencoded(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.post(
|
||||
server.PREFIX + "/empty.html",
|
||||
form={
|
||||
"firstName": "John",
|
||||
"lastName": "Doe",
|
||||
"file": "f.js",
|
||||
},
|
||||
)
|
||||
assert server_req.value.method == b"POST"
|
||||
assert (
|
||||
server_req.value.getHeader("Content-Type")
|
||||
== "application/x-www-form-urlencoded"
|
||||
)
|
||||
body = must(server_req.value.post_body).decode()
|
||||
assert server_req.value.getHeader("Content-Length") == str(len(body))
|
||||
params: Dict[bytes, List[bytes]] = parse_qs(server_req.value.post_body)
|
||||
assert params[b"firstName"] == [b"John"]
|
||||
assert params[b"lastName"] == [b"Doe"]
|
||||
assert params[b"file"] == [b"f.js"]
|
||||
|
||||
|
||||
def test_should_support_multipart_form_data(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
file: FilePayload = {
|
||||
"name": "f.js",
|
||||
"mimeType": "text/javascript",
|
||||
"buffer": b"var x = 10;\r\n;console.log(x);",
|
||||
}
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.post(
|
||||
server.PREFIX + "/empty.html",
|
||||
multipart={
|
||||
"firstName": "John",
|
||||
"lastName": "Doe",
|
||||
"file": file,
|
||||
},
|
||||
)
|
||||
assert server_req.value.method == b"POST"
|
||||
content_type = server_req.value.getHeader("Content-Type")
|
||||
assert content_type
|
||||
assert content_type.startswith("multipart/form-data; ")
|
||||
assert server_req.value.getHeader("Content-Length") == str(
|
||||
len(must(server_req.value.post_body))
|
||||
)
|
||||
assert server_req.value.args[b"firstName"] == [b"John"]
|
||||
assert server_req.value.args[b"lastName"] == [b"Doe"]
|
||||
assert server_req.value.args[b"file"][0] == file["buffer"]
|
||||
|
||||
|
||||
def test_should_support_form_data_with_repeated_keys(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
form = FormData()
|
||||
form.append("name", "John")
|
||||
form.append("name", "Doe")
|
||||
form.set("email", "john@example.com")
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.post(server.EMPTY_PAGE, form=form)
|
||||
params = parse_qs(must(server_req.value.post_body))
|
||||
assert params[b"name"] == [b"John", b"Doe"]
|
||||
assert params[b"email"] == [b"john@example.com"]
|
||||
|
||||
|
||||
def test_should_reject_file_value_in_form(
|
||||
context: BrowserContext, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
file = tmp_path / "f.txt"
|
||||
file.write_bytes(b"hello")
|
||||
form = FormData()
|
||||
form.set("attachment", file)
|
||||
with pytest.raises(Error, match="Use 'multipart' for file uploads"):
|
||||
context.request.post(server.EMPTY_PAGE, form=form)
|
||||
|
||||
|
||||
def test_should_support_multipart_form_data_with_multiple_files_in_one_field(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
file1: FilePayload = {
|
||||
"name": "f1.txt",
|
||||
"mimeType": "text/plain",
|
||||
"buffer": b"file 1 content",
|
||||
}
|
||||
file2: FilePayload = {
|
||||
"name": "f2.txt",
|
||||
"mimeType": "text/plain",
|
||||
"buffer": b"file 2 content",
|
||||
}
|
||||
form = FormData()
|
||||
form.append("files", file1)
|
||||
form.append("files", file2)
|
||||
form.set("user", "alice")
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.post(server.EMPTY_PAGE, multipart=form)
|
||||
assert cast(str, server_req.value.getHeader("Content-Type")).startswith(
|
||||
"multipart/form-data; "
|
||||
)
|
||||
assert server_req.value.args[b"user"] == [b"alice"]
|
||||
assert server_req.value.args[b"files"] == [file1["buffer"], file2["buffer"]]
|
||||
|
||||
|
||||
def test_should_support_multipart_form_data_with_path_value(
|
||||
context: BrowserContext, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
file = tmp_path / "data.csv"
|
||||
file.write_bytes(b"a,b,c\n1,2,3\n")
|
||||
form = FormData()
|
||||
form.set("attachment", file)
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.post(server.EMPTY_PAGE, multipart=form)
|
||||
assert cast(str, server_req.value.getHeader("Content-Type")).startswith(
|
||||
"multipart/form-data; "
|
||||
)
|
||||
assert server_req.value.args[b"attachment"] == [b"a,b,c\n1,2,3\n"]
|
||||
|
||||
|
||||
def test_should_add_default_headers(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
context.request.get(server.EMPTY_PAGE)
|
||||
assert server_req.value.getHeader("Accept") == "*/*"
|
||||
assert server_req.value.getHeader("Accept-Encoding") == "gzip,deflate,br"
|
||||
assert server_req.value.getHeader("User-Agent") == page.evaluate(
|
||||
"() => navigator.userAgent"
|
||||
)
|
||||
@@ -0,0 +1,390 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import APIResponse, Error, Playwright, StorageState
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
def test_should_work(playwright: Playwright, method: str, server: Server) -> None:
|
||||
request = playwright.request.new_context()
|
||||
response: APIResponse = getattr(request, method)(server.PREFIX + "/simple.json")
|
||||
assert response.status == 200
|
||||
assert response.status_text == "OK"
|
||||
assert response.ok is True
|
||||
assert response.url == server.PREFIX + "/simple.json"
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert {
|
||||
"name": "Content-Type",
|
||||
"value": "application/json",
|
||||
} in response.headers_array
|
||||
assert response.text() == ("" if method == "head" else '{"foo": "bar"}\n')
|
||||
|
||||
|
||||
def test_should_dispose_global_request(playwright: Playwright, server: Server) -> None:
|
||||
request = playwright.request.new_context()
|
||||
response = request.get(server.PREFIX + "/simple.json")
|
||||
assert response.json() == {"foo": "bar"}
|
||||
response.dispose()
|
||||
with pytest.raises(Error, match="Response has been disposed"):
|
||||
response.body()
|
||||
|
||||
|
||||
def test_should_support_global_user_agent_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context(user_agent="My Agent")
|
||||
response = request.get(server.PREFIX + "/empty.html")
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
request.get(server.EMPTY_PAGE)
|
||||
assert response.ok is True
|
||||
assert response.url == server.EMPTY_PAGE
|
||||
|
||||
assert server_req.value.getHeader("user-agent") == "My Agent"
|
||||
|
||||
|
||||
def test_should_support_global_timeout_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context(timeout=100)
|
||||
server.set_route("/empty.html", lambda req: None)
|
||||
with pytest.raises(Error, match="Timeout 100ms exceeded"):
|
||||
request.get(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_should_support_timeout_option_in_get_method(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context()
|
||||
server.set_route("/empty.html", lambda req: None)
|
||||
with pytest.raises(Error, match="APIRequestContext.get: Timeout 123ms exceeded."):
|
||||
request.get(server.EMPTY_PAGE, timeout=123)
|
||||
|
||||
|
||||
def test_should_propagate_extra_http_headers_with_redirects(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_redirect("/a/redirect1", "/b/c/redirect2")
|
||||
server.set_redirect("/b/c/redirect2", "/simple.json")
|
||||
request = playwright.request.new_context(extra_http_headers={"My-Secret": "Value"})
|
||||
with server.expect_request("/a/redirect1") as server_req1:
|
||||
with server.expect_request("/b/c/redirect2") as server_req2:
|
||||
with server.expect_request("/simple.json") as server_req3:
|
||||
request.get(f"{server.PREFIX}/a/redirect1")
|
||||
assert server_req1.value.getHeader("my-secret") == "Value"
|
||||
assert server_req2.value.getHeader("my-secret") == "Value"
|
||||
assert server_req3.value.getHeader("my-secret") == "Value"
|
||||
|
||||
|
||||
def test_should_support_global_http_credentials_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request1 = playwright.request.new_context()
|
||||
response1 = request1.get(server.EMPTY_PAGE)
|
||||
assert response1.status == 401
|
||||
response1.dispose()
|
||||
|
||||
request2 = playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
response2 = request2.get(server.EMPTY_PAGE)
|
||||
assert response2.status == 200
|
||||
assert response2.ok is True
|
||||
response2.dispose()
|
||||
|
||||
|
||||
def test_should_return_error_with_wrong_credentials(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "wrong"}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
assert response.ok is False
|
||||
|
||||
|
||||
def test_should_work_with_correct_credentials_and_matching_origin(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX,
|
||||
}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_work_with_correct_credentials_and_matching_origin_case_insensitive(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_return_error_with_correct_credentials_and_mismatching_scheme(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.replace("http://", "https://"),
|
||||
}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_return_error_with_correct_credentials_and_mismatching_hostname(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
hostname = urlparse(server.PREFIX).hostname
|
||||
assert hostname
|
||||
origin = server.PREFIX.replace(hostname, "mismatching-hostname")
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_return_error_with_correct_credentials_and_mismatching_port(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
origin = server.PREFIX.replace(str(server.PORT), str(server.PORT + 1))
|
||||
request = playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_support_global_ignore_https_errors_option(
|
||||
playwright: Playwright, https_server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context(ignore_https_errors=True)
|
||||
response = request.get(https_server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
assert response.ok is True
|
||||
assert response.url == https_server.EMPTY_PAGE
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_resolve_url_relative_to_global_base_url_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context(base_url=server.PREFIX)
|
||||
response = request.get("/empty.html")
|
||||
assert response.status == 200
|
||||
assert response.ok is True
|
||||
assert response.url == server.EMPTY_PAGE
|
||||
response.dispose()
|
||||
|
||||
|
||||
def test_should_use_playwright_as_a_user_agent(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context()
|
||||
with server.expect_request("/empty.html") as server_req:
|
||||
request.get(server.EMPTY_PAGE)
|
||||
assert str(server_req.value.getHeader("User-Agent")).startswith("Playwright/")
|
||||
request.dispose()
|
||||
|
||||
|
||||
def test_should_return_empty_body(playwright: Playwright, server: Server) -> None:
|
||||
request = playwright.request.new_context()
|
||||
response = request.get(server.EMPTY_PAGE)
|
||||
body = response.body()
|
||||
assert len(body) == 0
|
||||
assert response.text() == ""
|
||||
request.dispose()
|
||||
with pytest.raises(Error, match="Response has been disposed"):
|
||||
response.body()
|
||||
|
||||
|
||||
def test_storage_state_should_round_trip_through_file(
|
||||
playwright: Playwright, tmp_path: Path
|
||||
) -> None:
|
||||
expected: StorageState = {
|
||||
"cookies": [
|
||||
{
|
||||
"name": "a",
|
||||
"value": "b",
|
||||
"domain": "a.b.one.com",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": "Lax",
|
||||
}
|
||||
],
|
||||
"origins": [],
|
||||
}
|
||||
request = playwright.request.new_context(storage_state=expected)
|
||||
path = tmp_path / "storage-state.json"
|
||||
actual = request.storage_state(path=path)
|
||||
assert actual == expected
|
||||
|
||||
written = path.read_text("utf8")
|
||||
assert json.loads(written) == expected
|
||||
|
||||
request2 = playwright.request.new_context(storage_state=path)
|
||||
state2 = request2.storage_state()
|
||||
assert state2 == expected
|
||||
|
||||
|
||||
def test_should_throw_an_error_when_max_redirects_is_exceeded(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_redirect("/a/redirect1", "/b/c/redirect2")
|
||||
server.set_redirect("/b/c/redirect2", "/b/c/redirect3")
|
||||
server.set_redirect("/b/c/redirect3", "/b/c/redirect4")
|
||||
server.set_redirect("/b/c/redirect4", "/simple.json")
|
||||
|
||||
request = playwright.request.new_context()
|
||||
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
|
||||
for max_redirects in [1, 2, 3]:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
request.fetch(
|
||||
server.PREFIX + "/a/redirect1",
|
||||
method=method,
|
||||
max_redirects=max_redirects,
|
||||
)
|
||||
assert "Max redirect count exceeded" in str(exc_info)
|
||||
|
||||
|
||||
def test_should_not_follow_redirects_when_max_redirects_is_set_to_0(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_redirect("/a/redirect1", "/b/c/redirect2")
|
||||
server.set_redirect("/b/c/redirect2", "/simple.json")
|
||||
|
||||
request = playwright.request.new_context()
|
||||
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
|
||||
response = request.fetch(
|
||||
server.PREFIX + "/a/redirect1", method=method, max_redirects=0
|
||||
)
|
||||
assert response.headers["location"] == "/b/c/redirect2"
|
||||
assert response.status == 302
|
||||
|
||||
|
||||
def test_should_throw_an_error_when_max_redirects_is_less_than_0(
|
||||
playwright: Playwright,
|
||||
server: Server,
|
||||
) -> None:
|
||||
request = playwright.request.new_context()
|
||||
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
|
||||
with pytest.raises(AssertionError) as exc_info:
|
||||
request.fetch(
|
||||
server.PREFIX + "/a/redirect1", method=method, max_redirects=-1
|
||||
)
|
||||
assert "'max_redirects' must be greater than or equal to '0'" in str(exc_info)
|
||||
|
||||
|
||||
def test_should_serialize_null_values_in_json(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = playwright.request.new_context()
|
||||
server.set_route("/echo", lambda req: (req.write(req.post_body), req.finish()))
|
||||
response = request.post(server.PREFIX + "/echo", data={"foo": None})
|
||||
assert response.status == 200
|
||||
assert response.text() == '{"foo": null}'
|
||||
request.dispose()
|
||||
|
||||
|
||||
def test_should_throw_when_fail_on_status_code_is_true(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/empty.html",
|
||||
lambda req: (
|
||||
req.setResponseCode(404),
|
||||
req.setHeader("Content-Length", "10"),
|
||||
req.setHeader("Content-Type", "text/plain"),
|
||||
req.write(b"Not found."),
|
||||
req.finish(),
|
||||
),
|
||||
)
|
||||
request = playwright.request.new_context(fail_on_status_code=True)
|
||||
with pytest.raises(Error, match="404 Not Found"):
|
||||
request.fetch(server.EMPTY_PAGE)
|
||||
request.dispose()
|
||||
|
||||
|
||||
def test_should_not_throw_when_fail_on_status_code_is_false(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/empty.html",
|
||||
lambda req: (
|
||||
req.setResponseCode(404),
|
||||
req.setHeader("Content-Length", "10"),
|
||||
req.setHeader("Content-Type", "text/plain"),
|
||||
req.write(b"Not found."),
|
||||
req.finish(),
|
||||
),
|
||||
)
|
||||
request = playwright.request.new_context(fail_on_status_code=False)
|
||||
response = request.fetch(server.EMPTY_PAGE)
|
||||
assert response.status == 404
|
||||
request.dispose()
|
||||
|
||||
|
||||
def test_should_follow_max_redirects(playwright: Playwright, server: Server) -> None:
|
||||
redirect_count = 0
|
||||
|
||||
def _handle_request(req: TestServerRequest) -> None:
|
||||
nonlocal redirect_count
|
||||
redirect_count += 1
|
||||
req.setResponseCode(301)
|
||||
req.setHeader("Location", server.EMPTY_PAGE)
|
||||
req.finish()
|
||||
|
||||
server.set_route("/empty.html", _handle_request)
|
||||
request = playwright.request.new_context(max_redirects=1)
|
||||
with pytest.raises(Error, match="Max redirect count exceeded"):
|
||||
request.fetch(server.EMPTY_PAGE)
|
||||
assert redirect_count == 2
|
||||
request.dispose()
|
||||
@@ -0,0 +1,28 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_fill_textarea(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
page.fill("textarea", "some value")
|
||||
assert page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
def test_fill_input(page: Page, server: Server) -> None:
|
||||
page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
page.fill("input", "some value")
|
||||
assert page.evaluate("result") == "some value"
|
||||
@@ -0,0 +1,636 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, BrowserContext, Error, Page, Route, expect
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_work(browser: Browser, server: Server, tmp_path: Path) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(record_har_path=path)
|
||||
page = context.new_page()
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
|
||||
|
||||
def test_should_omit_content(browser: Browser, server: Server, tmp_path: Path) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(record_har_path=path, record_har_content="omit")
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
|
||||
content1 = log["entries"][0]["response"]["content"]
|
||||
assert "text" not in content1
|
||||
assert "encoding" not in content1
|
||||
|
||||
|
||||
def test_should_omit_content_legacy(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(record_har_path=path, record_har_omit_content=True)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
|
||||
content1 = log["entries"][0]["response"]["content"]
|
||||
assert "text" not in content1
|
||||
assert "encoding" not in content1
|
||||
|
||||
|
||||
def test_should_attach_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har.zip")
|
||||
context = browser.new_context(
|
||||
record_har_path=path,
|
||||
record_har_content="attach",
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
page.evaluate("() => fetch('/pptr.png').then(r => r.arrayBuffer())")
|
||||
context.close()
|
||||
with zipfile.ZipFile(path) as z:
|
||||
with z.open("har.har") as har:
|
||||
entries = json.load(har)["log"]["entries"]
|
||||
|
||||
assert "encoding" not in entries[0]["response"]["content"]
|
||||
assert (
|
||||
entries[0]["response"]["content"]["mimeType"]
|
||||
== "text/html; charset=utf-8"
|
||||
)
|
||||
assert (
|
||||
"75841480e2606c03389077304342fac2c58ccb1b"
|
||||
in entries[0]["response"]["content"]["_file"]
|
||||
)
|
||||
assert entries[0]["response"]["content"]["size"] >= 96
|
||||
assert entries[0]["response"]["content"]["compression"] == 0
|
||||
|
||||
assert "encoding" not in entries[1]["response"]["content"]
|
||||
assert (
|
||||
entries[1]["response"]["content"]["mimeType"]
|
||||
== "text/css; charset=utf-8"
|
||||
)
|
||||
assert (
|
||||
"79f739d7bc88e80f55b9891a22bf13a2b4e18adb"
|
||||
in entries[1]["response"]["content"]["_file"]
|
||||
)
|
||||
assert entries[1]["response"]["content"]["size"] >= 37
|
||||
assert entries[1]["response"]["content"]["compression"] == 0
|
||||
|
||||
assert "encoding" not in entries[2]["response"]["content"]
|
||||
assert entries[2]["response"]["content"]["mimeType"] == "image/png"
|
||||
assert (
|
||||
"a4c3a18f0bb83f5d9fe7ce561e065c36205762fa"
|
||||
in entries[2]["response"]["content"]["_file"]
|
||||
)
|
||||
assert entries[2]["response"]["content"]["size"] >= 6000
|
||||
assert entries[2]["response"]["content"]["compression"] == 0
|
||||
|
||||
with z.open("75841480e2606c03389077304342fac2c58ccb1b.html") as f:
|
||||
assert b"HAR Page" in f.read()
|
||||
|
||||
with z.open("79f739d7bc88e80f55b9891a22bf13a2b4e18adb.css") as f:
|
||||
assert b"pink" in f.read()
|
||||
|
||||
with z.open("a4c3a18f0bb83f5d9fe7ce561e065c36205762fa.png") as f:
|
||||
assert len(f.read()) == entries[2]["response"]["content"]["size"]
|
||||
|
||||
|
||||
def test_should_include_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(record_har_path=path)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
|
||||
content1 = log["entries"][0]["response"]["content"]
|
||||
assert content1["mimeType"] == "text/html; charset=utf-8"
|
||||
assert "HAR Page" in content1["text"]
|
||||
|
||||
|
||||
def test_should_default_to_full_mode(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(
|
||||
record_har_path=path,
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
assert log["entries"][0]["request"]["bodySize"] >= 0
|
||||
|
||||
|
||||
def test_should_support_minimal_mode(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(
|
||||
record_har_path=path,
|
||||
record_har_mode="minimal",
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
assert log["entries"][0]["request"]["bodySize"] == -1
|
||||
|
||||
|
||||
def test_should_filter_by_glob(browser: Browser, server: Server, tmp_path: str) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(
|
||||
base_url=server.PREFIX,
|
||||
record_har_path=path,
|
||||
record_har_url_filter="/*.css",
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
assert len(log["entries"]) == 1
|
||||
assert log["entries"][0]["request"]["url"].endswith("one-style.css")
|
||||
|
||||
|
||||
def test_should_filter_by_regexp(
|
||||
browser: Browser, server: Server, tmp_path: str
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = browser.new_context(
|
||||
base_url=server.PREFIX,
|
||||
record_har_path=path,
|
||||
record_har_url_filter=re.compile("HAR.X?HTML", re.I),
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
log = data["log"]
|
||||
assert len(log["entries"]) == 1
|
||||
assert log["entries"][0]["request"]["url"].endswith("har.html")
|
||||
|
||||
|
||||
def test_should_context_route_from_har_matching_the_method_and_following_redirects(
|
||||
context: BrowserContext, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
page = context.new_page()
|
||||
page.goto("http://no.playwright/")
|
||||
# HAR contains a redirect for the script that should be followed automatically.
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
# HAR contains a POST for the css file that should not be used.
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
def test_should_page_route_from_har_matching_the_method_and_following_redirects(
|
||||
page: Page, assetdir: Path
|
||||
) -> None:
|
||||
page.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
page.goto("http://no.playwright/")
|
||||
# HAR contains a redirect for the script that should be followed automatically.
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
# HAR contains a POST for the css file that should not be used.
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
def test_fallback_continue_should_continue_when_not_found_in_har(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(har=assetdir / "har-fulfill.har", not_found="fallback")
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
|
||||
|
||||
def test_by_default_should_abort_requests_not_found_in_har(
|
||||
context: BrowserContext,
|
||||
server: Server,
|
||||
assetdir: Path,
|
||||
is_chromium: bool,
|
||||
is_webkit: bool,
|
||||
) -> None:
|
||||
context.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
page = context.new_page()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert exc_info.value
|
||||
if is_chromium:
|
||||
assert "net::ERR_FAILED" in exc_info.value.message
|
||||
elif is_webkit:
|
||||
assert "Blocked by Web Inspector" in exc_info.value.message
|
||||
else:
|
||||
assert "NS_ERROR_FAILURE" in exc_info.value.message
|
||||
|
||||
|
||||
def test_fallback_continue_should_continue_requests_on_bad_har(
|
||||
context: BrowserContext, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path_to_invalid_har = tmp_path / "invalid.har"
|
||||
with path_to_invalid_har.open("w") as f:
|
||||
json.dump({"log": {}}, f)
|
||||
context.route_from_har(har=path_to_invalid_har, not_found="fallback")
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
|
||||
|
||||
def test_should_only_handle_requests_matching_url_filter(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(
|
||||
har=assetdir / "har-fulfill.har", not_found="fallback", url="**/*.js"
|
||||
)
|
||||
page = context.new_page()
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
context.route("http://no.playwright/", handler)
|
||||
page.goto("http://no.playwright/")
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgba(0, 0, 0, 0)")
|
||||
|
||||
|
||||
def test_should_only_handle_requests_matching_url_filter_no_fallback(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(har=assetdir / "har-fulfill.har", url="**/*.js")
|
||||
page = context.new_page()
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
context.route("http://no.playwright/", handler)
|
||||
page.goto("http://no.playwright/")
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgba(0, 0, 0, 0)")
|
||||
|
||||
|
||||
def test_should_only_handle_requests_matching_url_filter_no_fallback_page(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
page.route_from_har(har=assetdir / "har-fulfill.har", url="**/*.js")
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
page.route("http://no.playwright/", handler)
|
||||
page.goto("http://no.playwright/")
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgba(0, 0, 0, 0)")
|
||||
|
||||
|
||||
def test_should_support_regex_filter(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(
|
||||
har=assetdir / "har-fulfill.har",
|
||||
url=re.compile(r".*(\.js|.*\.css|no.playwright\/)"),
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("http://no.playwright/")
|
||||
assert page.evaluate("window.value") == "foo"
|
||||
expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
def test_should_go_back_to_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://theverge.com/")
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
|
||||
response = page.go_back()
|
||||
assert response
|
||||
expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
@pytest.mark.skip_browser(
|
||||
"firefox"
|
||||
) # skipped upstream (https://github.com/microsoft/playwright/blob/6a8d835145e2f4002ee00b67a80a1f70af956703/tests/library/browsercontext-har.spec.ts#L214)
|
||||
def test_should_go_forward_to_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://theverge.com/")
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
page.goto("https://theverge.com/")
|
||||
expect(page).to_have_url("https://www.theverge.com/")
|
||||
page.go_back()
|
||||
expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
response = page.go_forward()
|
||||
assert response
|
||||
expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
def test_should_reload_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto("https://theverge.com/")
|
||||
expect(page).to_have_url("https://www.theverge.com/")
|
||||
response = page.reload()
|
||||
assert response
|
||||
expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
def test_should_fulfill_from_har_with_content_in_a_file(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
context.route_from_har(har=assetdir / "har-sha1.har")
|
||||
page = context.new_page()
|
||||
page.goto("http://no.playwright/")
|
||||
assert page.content() == "<html><head></head><body>Hello, world</body></html>"
|
||||
|
||||
|
||||
def test_should_round_trip_har_zip(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = browser.new_context(record_har_mode="minimal", record_har_path=har_path)
|
||||
page_1 = context_1.new_page()
|
||||
page_1.goto(server.PREFIX + "/one-style.html")
|
||||
context_1.close()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
context_2.route_from_har(har=har_path, not_found="abort")
|
||||
page_2 = context_2.new_page()
|
||||
page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page_2.content()
|
||||
expect(page_2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_round_trip_har_with_post_data(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/echo", lambda req: (req.write(cast(Any, req).post_body), req.finish())
|
||||
)
|
||||
fetch_function = """
|
||||
async (body) => {
|
||||
const response = await fetch('/echo', { method: 'POST', body });
|
||||
return response.text();
|
||||
};
|
||||
"""
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = browser.new_context(record_har_mode="minimal", record_har_path=har_path)
|
||||
page_1 = context_1.new_page()
|
||||
page_1.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert page_1.evaluate(fetch_function, "1") == "1"
|
||||
assert page_1.evaluate(fetch_function, "2") == "2"
|
||||
assert page_1.evaluate(fetch_function, "3") == "3"
|
||||
context_1.close()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
context_2.route_from_har(har=har_path, not_found="abort")
|
||||
page_2 = context_2.new_page()
|
||||
page_2.goto(server.EMPTY_PAGE)
|
||||
assert page_2.evaluate(fetch_function, "1") == "1"
|
||||
assert page_2.evaluate(fetch_function, "2") == "2"
|
||||
assert page_2.evaluate(fetch_function, "3") == "3"
|
||||
with pytest.raises(Exception):
|
||||
page_2.evaluate(fetch_function, "4")
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_disambiguate_by_header(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/echo",
|
||||
lambda req: (req.write(cast(str, req.getHeader("baz")).encode()), req.finish()),
|
||||
)
|
||||
fetch_function = """
|
||||
async (bazValue) => {
|
||||
const response = await fetch('/echo', {
|
||||
method: 'POST',
|
||||
body: '',
|
||||
headers: {
|
||||
foo: 'foo-value',
|
||||
bar: 'bar-value',
|
||||
baz: bazValue,
|
||||
}
|
||||
});
|
||||
return response.text();
|
||||
};
|
||||
"""
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = browser.new_context(record_har_mode="minimal", record_har_path=har_path)
|
||||
page_1 = context_1.new_page()
|
||||
page_1.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert page_1.evaluate(fetch_function, "baz1") == "baz1"
|
||||
assert page_1.evaluate(fetch_function, "baz2") == "baz2"
|
||||
assert page_1.evaluate(fetch_function, "baz3") == "baz3"
|
||||
context_1.close()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
context_2.route_from_har(har=har_path)
|
||||
page_2 = context_2.new_page()
|
||||
page_2.goto(server.EMPTY_PAGE)
|
||||
assert page_2.evaluate(fetch_function, "baz1") == "baz1"
|
||||
assert page_2.evaluate(fetch_function, "baz2") == "baz2"
|
||||
assert page_2.evaluate(fetch_function, "baz3") == "baz3"
|
||||
assert page_2.evaluate(fetch_function, "baz4") == "baz1"
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_produce_extracted_zip(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.har"
|
||||
context = browser.new_context(
|
||||
record_har_mode="minimal", record_har_path=har_path, record_har_content="attach"
|
||||
)
|
||||
page_1 = context.new_page()
|
||||
page_1.goto(server.PREFIX + "/one-style.html")
|
||||
context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
with har_path.open() as r:
|
||||
content = r.read()
|
||||
assert "log" in content
|
||||
assert "background-color" not in r.read()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
context_2.route_from_har(har_path, not_found="abort")
|
||||
page_2 = context_2.new_page()
|
||||
page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page_2.content()
|
||||
expect(page_2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_update_har_zip_for_context(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context = browser.new_context()
|
||||
context.route_from_har(har_path, update=True)
|
||||
page_1 = context.new_page()
|
||||
page_1.goto(server.PREFIX + "/one-style.html")
|
||||
context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
context_2.route_from_har(har_path, not_found="abort")
|
||||
page_2 = context_2.new_page()
|
||||
page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page_2.content()
|
||||
expect(page_2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_update_har_zip_for_page(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context = browser.new_context()
|
||||
page_1 = context.new_page()
|
||||
page_1.route_from_har(har_path, update=True)
|
||||
page_1.goto(server.PREFIX + "/one-style.html")
|
||||
context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
page_2 = context_2.new_page()
|
||||
page_2.route_from_har(har_path, not_found="abort")
|
||||
page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page_2.content()
|
||||
expect(page_2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context_2.close()
|
||||
|
||||
|
||||
def test_should_update_har_zip_for_page_with_different_options(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context1 = browser.new_context()
|
||||
page1 = context1.new_page()
|
||||
page1.route_from_har(
|
||||
har_path, update=True, update_content="embed", update_mode="full"
|
||||
)
|
||||
page1.goto(server.PREFIX + "/one-style.html")
|
||||
context1.close()
|
||||
|
||||
context2 = browser.new_context()
|
||||
page2 = context2.new_page()
|
||||
page2.route_from_har(har_path, not_found="abort")
|
||||
page2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page2.content()
|
||||
expect(page2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context2.close()
|
||||
|
||||
|
||||
def test_should_update_extracted_har_zip_for_page(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.har"
|
||||
context = browser.new_context()
|
||||
page_1 = context.new_page()
|
||||
page_1.route_from_har(har_path, update=True)
|
||||
page_1.goto(server.PREFIX + "/one-style.html")
|
||||
context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
with har_path.open() as r:
|
||||
content = r.read()
|
||||
assert "log" in content
|
||||
assert "background-color" not in r.read()
|
||||
|
||||
context_2 = browser.new_context()
|
||||
page_2 = context_2.new_page()
|
||||
page_2.route_from_har(har_path, not_found="abort")
|
||||
page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in page_2.content()
|
||||
expect(page_2.locator("body")).to_have_css("background-color", "rgb(255, 192, 203)")
|
||||
context_2.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
def test_expect_file_chooser(page: Page) -> None:
|
||||
page.set_content("<input type=file></input>")
|
||||
with page.expect_file_chooser() as fc_info:
|
||||
page.click('input[type="file"]')
|
||||
fc = fc_info.value
|
||||
fc.set_files(
|
||||
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"Hello World"}
|
||||
)
|
||||
|
||||
|
||||
def test_set_input_files_should_preserve_last_modified_timestamp(
|
||||
page: Page,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
page.set_content("<input type=file multiple=true/>")
|
||||
input = page.locator("input")
|
||||
files: Any = ["file-to-upload.txt", "file-to-upload-2.txt"]
|
||||
input.set_input_files([assetdir / file for file in files])
|
||||
assert input.evaluate("input => [...input.files].map(f => f.name)") == files
|
||||
timestamps = input.evaluate("input => [...input.files].map(f => f.lastModified)")
|
||||
expected_timestamps = [os.path.getmtime(assetdir / file) * 1000 for file in files]
|
||||
|
||||
# On Linux browser sometimes reduces the timestamp by 1ms: 1696272058110.0715 -> 1696272058109 or even
|
||||
# rounds it to seconds in WebKit: 1696272058110 -> 1696272058000.
|
||||
for i in range(len(timestamps)):
|
||||
assert abs(timestamps[i] - expected_timestamps[i]) < 1000
|
||||
@@ -0,0 +1,97 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserType, Error
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
def test_browser_type_launch_should_throw_if_page_argument_is_passed(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
browser_type.launch(**launch_arguments, args=["http://example.com"])
|
||||
assert "can not specify page" in exc.value.message
|
||||
|
||||
|
||||
def test_browser_type_launch_should_reject_if_launched_browser_fails_immediately(
|
||||
browser_type: BrowserType, launch_arguments: Dict, assetdir: Path
|
||||
) -> None:
|
||||
with pytest.raises(Error):
|
||||
browser_type.launch(
|
||||
**launch_arguments,
|
||||
executable_path=assetdir / "dummy_bad_browser_executable.js",
|
||||
)
|
||||
|
||||
|
||||
def test_browser_type_launch_should_reject_if_executable_path_is_invalid(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
browser_type.launch(**launch_arguments, executable_path="random-invalid-path")
|
||||
assert "executable doesn't exist" in exc.value.message
|
||||
|
||||
|
||||
def test_browser_type_executable_path_should_work(
|
||||
browser_type: BrowserType, browser_channel: str
|
||||
) -> None:
|
||||
if browser_channel:
|
||||
return
|
||||
executable_path = browser_type.executable_path
|
||||
assert os.path.exists(executable_path)
|
||||
assert os.path.realpath(executable_path) == os.path.realpath(executable_path)
|
||||
|
||||
|
||||
def test_browser_type_name_should_work(
|
||||
browser_type: BrowserType, is_webkit: bool, is_firefox: bool, is_chromium: bool
|
||||
) -> None:
|
||||
if is_webkit:
|
||||
assert browser_type.name == "webkit"
|
||||
elif is_firefox:
|
||||
assert browser_type.name == "firefox"
|
||||
elif is_chromium:
|
||||
assert browser_type.name == "chromium"
|
||||
else:
|
||||
raise ValueError("Unknown browser")
|
||||
|
||||
|
||||
def test_browser_close_should_fire_close_event_for_all_contexts(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = browser_type.launch(**launch_arguments)
|
||||
context = browser.new_context()
|
||||
closed = []
|
||||
context.on("close", lambda _: closed.append(True))
|
||||
browser.close()
|
||||
assert closed == [True]
|
||||
|
||||
|
||||
def test_browser_close_should_be_callable_twice(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = browser_type.launch(**launch_arguments)
|
||||
browser.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
def test_browser_type_launch_should_accept_ignore_default_args_false(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = browser_type.launch(**launch_arguments, ignore_default_args=False)
|
||||
browser.close()
|
||||
@@ -0,0 +1,33 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from playwright.sync_api import Page, Response
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_listeners(page: Page, server: Server) -> None:
|
||||
log = []
|
||||
|
||||
def print_response(response: Response) -> None:
|
||||
log.append(response)
|
||||
|
||||
page.on("response", print_response)
|
||||
page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
assert len(log) > 0
|
||||
page.remove_listener("response", print_response)
|
||||
|
||||
log = []
|
||||
page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
assert len(log) == 0
|
||||
@@ -0,0 +1,213 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import re
|
||||
|
||||
from playwright.sync_api import Page, expect
|
||||
|
||||
|
||||
def test_get_by_test_id(page: Page) -> None:
|
||||
page.set_content("<div><div data-testid='Hello'>Hello world</div></div>")
|
||||
expect(page.get_by_test_id("Hello")).to_have_text("Hello world")
|
||||
expect(page.main_frame.get_by_test_id("Hello")).to_have_text("Hello world")
|
||||
expect(page.locator("div").get_by_test_id("Hello")).to_have_text("Hello world")
|
||||
|
||||
|
||||
def test_get_by_test_id_escape_id(page: Page) -> None:
|
||||
page.set_content("<div><div data-testid='He\"llo'>Hello world</div></div>")
|
||||
expect(page.get_by_test_id('He"llo')).to_have_text("Hello world")
|
||||
|
||||
|
||||
def test_get_by_text(page: Page) -> None:
|
||||
page.set_content("<div><div>yo</div><div>ya</div><div>\nye </div></div>")
|
||||
|
||||
expect(page.get_by_text("yo")).to_have_count(1)
|
||||
expect(page.main_frame.get_by_text("yo")).to_have_count(1)
|
||||
expect(page.locator("div").get_by_text("yo")).to_have_count(1)
|
||||
|
||||
assert ">\nye </div>" in page.get_by_text("ye").evaluate("e => e.outerHTML")
|
||||
assert ">\nye </div>" in page.get_by_text(r"ye").evaluate("e => e.outerHTML")
|
||||
|
||||
page.set_content("<div> ye </div><div>ye</div>")
|
||||
assert "> ye </div>" in page.get_by_text("ye", exact=True).first.evaluate(
|
||||
"e => e.outerHTML"
|
||||
)
|
||||
|
||||
page.set_content("<div>Hello world</div><div>Hello</div>")
|
||||
assert (
|
||||
page.get_by_text("Hello", exact=True).evaluate("e => e.outerHTML")
|
||||
== "<div>Hello</div>"
|
||||
)
|
||||
|
||||
|
||||
def test_get_by_label(page: Page) -> None:
|
||||
page.set_content(
|
||||
"<div><label for=target>Name</label><input id=target type=text></div>"
|
||||
)
|
||||
|
||||
expect(page.get_by_label("Name")).to_have_count(1)
|
||||
expect(page.main_frame.get_by_label("Name")).to_have_count(1)
|
||||
expect(page.locator("div").get_by_label("Name")).to_have_count(1)
|
||||
|
||||
assert page.get_by_text("Name").evaluate("e => e.nodeName") == "LABEL"
|
||||
assert page.get_by_label("Name").evaluate("e => e.nodeName") == "INPUT"
|
||||
assert page.main_frame.get_by_label("Name").evaluate("e => e.nodeName") == "INPUT"
|
||||
assert (
|
||||
page.locator("div").get_by_label("Name").evaluate("e => e.nodeName") == "INPUT"
|
||||
)
|
||||
|
||||
|
||||
def test_get_by_label_with_nested_elements(page: Page) -> None:
|
||||
page.set_content(
|
||||
"<label for=target>Last <span>Name</span></label><input id=target type=text>"
|
||||
)
|
||||
|
||||
expect(page.get_by_label("last name")).to_have_attribute("id", "target")
|
||||
expect(page.get_by_label("st na")).to_have_attribute("id", "target")
|
||||
expect(page.get_by_label("Name")).to_have_attribute("id", "target")
|
||||
expect(page.get_by_label("Last Name", exact=True)).to_have_attribute("id", "target")
|
||||
expect(
|
||||
page.get_by_label(re.compile(r"Last\s+name", re.IGNORECASE))
|
||||
).to_have_attribute("id", "target")
|
||||
|
||||
expect(page.get_by_label("Last", exact=True)).to_have_count(0)
|
||||
expect(page.get_by_label("last name", exact=True)).to_have_count(0)
|
||||
expect(page.get_by_label("Name", exact=True)).to_have_count(0)
|
||||
expect(page.get_by_label("what?")).to_have_count(0)
|
||||
expect(page.get_by_label(re.compile(r"last name"))).to_have_count(0)
|
||||
|
||||
|
||||
def test_get_by_placeholder(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<div>
|
||||
<input placeholder="Hello">
|
||||
<input placeholder="Hello World">
|
||||
</div>"""
|
||||
)
|
||||
|
||||
expect(page.get_by_placeholder("hello")).to_have_count(2)
|
||||
expect(page.main_frame.get_by_placeholder("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_placeholder("hello")).to_have_count(2)
|
||||
|
||||
expect(page.get_by_placeholder("hello")).to_have_count(2)
|
||||
expect(page.get_by_placeholder("Hello", exact=True)).to_have_count(1)
|
||||
expect(page.get_by_placeholder(re.compile(r"wor", re.IGNORECASE))).to_have_count(1)
|
||||
|
||||
# Coverage
|
||||
expect(page.main_frame.get_by_placeholder("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_placeholder("hello")).to_have_count(2)
|
||||
|
||||
|
||||
def test_get_by_alt_text(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<div>
|
||||
<input alt="Hello">
|
||||
<input alt="Hello World">
|
||||
</div>"""
|
||||
)
|
||||
|
||||
expect(page.get_by_alt_text("hello")).to_have_count(2)
|
||||
expect(page.main_frame.get_by_alt_text("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_alt_text("hello")).to_have_count(2)
|
||||
|
||||
expect(page.get_by_alt_text("hello")).to_have_count(2)
|
||||
expect(page.get_by_alt_text("Hello", exact=True)).to_have_count(1)
|
||||
expect(page.get_by_alt_text(re.compile(r"wor", re.IGNORECASE))).to_have_count(1)
|
||||
|
||||
# Coverage
|
||||
expect(page.main_frame.get_by_alt_text("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_alt_text("hello")).to_have_count(2)
|
||||
|
||||
|
||||
def test_get_by_title(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<div>
|
||||
<input title="Hello">
|
||||
<input title="Hello World">
|
||||
</div>"""
|
||||
)
|
||||
|
||||
expect(page.get_by_title("hello")).to_have_count(2)
|
||||
expect(page.main_frame.get_by_title("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_title("hello")).to_have_count(2)
|
||||
|
||||
expect(page.get_by_title("hello")).to_have_count(2)
|
||||
expect(page.get_by_title("Hello", exact=True)).to_have_count(1)
|
||||
expect(page.get_by_title(re.compile(r"wor", re.IGNORECASE))).to_have_count(1)
|
||||
|
||||
# Coverage
|
||||
expect(page.main_frame.get_by_title("hello")).to_have_count(2)
|
||||
expect(page.locator("div").get_by_title("hello")).to_have_count(2)
|
||||
|
||||
|
||||
def test_get_by_escaping(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""<label id=label for=control>Hello my
|
||||
wo"rld</label><input id=control />"""
|
||||
)
|
||||
page.locator("input").evaluate(
|
||||
"""input => {
|
||||
input.setAttribute('placeholder', 'hello my\\nwo"rld');
|
||||
input.setAttribute('title', 'hello my\\nwo"rld');
|
||||
input.setAttribute('alt', 'hello my\\nwo"rld');
|
||||
}"""
|
||||
)
|
||||
expect(page.get_by_text('hello my\nwo"rld')).to_have_attribute("id", "label")
|
||||
expect(page.get_by_text('hello my wo"rld')).to_have_attribute(
|
||||
"id", "label"
|
||||
)
|
||||
expect(page.get_by_label('hello my\nwo"rld')).to_have_attribute("id", "control")
|
||||
expect(page.get_by_placeholder('hello my\nwo"rld')).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
expect(page.get_by_alt_text('hello my\nwo"rld')).to_have_attribute("id", "control")
|
||||
expect(page.get_by_title('hello my\nwo"rld')).to_have_attribute("id", "control")
|
||||
|
||||
page.set_content(
|
||||
"""<label id=label for=control>Hello my
|
||||
world</label><input id=control />"""
|
||||
)
|
||||
page.locator("input").evaluate(
|
||||
"""input => {
|
||||
input.setAttribute('placeholder', 'hello my\\nworld');
|
||||
input.setAttribute('title', 'hello my\\nworld');
|
||||
input.setAttribute('alt', 'hello my\\nworld');
|
||||
}"""
|
||||
)
|
||||
expect(page.get_by_text("hello my\nworld")).to_have_attribute("id", "label")
|
||||
expect(page.get_by_text("hello my world")).to_have_attribute(
|
||||
"id", "label"
|
||||
)
|
||||
expect(page.get_by_label("hello my\nworld")).to_have_attribute("id", "control")
|
||||
expect(page.get_by_placeholder("hello my\nworld")).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
expect(page.get_by_alt_text("hello my\nworld")).to_have_attribute("id", "control")
|
||||
expect(page.get_by_title("hello my\nworld")).to_have_attribute("id", "control")
|
||||
|
||||
|
||||
def test_get_by_role(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<button>Hello</button>
|
||||
<button>Hel"lo</button>
|
||||
<div role="dialog">I am a dialog</div>
|
||||
"""
|
||||
)
|
||||
expect(page.get_by_role("button", name="hello")).to_have_count(1)
|
||||
expect(page.get_by_role("button", name='Hel"lo')).to_have_count(1)
|
||||
expect(
|
||||
page.get_by_role("button", name=re.compile(r"he", re.IGNORECASE))
|
||||
).to_have_count(2)
|
||||
expect(page.get_by_role("dialog")).to_have_count(1)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,116 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, Page, Playwright, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_response_server_addr(page: Page, server: Server) -> None:
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
server_addr = response.server_addr()
|
||||
assert server_addr
|
||||
assert server_addr["port"] == server.PORT
|
||||
assert server_addr["ipAddress"] in ["127.0.0.1", "[::1]"]
|
||||
|
||||
|
||||
def test_response_security_details(
|
||||
browser: Browser,
|
||||
https_server: Server,
|
||||
browser_name: str,
|
||||
is_win: bool,
|
||||
is_linux: bool,
|
||||
) -> None:
|
||||
if (browser_name == "webkit" and is_linux) or (browser_name == "webkit" and is_win):
|
||||
pytest.skip("https://github.com/microsoft/playwright/issues/6759")
|
||||
page = browser.new_page(ignore_https_errors=True)
|
||||
response = page.goto(https_server.EMPTY_PAGE)
|
||||
assert response
|
||||
response.finished()
|
||||
security_details = response.security_details()
|
||||
assert security_details
|
||||
if browser_name == "webkit" and is_win:
|
||||
assert security_details == {
|
||||
"subjectName": "puppeteer-tests",
|
||||
"validFrom": 1550084863,
|
||||
"validTo": -1,
|
||||
}
|
||||
elif browser_name == "webkit":
|
||||
assert security_details == {
|
||||
"protocol": "TLS 1.3",
|
||||
"subjectName": "puppeteer-tests",
|
||||
"validFrom": 1550084863,
|
||||
"validTo": 33086084863,
|
||||
}
|
||||
else:
|
||||
assert security_details == {
|
||||
"issuer": "puppeteer-tests",
|
||||
"protocol": "TLS 1.3",
|
||||
"subjectName": "puppeteer-tests",
|
||||
"validFrom": 1550084863,
|
||||
"validTo": 33086084863,
|
||||
}
|
||||
page.close()
|
||||
|
||||
|
||||
def test_response_security_details_none_without_https(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
security_details = response.security_details()
|
||||
assert security_details is None
|
||||
|
||||
|
||||
def test_should_fulfill_with_global_fetch_result(
|
||||
page: Page, playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
def handle_request(route: Route) -> None:
|
||||
request = playwright.request.new_context()
|
||||
response = request.get(server.PREFIX + "/simple.json")
|
||||
route.fulfill(response=response)
|
||||
request.dispose()
|
||||
|
||||
page.route("**/*", handle_request)
|
||||
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert response.json() == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_should_report_if_response_was_from_service_worker(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = page.goto(server.PREFIX + "/serviceworkers/fetch/sw.html")
|
||||
assert response
|
||||
assert not response.from_service_worker
|
||||
page.evaluate("() => window.activationPromise")
|
||||
with page.expect_response("**/example.txt") as response_info:
|
||||
page.evaluate("() => fetch('/example.txt')")
|
||||
assert response_info.value.from_service_worker
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_report_service_worker_request(page: Page, server: Server) -> None:
|
||||
with page.context.expect_event("serviceworker") as worker_info:
|
||||
page.goto(server.PREFIX + "/serviceworkers/fetch/sw.html")
|
||||
page.evaluate("() => window.activationPromise")
|
||||
with page.context.expect_event(
|
||||
"request", lambda r: r.service_worker is not None
|
||||
) as request_info:
|
||||
page.evaluate("() => fetch('/example.txt')")
|
||||
assert request_info.value.service_worker == worker_info.value
|
||||
@@ -0,0 +1,124 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_input_value(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/textarea.html")
|
||||
|
||||
page.fill("input", "my-text-content")
|
||||
assert page.input_value("input") == "my-text-content"
|
||||
|
||||
page.fill("input", "")
|
||||
assert page.input_value("input") == ""
|
||||
|
||||
|
||||
def test_drag_and_drop_helper_method(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/drag-n-drop.html")
|
||||
page.drag_and_drop("#source", "#target")
|
||||
assert (
|
||||
page.eval_on_selector(
|
||||
"#target", "target => target.contains(document.querySelector('#source'))"
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
|
||||
def test_should_check_box_using_set_checked(page: Page) -> None:
|
||||
page.set_content("`<input id='checkbox' type='checkbox'></input>`")
|
||||
page.set_checked("input", True)
|
||||
assert page.evaluate("checkbox.checked") is True
|
||||
page.set_checked("input", False)
|
||||
assert page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
def test_should_set_bodysize_and_headersize(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with page.expect_request("*/**") as request_info:
|
||||
page.evaluate(
|
||||
"() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())"
|
||||
)
|
||||
request = request_info.value
|
||||
sizes = request.sizes()
|
||||
assert sizes["requestBodySize"] == 5
|
||||
assert sizes["requestHeadersSize"] >= 300
|
||||
|
||||
|
||||
def test_should_set_bodysize_to_0(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with page.expect_request("*/**") as request_info:
|
||||
page.evaluate("() => fetch('./get').then(r => r.text())")
|
||||
|
||||
request = request_info.value
|
||||
sizes = request.sizes()
|
||||
assert sizes["requestBodySize"] == 0
|
||||
assert sizes["requestHeadersSize"] >= 200
|
||||
|
||||
|
||||
def test_sync_stacks_should_work(page: Page, server: Server) -> None:
|
||||
page.route("**/empty.html", lambda route: route.abort())
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert exc_info.value.stack
|
||||
assert __file__ in exc_info.value.stack
|
||||
|
||||
|
||||
def test_emitted_for_domcontentloaded_and_load(page: Page, server: Server) -> None:
|
||||
with page.expect_event("domcontentloaded") as dom_info:
|
||||
with page.expect_event("load") as load_info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert isinstance(dom_info.value, Page)
|
||||
assert isinstance(load_info.value, Page)
|
||||
|
||||
|
||||
def test_page_pause_should_reset_default_timeouts(
|
||||
page: Page, headless: bool, server: Server
|
||||
) -> None:
|
||||
if not headless:
|
||||
pytest.skip()
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.pause()
|
||||
with pytest.raises(Error, match="Timeout 30000ms exceeded."):
|
||||
page.get_by_text("foo").click()
|
||||
|
||||
|
||||
def test_page_pause_should_reset_custom_timeouts(
|
||||
page: Page, headless: bool, server: Server
|
||||
) -> None:
|
||||
if not headless:
|
||||
pytest.skip()
|
||||
|
||||
page.set_default_timeout(123)
|
||||
page.set_default_navigation_timeout(456)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.pause()
|
||||
with pytest.raises(Error, match="Timeout 123ms exceeded."):
|
||||
page.get_by_text("foo").click()
|
||||
|
||||
server.set_route("/empty.html", lambda route: None)
|
||||
with pytest.raises(Error, match="Timeout 456ms exceeded."):
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_page_should_ignore_deprecated_is_hidden_and_visible_timeout(
|
||||
page: Page,
|
||||
) -> None:
|
||||
page.set_content("<div>foo</div>")
|
||||
assert page.is_hidden("div", timeout=10) is False
|
||||
assert page.is_visible("div", timeout=10) is True
|
||||
@@ -0,0 +1,386 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Locator, Page, expect
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
def test_should_work(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
before_count = 0
|
||||
after_count = 0
|
||||
|
||||
original_locator = page.get_by_text("This interstitial covers the button")
|
||||
|
||||
def handler(locator: Locator) -> None:
|
||||
assert locator == original_locator
|
||||
nonlocal before_count
|
||||
nonlocal after_count
|
||||
before_count += 1
|
||||
page.locator("#close").click()
|
||||
after_count += 1
|
||||
|
||||
page.add_locator_handler(original_locator, handler)
|
||||
|
||||
for args in [
|
||||
["mouseover", 1],
|
||||
["mouseover", 1, "capture"],
|
||||
["mouseover", 2],
|
||||
["mouseover", 2, "capture"],
|
||||
["pointerover", 1],
|
||||
["pointerover", 1, "capture"],
|
||||
["none", 1],
|
||||
["remove", 1],
|
||||
["hide", 1],
|
||||
]:
|
||||
page.locator("#aside").hover()
|
||||
before_count = 0
|
||||
after_count = 0
|
||||
page.evaluate(
|
||||
"(args) => { window.clicked = 0; window.setupAnnoyingInterstitial(...args); }",
|
||||
args,
|
||||
)
|
||||
assert before_count == 0
|
||||
assert after_count == 0
|
||||
page.locator("#target").click()
|
||||
assert before_count == args[1]
|
||||
assert after_count == args[1]
|
||||
assert page.evaluate("window.clicked") == 1
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
|
||||
|
||||
def test_should_work_with_a_custom_check(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
def handler() -> None:
|
||||
if page.get_by_text("This interstitial covers the button").is_visible():
|
||||
page.locator("#close").click()
|
||||
|
||||
page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
|
||||
|
||||
for args in [
|
||||
["mouseover", 2],
|
||||
["none", 1],
|
||||
["remove", 1],
|
||||
["hide", 1],
|
||||
]:
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
"(args) => { window.clicked = 0; window.setupAnnoyingInterstitial(...args); }",
|
||||
args,
|
||||
)
|
||||
page.locator("#target").click()
|
||||
assert page.evaluate("window.clicked") == 1
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
|
||||
|
||||
def test_should_work_with_locator_hover(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
'() => { window.setupAnnoyingInterstitial("pointerover", 1, "capture"); }'
|
||||
)
|
||||
page.locator("#target").hover()
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert (
|
||||
page.eval_on_selector(
|
||||
"#target", "e => window.getComputedStyle(e).backgroundColor"
|
||||
)
|
||||
== "rgb(255, 255, 0)"
|
||||
)
|
||||
|
||||
|
||||
def test_should_not_work_with_force_true(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate('() => { window.setupAnnoyingInterstitial("none", 1); }')
|
||||
page.locator("#target").click(force=True, timeout=2000)
|
||||
assert page.locator("#interstitial").is_visible()
|
||||
assert page.evaluate("window.clicked") is None
|
||||
|
||||
|
||||
def test_should_throw_when_page_closes(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), lambda: page.close()
|
||||
)
|
||||
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("mouseover", 1); }'
|
||||
)
|
||||
with pytest.raises(Error) as exc:
|
||||
page.locator("#target").click()
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc.value.message
|
||||
|
||||
|
||||
def test_should_throw_when_handler_times_out(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
called = 0
|
||||
|
||||
def handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
# Deliberately timeout.
|
||||
try:
|
||||
page.wait_for_timeout(9999999)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), handler
|
||||
)
|
||||
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("mouseover", 1); }'
|
||||
)
|
||||
with pytest.raises(Error) as exc:
|
||||
page.locator("#target").click(timeout=3000)
|
||||
assert "Timeout 3000ms exceeded" in exc.value.message
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
page.locator("#target").click(timeout=3000)
|
||||
assert "Timeout 3000ms exceeded" in exc.value.message
|
||||
|
||||
# Should not enter the same handler while it is still running.
|
||||
assert called == 1
|
||||
|
||||
|
||||
def test_should_work_with_to_be_visible(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
called = 0
|
||||
|
||||
def handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
page.locator("#close").click()
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), handler
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("remove", 1); }'
|
||||
)
|
||||
expect(page.locator("#target")).to_be_visible()
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 1
|
||||
|
||||
|
||||
def test_should_work_when_owner_frame_detaches(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = 'data:text/html,<body>hello from iframe</body>';
|
||||
document.body.append(iframe);
|
||||
|
||||
const target = document.createElement('button');
|
||||
target.textContent = 'Click me';
|
||||
target.id = 'target';
|
||||
target.addEventListener('click', () => window._clicked = true);
|
||||
document.body.appendChild(target);
|
||||
|
||||
const closeButton = document.createElement('button');
|
||||
closeButton.textContent = 'close';
|
||||
closeButton.id = 'close';
|
||||
closeButton.addEventListener('click', () => iframe.remove());
|
||||
document.body.appendChild(closeButton);
|
||||
}
|
||||
"""
|
||||
)
|
||||
page.add_locator_handler(
|
||||
page.frame_locator("iframe").locator("body"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
page.locator("#target").click()
|
||||
assert page.query_selector("iframe") is None
|
||||
assert page.evaluate("window._clicked") is True
|
||||
|
||||
|
||||
def test_should_work_with_times_option(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
|
||||
page.add_locator_handler(
|
||||
page.locator("body"), _handler, no_wait_after=True, times=2
|
||||
)
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('mouseover', 4);
|
||||
}
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.locator("#target").click(timeout=3000)
|
||||
assert called == 2
|
||||
assert page.evaluate("window.clicked") == 0
|
||||
expect(page.locator("#interstitial")).to_be_visible()
|
||||
assert "Timeout 3000ms exceeded" in exc_info.value.message
|
||||
assert (
|
||||
'<div>This interstitial covers the button</div> from <div class="visible" id="interstitial">…</div> subtree intercepts pointer events'
|
||||
in exc_info.value.message
|
||||
)
|
||||
|
||||
|
||||
def test_should_wait_for_hidden_by_default(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler(button: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
button.click()
|
||||
|
||||
page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('timeout', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
page.locator("#target").click()
|
||||
assert page.evaluate("window.clicked") == 1
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 1
|
||||
|
||||
|
||||
def test_should_wait_for_hidden_by_default_2(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
|
||||
page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.locator("#target").click(timeout=3000)
|
||||
assert page.evaluate("window.clicked") == 0
|
||||
assert page.locator("#interstitial").is_visible()
|
||||
assert called == 1
|
||||
assert (
|
||||
'locator handler has finished, waiting for get_by_role("button", name="close") to be hidden'
|
||||
in exc_info.value.message
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_noWaitAfter(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler(button: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
if called == 1:
|
||||
button.click()
|
||||
else:
|
||||
page.locator("#interstitial").wait_for(state="hidden")
|
||||
|
||||
page.add_locator_handler(
|
||||
page.get_by_role("button", name="close"), _handler, no_wait_after=True
|
||||
)
|
||||
page.locator("#aside").hover()
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('timeout', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
page.locator("#target").click()
|
||||
assert page.evaluate("window.clicked") == 1
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 2
|
||||
|
||||
|
||||
def test_should_removeLocatorHandler(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler(locator: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
locator.click()
|
||||
|
||||
page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
page.locator("#target").click()
|
||||
assert called == 1
|
||||
assert page.evaluate("window.clicked") == 1
|
||||
expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
page.remove_locator_handler(page.get_by_role("button", name="close"))
|
||||
with pytest.raises(Error) as error:
|
||||
page.locator("#target").click(timeout=3000)
|
||||
assert called == 1
|
||||
assert page.evaluate("window.clicked") == 0
|
||||
expect(page.locator("#interstitial")).to_be_visible()
|
||||
assert "Timeout 3000ms exceeded" in error.value.message
|
||||
@@ -0,0 +1,274 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Locator, Page, expect
|
||||
|
||||
|
||||
def _unshift(snapshot: str) -> str:
|
||||
lines = snapshot.split("\n")
|
||||
whitespace_prefix_length = 100
|
||||
for line in lines:
|
||||
if not line.strip():
|
||||
continue
|
||||
match = re.match(r"^(\s*)", line)
|
||||
if match and len(match[1]) < whitespace_prefix_length:
|
||||
whitespace_prefix_length = len(match[1])
|
||||
return "\n".join(
|
||||
[line[whitespace_prefix_length:] for line in lines if line.strip()]
|
||||
)
|
||||
|
||||
|
||||
def check_and_match_snapshot(locator: Locator, snapshot: str) -> None:
|
||||
assert locator.aria_snapshot() == _unshift(snapshot)
|
||||
expect(locator).to_match_aria_snapshot(snapshot)
|
||||
|
||||
|
||||
def test_should_snapshot(page: Page) -> None:
|
||||
page.set_content("<h1>title</h1>")
|
||||
check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_list(page: Page) -> None:
|
||||
page.set_content("<h1>title</h1><h1>title 2</h1>")
|
||||
check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
- heading "title 2" [level=1]
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_list_with_list(page: Page) -> None:
|
||||
page.set_content("<ul><li>one</li><li>two</li></ul>")
|
||||
check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list:
|
||||
- listitem: one
|
||||
- listitem: two
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_list_with_accessible_name(page: Page) -> None:
|
||||
page.set_content('<ul aria-label="my list"><li>one</li><li>two</li></ul>')
|
||||
check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list "my list":
|
||||
- listitem: one
|
||||
- listitem: two
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_complex(page: Page) -> None:
|
||||
page.set_content('<ul><li><a href="about:blank">link</a></li></ul>')
|
||||
check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list:
|
||||
- listitem:
|
||||
- link "link":
|
||||
- /url: about:blank
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_with_unexpected_children_equal(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>One</li>
|
||||
<li>Two</li>
|
||||
<li>Three</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- listitem: One
|
||||
- listitem: Three
|
||||
""",
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: equal
|
||||
- listitem: One
|
||||
- listitem: Three
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_with_unexpected_children_deep_equal(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>
|
||||
<ul>
|
||||
<li>1.1</li>
|
||||
<li>1.2</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_with_restored_contain_mode_inside_deep_equal(
|
||||
page: Page,
|
||||
) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>
|
||||
<ul>
|
||||
<li>1.1</li>
|
||||
<li>1.2</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- /children: contain
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_match_values_both_against_regex_and_string(page: Page) -> None:
|
||||
page.set_content('<a href="/auth?r=/">Log in</a>')
|
||||
expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- link "Log in":
|
||||
- /url: /auth?r=/
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def test_should_snapshot_with_depth(page: Page) -> None:
|
||||
page.set_content("<ul><li><a href=about:blank>link</a></li></ul>")
|
||||
snapshot = page.locator("body").aria_snapshot(depth=1)
|
||||
assert "listitem" in snapshot
|
||||
assert "/url" not in snapshot
|
||||
|
||||
|
||||
def test_page_aria_snapshot_should_work(page: Page) -> None:
|
||||
page.set_content("<h1>title</h1>")
|
||||
snapshot = page.aria_snapshot()
|
||||
assert _unshift(snapshot) == _unshift(
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def test_to_match_aria_snapshot_should_match_page(page: Page) -> None:
|
||||
page.set_content("<h1>title</h1>")
|
||||
expect(page).to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "title"
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def test_to_match_aria_snapshot_should_match_page_complex(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<h1>Microsoft</h1>
|
||||
<div>Open source projects and samples from Microsoft</div>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="about:blank">Playwright</a>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
expect(page).to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "Microsoft"
|
||||
- text: Open source projects and samples from Microsoft
|
||||
- list:
|
||||
- listitem:
|
||||
- link "Playwright"
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def test_to_match_aria_snapshot_should_match_page_with_not(page: Page) -> None:
|
||||
page.set_content("<h1>title</h1>")
|
||||
expect(page).not_to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "wrong"
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,470 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import datetime
|
||||
from typing import Any, Generator, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def calls(page: Page) -> List[Any]:
|
||||
calls: List[Any] = []
|
||||
page.expose_function("stub", lambda *args: calls.append(list(args)))
|
||||
return calls
|
||||
|
||||
|
||||
class TestRunFor:
|
||||
@pytest.fixture(autouse=True)
|
||||
def before_each(self, page: Page) -> Generator[None, None, None]:
|
||||
page.clock.install(time=0)
|
||||
page.clock.pause_at(1000)
|
||||
yield
|
||||
|
||||
def test_run_for_triggers_immediately_without_specified_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(window.stub)")
|
||||
page.clock.run_for(0)
|
||||
assert len(calls) == 1
|
||||
|
||||
def test_run_for_does_not_trigger_without_sufficient_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(window.stub, 100)")
|
||||
page.clock.run_for(10)
|
||||
assert len(calls) == 0
|
||||
|
||||
def test_run_for_triggers_after_sufficient_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(window.stub, 100)")
|
||||
page.clock.run_for(100)
|
||||
assert len(calls) == 1
|
||||
|
||||
def test_run_for_triggers_simultaneous_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(window.stub, 100); setTimeout(window.stub, 100)")
|
||||
page.clock.run_for(100)
|
||||
assert len(calls) == 2
|
||||
|
||||
def test_run_for_triggers_multiple_simultaneous_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate(
|
||||
"setTimeout(window.stub, 100); setTimeout(window.stub, 100); setTimeout(window.stub, 99); setTimeout(window.stub, 100)"
|
||||
)
|
||||
page.clock.run_for(100)
|
||||
assert len(calls) == 4
|
||||
|
||||
def test_run_for_waits_after_setTimeout_was_called(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(window.stub, 150)")
|
||||
page.clock.run_for(50)
|
||||
assert len(calls) == 0
|
||||
page.clock.run_for(100)
|
||||
assert len(calls) == 1
|
||||
|
||||
def test_run_for_triggers_event_when_some_throw(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate(
|
||||
"setTimeout(() => { throw new Error(); }, 100); setTimeout(window.stub, 120)"
|
||||
)
|
||||
with pytest.raises(Error):
|
||||
page.clock.run_for(120)
|
||||
assert len(calls) == 1
|
||||
|
||||
def test_run_for_creates_updated_Date_while_ticking(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.clock.set_system_time(0)
|
||||
page.evaluate("setInterval(() => { window.stub(new Date().getTime()); }, 10)")
|
||||
page.clock.run_for(100)
|
||||
assert calls == [
|
||||
[10],
|
||||
[20],
|
||||
[30],
|
||||
[40],
|
||||
[50],
|
||||
[60],
|
||||
[70],
|
||||
[80],
|
||||
[90],
|
||||
[100],
|
||||
]
|
||||
|
||||
def test_run_for_passes_8_seconds(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate("setInterval(window.stub, 4000)")
|
||||
page.clock.run_for("08")
|
||||
assert len(calls) == 2
|
||||
|
||||
def test_run_for_passes_1_minute(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate("setInterval(window.stub, 6000)")
|
||||
page.clock.run_for("01:00")
|
||||
assert len(calls) == 10
|
||||
|
||||
def test_run_for_passes_2_hours_34_minutes_and_10_seconds(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setInterval(window.stub, 10000)")
|
||||
page.clock.run_for("02:34:10")
|
||||
assert len(calls) == 925
|
||||
|
||||
def test_run_for_throws_for_invalid_format(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setInterval(window.stub, 10000)")
|
||||
with pytest.raises(Error):
|
||||
page.clock.run_for("12:02:34:10")
|
||||
assert len(calls) == 0
|
||||
|
||||
def test_run_for_returns_the_current_now_value(self, page: Page) -> None:
|
||||
page.clock.set_system_time(0)
|
||||
value = 200
|
||||
page.clock.run_for(value)
|
||||
assert page.evaluate("Date.now()") == value
|
||||
|
||||
|
||||
class TestFastForward:
|
||||
@pytest.fixture(autouse=True)
|
||||
def before_each(self, page: Page) -> Generator[None, None, None]:
|
||||
page.clock.install(time=0)
|
||||
page.clock.pause_at(1)
|
||||
yield
|
||||
|
||||
def test_ignores_timers_which_wouldnt_be_run(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate(
|
||||
"setTimeout(() => { window.stub('should not be logged'); }, 1000)"
|
||||
)
|
||||
page.clock.fast_forward(500)
|
||||
assert len(calls) == 0
|
||||
|
||||
def test_pushes_back_execution_time_for_skipped_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.evaluate("setTimeout(() => { window.stub(Date.now()); }, 1000)")
|
||||
page.clock.fast_forward(2000)
|
||||
assert calls == [[1000 + 2000]]
|
||||
|
||||
def test_supports_string_time_arguments(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate(
|
||||
"setTimeout(() => { window.stub(Date.now()); }, 100000)"
|
||||
) # 100000 = 1:40
|
||||
page.clock.fast_forward("01:50")
|
||||
assert calls == [[1000 + 110000]]
|
||||
|
||||
|
||||
class TestStubTimers:
|
||||
@pytest.fixture(autouse=True)
|
||||
def before_each(self, page: Page) -> Generator[None, None, None]:
|
||||
page.clock.install(time=0)
|
||||
page.clock.pause_at(1)
|
||||
yield
|
||||
|
||||
def test_sets_initial_timestamp(self, page: Page) -> None:
|
||||
page.clock.set_system_time(1.4)
|
||||
assert page.evaluate("Date.now()") == 1400
|
||||
|
||||
def test_replaces_global_setTimeout(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate("setTimeout(window.stub, 1000)")
|
||||
page.clock.run_for(1000)
|
||||
assert len(calls) == 1
|
||||
|
||||
def test_global_fake_setTimeout_should_return_id(self, page: Page) -> None:
|
||||
to = page.evaluate("setTimeout(window.stub, 1000)")
|
||||
assert isinstance(to, int)
|
||||
|
||||
def test_replaces_global_clearTimeout(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate(
|
||||
"""
|
||||
const to = setTimeout(window.stub, 1000);
|
||||
clearTimeout(to);
|
||||
"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert len(calls) == 0
|
||||
|
||||
def test_replaces_global_setInterval(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate("setInterval(window.stub, 500)")
|
||||
page.clock.run_for(1000)
|
||||
assert len(calls) == 2
|
||||
|
||||
def test_replaces_global_clearInterval(self, page: Page, calls: List[Any]) -> None:
|
||||
page.evaluate(
|
||||
"""
|
||||
const to = setInterval(window.stub, 500);
|
||||
clearInterval(to);
|
||||
"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert len(calls) == 0
|
||||
|
||||
def test_replaces_global_performance_now(self, page: Page) -> None:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.waitForPromise = new Promise(async resolve => {
|
||||
const prev = performance.now();
|
||||
await new Promise(f => setTimeout(f, 1000));
|
||||
const next = performance.now();
|
||||
resolve({ prev, next });
|
||||
});
|
||||
}"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert page.evaluate("window.waitForPromise") == {"prev": 1000, "next": 2000}
|
||||
|
||||
def test_fakes_Date_constructor(self, page: Page) -> None:
|
||||
now = page.evaluate("new Date().getTime()")
|
||||
assert now == 1000
|
||||
|
||||
|
||||
class TestStubTimersPerformance:
|
||||
def test_replaces_global_performance_time_origin(self, page: Page) -> None:
|
||||
page.clock.install(time=1)
|
||||
page.clock.pause_at(2)
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.waitForPromise = new Promise(async resolve => {
|
||||
const prev = performance.now();
|
||||
await new Promise(f => setTimeout(f, 1000));
|
||||
const next = performance.now();
|
||||
resolve({ prev, next });
|
||||
});
|
||||
}"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert page.evaluate("performance.timeOrigin") == 1000
|
||||
assert page.evaluate("window.waitForPromise") == {"prev": 1000, "next": 2000}
|
||||
|
||||
|
||||
class TestPopup:
|
||||
def test_should_tick_after_popup(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
now = datetime.datetime.fromisoformat("2015-09-25")
|
||||
page.clock.pause_at(now)
|
||||
with page.expect_popup() as popup_info:
|
||||
page.evaluate("window.open('about:blank')")
|
||||
popup = popup_info.value
|
||||
popup_time = popup.evaluate("Date.now()")
|
||||
assert popup_time == now.timestamp() * 1000
|
||||
page.clock.run_for(1000)
|
||||
popup_time_after = popup.evaluate("Date.now()")
|
||||
assert popup_time_after == now.timestamp() * 1000 + 1000
|
||||
|
||||
def test_should_tick_before_popup(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
now = datetime.datetime.fromisoformat("2015-09-25")
|
||||
page.clock.pause_at(now)
|
||||
page.clock.run_for(1000)
|
||||
with page.expect_popup() as popup_info:
|
||||
page.evaluate("window.open('about:blank')")
|
||||
popup = popup_info.value
|
||||
popup_time = popup.evaluate("Date.now()")
|
||||
assert popup_time == int(now.timestamp() * 1_000 + 1000)
|
||||
assert datetime.datetime.fromtimestamp(popup_time / 1_000).year == 2015
|
||||
|
||||
def test_should_run_time_before_popup(self, page: Page, server: Server) -> None:
|
||||
server.set_route(
|
||||
"/popup.html",
|
||||
lambda res: (
|
||||
res.setHeader("Content-Type", "text/html"),
|
||||
res.write(b"<script>window.time = Date.now()</script>"),
|
||||
res.finish(),
|
||||
),
|
||||
)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
# Wait for 2 second in real life to check that it is past in popup.
|
||||
page.wait_for_timeout(2000)
|
||||
with page.expect_popup() as popup_info:
|
||||
page.evaluate("window.open('{}')".format(server.PREFIX + "/popup.html"))
|
||||
popup = popup_info.value
|
||||
popup_time = popup.evaluate("window.time")
|
||||
assert popup_time >= 2000
|
||||
|
||||
def test_should_not_run_time_before_popup_on_pause(
|
||||
self, page: Page, server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/popup.html",
|
||||
lambda res: (
|
||||
res.setHeader("Content-Type", "text/html"),
|
||||
res.write(b"<script>window.time = Date.now()</script>"),
|
||||
res.finish(),
|
||||
),
|
||||
)
|
||||
page.clock.install(time=0)
|
||||
page.clock.pause_at(1)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
# Wait for 2 second in real life to check that it is past in popup.
|
||||
page.wait_for_timeout(2000)
|
||||
with page.expect_popup() as popup_info:
|
||||
page.evaluate("window.open('{}')".format(server.PREFIX + "/popup.html"))
|
||||
popup = popup_info.value
|
||||
popup_time = popup.evaluate("window.time")
|
||||
assert popup_time == 1000
|
||||
|
||||
|
||||
class TestSetFixedTime:
|
||||
def test_allows_passing_as_int(self, page: Page) -> None:
|
||||
page.clock.set_fixed_time(1)
|
||||
assert page.evaluate("Date.now()") == 1000
|
||||
page.clock.set_fixed_time(int(2))
|
||||
assert page.evaluate("Date.now()") == 2000
|
||||
|
||||
def test_does_not_fake_methods(self, page: Page) -> None:
|
||||
page.clock.set_fixed_time(0)
|
||||
# Should not stall.
|
||||
page.evaluate("new Promise(f => setTimeout(f, 1))")
|
||||
|
||||
def test_allows_setting_time_multiple_times(self, page: Page) -> None:
|
||||
page.clock.set_fixed_time(0.1)
|
||||
assert page.evaluate("Date.now()") == 100
|
||||
page.clock.set_fixed_time(0.2)
|
||||
assert page.evaluate("Date.now()") == 200
|
||||
|
||||
def test_fixed_time_is_not_affected_by_clock_manipulation(self, page: Page) -> None:
|
||||
page.clock.set_fixed_time(0.1)
|
||||
assert page.evaluate("Date.now()") == 100
|
||||
page.clock.fast_forward(20)
|
||||
assert page.evaluate("Date.now()") == 100
|
||||
|
||||
def test_allows_installing_fake_timers_after_setting_time(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.clock.set_fixed_time(0.1)
|
||||
assert page.evaluate("Date.now()") == 100
|
||||
page.clock.set_fixed_time(0.2)
|
||||
page.evaluate("setTimeout(() => window.stub(Date.now()))")
|
||||
page.clock.run_for(0)
|
||||
assert calls == [[200]]
|
||||
|
||||
|
||||
class TestWhileRunning:
|
||||
def test_should_progress_time(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.wait_for_timeout(1000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert 1000 <= now <= 2000
|
||||
|
||||
def test_should_run_for(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.run_for(10000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
def test_should_fast_forward(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.fast_forward(10000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
def test_should_fast_forward_to(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.fast_forward(10000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
def test_should_pause(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1)
|
||||
page.wait_for_timeout(1000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert 0 <= now <= 1000
|
||||
|
||||
def test_should_pause_and_fast_forward(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1)
|
||||
page.clock.fast_forward(1000)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert now == 2000
|
||||
|
||||
def test_should_set_system_time_on_pause(self, page: Page) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1)
|
||||
now = page.evaluate("Date.now()")
|
||||
assert now == 1000
|
||||
|
||||
|
||||
class TestWhileOnPause:
|
||||
def test_fast_forward_should_not_run_nested_immediate(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1000)
|
||||
page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
setTimeout(() => window.stub('inner'), 0);
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
page.clock.fast_forward(1000)
|
||||
assert calls == [["outer"]]
|
||||
page.clock.fast_forward(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
|
||||
def test_run_for_should_not_run_nested_immediate(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1000)
|
||||
page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
setTimeout(() => window.stub('inner'), 0);
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert calls == [["outer"]]
|
||||
page.clock.run_for(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
|
||||
def test_run_for_should_not_run_nested_immediate_from_microtask(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
page.clock.install(time=0)
|
||||
page.goto("data:text/html,")
|
||||
page.clock.pause_at(1000)
|
||||
page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
void Promise.resolve().then(() => setTimeout(() => window.stub('inner'), 0));
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
page.clock.run_for(1000)
|
||||
assert calls == [["outer"]]
|
||||
page.clock.run_for(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
@@ -0,0 +1,49 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
def test_console_messages_should_work(page: Page) -> None:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
for (let i = 0; i < 301; i++)
|
||||
console.log('message' + i);
|
||||
}"""
|
||||
)
|
||||
|
||||
messages = page.console_messages()
|
||||
objects = [{"text": m.text, "type": m.type, "page": m.page} for m in messages]
|
||||
|
||||
expected = []
|
||||
for i in range(201, 301):
|
||||
expected.append({"text": f"message{i}", "type": "log", "page": page})
|
||||
|
||||
assert len(objects) >= 100, "should be at least 100 messages"
|
||||
message_count = len(messages) - len(expected)
|
||||
assert objects[message_count:] == expected, "should return last messages"
|
||||
|
||||
|
||||
def test_should_have_a_timestamp(page: Page) -> None:
|
||||
with page.expect_console_message() as message_info:
|
||||
page.evaluate("() => console.log('hello')")
|
||||
assert message_info.value.timestamp > 0
|
||||
|
||||
|
||||
def test_clear_console_messages_should_drop_buffered_messages(page: Page) -> None:
|
||||
page.evaluate("() => console.log('first')")
|
||||
assert any(m.text == "first" for m in page.console_messages())
|
||||
page.clear_console_messages()
|
||||
assert not any(m.text == "first" for m in page.console_messages())
|
||||
@@ -0,0 +1,36 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
def test_page_errors_should_work(page: Page) -> None:
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
for (let i = 0; i < 301; i++)
|
||||
window.setTimeout(() => { throw new Error('error' + i); }, 0);
|
||||
await new Promise(f => window.setTimeout(f, 100));
|
||||
}"""
|
||||
)
|
||||
|
||||
errors = page.page_errors()
|
||||
messages = [e.message for e in errors]
|
||||
|
||||
expected = []
|
||||
for i in range(201, 301):
|
||||
expected.append(f"error{i}")
|
||||
|
||||
assert len(messages) >= 100, "should be at least 100 errors"
|
||||
message_count = len(messages) - len(expected)
|
||||
assert messages[message_count:] == expected, "should return last errors"
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page, Request, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_return_last_requests(page: Page, server: Server) -> None:
|
||||
page.goto(server.PREFIX + "/title.html")
|
||||
for i in range(200):
|
||||
|
||||
def _handle_route(route: Route) -> None:
|
||||
route.fulfill(
|
||||
status=200,
|
||||
body=f"url:{route.request.url}",
|
||||
)
|
||||
|
||||
page.route(f"**/fetch?{i}", _handle_route)
|
||||
|
||||
# #0 is the navigation request, so start with #1.
|
||||
for i in range(1, 100):
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + f"/fetch?{i}")
|
||||
first_100_requests_with_goto = page.requests()
|
||||
first_100_requests = first_100_requests_with_goto[1:]
|
||||
|
||||
for i in range(100, 200):
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + f"/fetch?{i}")
|
||||
last_100_requests = page.requests()
|
||||
|
||||
all_requests = first_100_requests + last_100_requests
|
||||
|
||||
def gather_response(request: Request) -> dict:
|
||||
response = request.response()
|
||||
assert response
|
||||
return {"text": response.text(), "url": request.url}
|
||||
|
||||
# All 199 requests are fully functional.
|
||||
received = [gather_response(request) for request in all_requests]
|
||||
expected = []
|
||||
for i in range(1, 200):
|
||||
url = server.PREFIX + f"/fetch?{i}"
|
||||
expected.append({"url": url, "text": f"url:{url}"})
|
||||
assert received == expected
|
||||
@@ -0,0 +1,72 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.sync_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_reject_response_finished_if_page_closes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
def handle_get(request: http.Request) -> None:
|
||||
# In Firefox, |fetch| will be hanging until it receives |Content-Type| header
|
||||
# from server.
|
||||
request.setHeader("Content-Type", "text/plain; charset=utf-8")
|
||||
request.write(b"hello ")
|
||||
|
||||
server.set_route("/get", handle_get)
|
||||
# send request and wait for server response
|
||||
with page.expect_response("**/*") as response_info:
|
||||
page.evaluate("() => fetch('./get', { method: 'GET' })")
|
||||
page_response = response_info.value
|
||||
page.close()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page_response.finished()
|
||||
error = exc_info.value
|
||||
assert "closed" in error.message
|
||||
|
||||
|
||||
def test_should_reject_response_finished_if_context_closes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
def handle_get(request: http.Request) -> None:
|
||||
# In Firefox, |fetch| will be hanging until it receives |Content-Type| header
|
||||
# from server.
|
||||
request.setHeader("Content-Type", "text/plain; charset=utf-8")
|
||||
request.write(b"hello ")
|
||||
|
||||
server.set_route("/get", handle_get)
|
||||
# send request and wait for server response
|
||||
with page.expect_response("**/*") as response_info:
|
||||
page.evaluate("() => fetch('./get', { method: 'GET' })")
|
||||
page_response = response_info.value
|
||||
|
||||
page.context.close()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page_response.finished()
|
||||
error = exc_info.value
|
||||
assert "closed" in error.message
|
||||
|
||||
|
||||
def test_should_return_http_version(page: Page, server: Server) -> None:
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.http_version() in ("HTTP/1.0", "HTTP/1.1", "HTTP/2.0")
|
||||
@@ -0,0 +1,349 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Callable, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page, Request, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def _append_with_return_value(values: List, value: Any) -> Any:
|
||||
values.append(value)
|
||||
|
||||
|
||||
def test_should_work(page: Page, server: Server) -> None:
|
||||
page.route("**/*", lambda route: route.fallback())
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_should_fall_back(page: Page, server: Server) -> None:
|
||||
intercepted: List[str] = []
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 1),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 2),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 3),
|
||||
route.fallback(),
|
||||
),
|
||||
)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
def test_should_fall_back_async_delayed(page: Page, server: Server) -> None:
|
||||
intercepted: List[str] = []
|
||||
|
||||
def create_handler(i: int) -> Callable[[Route], None]:
|
||||
def handler(route: Route) -> None:
|
||||
_append_with_return_value(intercepted, i)
|
||||
page.wait_for_timeout(500)
|
||||
route.fallback()
|
||||
|
||||
return handler
|
||||
|
||||
page.route("**/empty.html", create_handler(1))
|
||||
page.route("**/empty.html", create_handler(2))
|
||||
page.route("**/empty.html", create_handler(3))
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
def test_should_chain_once(page: Page, server: Server) -> None:
|
||||
page.route(
|
||||
"**/madeup.txt",
|
||||
lambda route: route.fulfill(status=200, body="fulfilled one"),
|
||||
times=1,
|
||||
)
|
||||
page.route("**/madeup.txt", lambda route: route.fallback(), times=1)
|
||||
|
||||
resp = page.goto(server.PREFIX + "/madeup.txt")
|
||||
assert resp
|
||||
body = resp.body()
|
||||
assert body == b"fulfilled one"
|
||||
|
||||
|
||||
def test_should_not_chain_fulfill(page: Page, server: Server) -> None:
|
||||
failed: List[bool] = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
page.route("**/empty.html", handler)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.fulfill(status=200, body="fulfilled"),
|
||||
)
|
||||
page.route("**/empty.html", lambda route: route.fallback())
|
||||
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
body = response.body()
|
||||
assert body == b"fulfilled"
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
def test_should_not_chain_abort(
|
||||
page: Page, server: Server, is_webkit: bool, is_firefox: bool
|
||||
) -> None:
|
||||
failed: List[bool] = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
page.route("**/empty.html", handler)
|
||||
page.route("**/empty.html", lambda route: route.abort())
|
||||
page.route("**/empty.html", lambda route: route.fallback())
|
||||
|
||||
with pytest.raises(Error) as excinfo:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
if is_webkit:
|
||||
assert "Blocked by Web Inspector" in excinfo.value.message
|
||||
elif is_firefox:
|
||||
assert "NS_ERROR_FAILURE" in excinfo.value.message
|
||||
else:
|
||||
assert "net::ERR_FAILED" in excinfo.value.message
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
def test_should_fall_back_after_exception(page: Page, server: Server) -> None:
|
||||
page.route("**/empty.html", lambda route: route.continue_())
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
try:
|
||||
route.fulfill(response=47) # type: ignore
|
||||
except Exception:
|
||||
route.fallback()
|
||||
|
||||
page.route("**/empty.html", handler)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_should_amend_http_headers(page: Page, server: Server) -> None:
|
||||
values: List[str] = []
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
_append_with_return_value(values, route.request.headers.get("foo"))
|
||||
_append_with_return_value(values, route.request.header_value("FOO"))
|
||||
route.continue_()
|
||||
|
||||
page.route("**/sleep.zzz", handler)
|
||||
|
||||
def handler_with_header_mods(route: Route) -> None:
|
||||
route.fallback(headers={**route.request.headers, "FOO": "bar"})
|
||||
|
||||
page.route("**/*", handler_with_header_mods)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz')")
|
||||
_append_with_return_value(values, server_request_info.value.getHeader("foo"))
|
||||
assert values == ["bar", "bar", "bar"]
|
||||
|
||||
|
||||
def test_should_delete_header_with_undefined_value(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
server.set_route(
|
||||
"/something",
|
||||
lambda r: (
|
||||
r.setHeader("Acces-Control-Allow-Origin", "*"),
|
||||
r.write(b"done"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
intercepted_request = []
|
||||
|
||||
def capture_and_continue(route: Route, request: Request) -> None:
|
||||
intercepted_request.append(request)
|
||||
route.continue_()
|
||||
|
||||
page.route("**/*", capture_and_continue)
|
||||
|
||||
def delete_foo_header(route: Route, request: Request) -> None:
|
||||
headers = request.all_headers()
|
||||
route.fallback(headers={**headers, "foo": None}) # type: ignore
|
||||
|
||||
page.route(server.PREFIX + "/something", delete_foo_header)
|
||||
with server.expect_request("/something") as server_req_info:
|
||||
text = page.evaluate(
|
||||
"""
|
||||
async url => {
|
||||
const data = await fetch(url, {
|
||||
headers: {
|
||||
foo: 'a',
|
||||
bar: 'b',
|
||||
}
|
||||
});
|
||||
return data.text();
|
||||
}
|
||||
""",
|
||||
server.PREFIX + "/something",
|
||||
)
|
||||
server_req = server_req_info.value
|
||||
assert text == "done"
|
||||
assert not intercepted_request[0].headers.get("foo")
|
||||
assert intercepted_request[0].headers.get("bar") == "b"
|
||||
assert not server_req.getHeader("foo")
|
||||
assert server_req.getHeader("bar") == "b"
|
||||
|
||||
|
||||
def test_should_amend_method(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
method: List[str] = []
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(method, route.request.method),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
page.route("**/*", lambda route: route.fallback(method="POST"))
|
||||
|
||||
with server.expect_request("/sleep.zzz") as request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz')")
|
||||
request = request_info.value
|
||||
assert method == ["POST"]
|
||||
assert request.method == b"POST"
|
||||
|
||||
|
||||
def test_should_override_request_url(page: Page, server: Server) -> None:
|
||||
url: List[str] = []
|
||||
page.route(
|
||||
"**/global-var.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(url, route.request.url),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/foo",
|
||||
lambda route: route.fallback(url=server.PREFIX + "/global-var.html"),
|
||||
)
|
||||
|
||||
with server.expect_request("/global-var.html") as server_request_info:
|
||||
with page.expect_event("response") as response_info:
|
||||
page.goto(server.PREFIX + "/foo")
|
||||
server_request = server_request_info.value
|
||||
response = response_info.value
|
||||
assert url == [server.PREFIX + "/global-var.html"]
|
||||
assert response.url == server.PREFIX + "/global-var.html"
|
||||
assert response.request.url == server.PREFIX + "/global-var.html"
|
||||
assert page.evaluate("() => window['globalVar']") == 123
|
||||
assert server_request.uri == b"/global-var.html"
|
||||
assert server_request.method == b"GET"
|
||||
|
||||
|
||||
def test_should_amend_post_data(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
post_data: List[str] = []
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(post_data, route.request.post_data),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
page.route("**/*", lambda route: route.fallback(post_data="doggo"))
|
||||
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })")
|
||||
server_request = server_request_info.value
|
||||
assert post_data == ["doggo"]
|
||||
assert server_request.post_body == b"doggo"
|
||||
|
||||
|
||||
def test_should_amend_binary_post_data(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
post_data_buffer: List[str] = []
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: (
|
||||
_append_with_return_value(post_data_buffer, route.request.post_data),
|
||||
route.continue_(),
|
||||
),
|
||||
)
|
||||
page.route("**/*", lambda route: route.fallback(post_data=b"\x00\x01\x02\x03\x04"))
|
||||
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })")
|
||||
server_request = server_request_info.value
|
||||
# FIXME: should this be bytes?
|
||||
assert post_data_buffer == ["\x00\x01\x02\x03\x04"]
|
||||
assert server_request.method == b"POST"
|
||||
assert server_request.post_body == b"\x00\x01\x02\x03\x04"
|
||||
|
||||
|
||||
def test_should_chain_fallback_with_dynamic_url(server: Server, page: Page) -> None:
|
||||
intercepted: List[int] = []
|
||||
page.route(
|
||||
"**/bar",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 1),
|
||||
route.fallback(url=server.EMPTY_PAGE),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/foo",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 2),
|
||||
route.fallback(url="http://localhost/bar"),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: (
|
||||
_append_with_return_value(intercepted, 3),
|
||||
route.fallback(url="http://localhost/foo"),
|
||||
),
|
||||
)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
def test_should_amend_json_post_data(server: Server, page: Page) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
post_data = []
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
post_data.append(route.request.post_data)
|
||||
route.continue_()
|
||||
|
||||
page.route("**/*", handler)
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: route.fallback(post_data={"foo": "bar"}),
|
||||
)
|
||||
|
||||
with server.expect_request("/sleep.zzz") as server_request:
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })")
|
||||
assert post_data == ['{"foo": "bar"}']
|
||||
assert server_request.value.post_body == b'{"foo": "bar"}'
|
||||
@@ -0,0 +1,34 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_work(page: Page, server: Server) -> None:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
globalThis.objectToDestroy = { hello: 'world' };
|
||||
globalThis.weakRef = new WeakRef(globalThis.objectToDestroy);
|
||||
}"""
|
||||
)
|
||||
page.request_gc()
|
||||
assert page.evaluate("() => globalThis.weakRef.deref()") == {"hello": "world"}
|
||||
|
||||
page.request_gc()
|
||||
assert page.evaluate("() => globalThis.weakRef.deref()") == {"hello": "world"}
|
||||
|
||||
page.evaluate("() => globalThis.objectToDestroy = null")
|
||||
page.request_gc()
|
||||
assert page.evaluate("() => globalThis.weakRef.deref()") is None
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page, Route
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
def test_should_support_timeout_option_in_route_fetch(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
def _handle(request: TestServerRequest) -> None:
|
||||
request.responseHeaders.addRawHeader("Content-Length", "4096")
|
||||
request.responseHeaders.addRawHeader("Content-Type", "text/html")
|
||||
request.write(b"")
|
||||
|
||||
server.set_route(
|
||||
"/slow",
|
||||
_handle,
|
||||
)
|
||||
|
||||
def handle(route: Route) -> None:
|
||||
with pytest.raises(Error) as error:
|
||||
route.fetch(timeout=1000)
|
||||
assert "Route.fetch: Timeout 1000ms exceeded." in error.value.message
|
||||
|
||||
page.route("**/*", lambda route: handle(route))
|
||||
with pytest.raises(Error) as error:
|
||||
page.goto(server.PREFIX + "/slow", timeout=2000)
|
||||
assert "Timeout 2000ms exceeded" in error.value.message
|
||||
|
||||
|
||||
def test_should_intercept_with_url_override(server: Server, page: Page) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = route.fetch(url=server.PREFIX + "/one-style.html")
|
||||
route.fulfill(response=response)
|
||||
|
||||
page.route("**/*.html", lambda route: handle(route))
|
||||
response = page.goto(server.PREFIX + "/empty.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert "one-style.css" in response.body().decode("utf-8")
|
||||
@@ -0,0 +1,36 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import BrowserContext, Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_context_request_should_support_timeout_option(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
# https://github.com/microsoft/playwright/issues/39220
|
||||
|
||||
server.set_route("/", lambda req: None)
|
||||
with pytest.raises(Error, match="Timeout 123ms exceeded"):
|
||||
page.request.get(server.PREFIX, timeout=123)
|
||||
with pytest.raises(Error, match="Timeout 123ms exceeded"):
|
||||
context.request.get(server.PREFIX, timeout=123)
|
||||
|
||||
context.set_default_timeout(123)
|
||||
with pytest.raises(Error, match="Timeout 123ms exceeded"):
|
||||
page.request.get(server.PREFIX)
|
||||
with pytest.raises(Error, match="Timeout 123ms exceeded"):
|
||||
context.request.get(server.PREFIX)
|
||||
@@ -0,0 +1,255 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option(server: Server, page: Page) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", "blue")
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_value(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", "blue")
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_label(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", label="Indigo")
|
||||
assert page.evaluate("result.onInput") == ["indigo"]
|
||||
assert page.evaluate("result.onChange") == ["indigo"]
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_empty_label(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<select>
|
||||
<option value="indigo">Indigo</option>
|
||||
<option value="violet"></option>
|
||||
</select>
|
||||
"""
|
||||
)
|
||||
assert page.locator("select").input_value() == "indigo"
|
||||
page.select_option("select", label="")
|
||||
assert page.locator("select").input_value() == "violet"
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_handle(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", element=page.query_selector("[id=whiteOption]"))
|
||||
assert page.evaluate("result.onInput") == ["white"]
|
||||
assert page.evaluate("result.onChange") == ["white"]
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_index(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", index=2)
|
||||
assert page.evaluate("result.onInput") == ["brown"]
|
||||
assert page.evaluate("result.onChange") == ["brown"]
|
||||
|
||||
|
||||
def test_select_option_should_select_single_option_by_index_0(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", index=0)
|
||||
assert page.evaluate("result.onInput") == ["black"]
|
||||
|
||||
|
||||
def test_select_option_should_select_only_first_option(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", ["blue", "green", "red"])
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
def test_select_option_should_not_throw_when_select_causes_navigation(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.eval_on_selector(
|
||||
"select",
|
||||
"select => select.addEventListener('input', () => window.location = '/empty.html')",
|
||||
)
|
||||
with page.expect_navigation():
|
||||
page.select_option("select", "blue")
|
||||
assert "empty.html" in page.url
|
||||
|
||||
|
||||
def test_select_option_should_select_multiple_options(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("makeMultiple()")
|
||||
page.select_option("select", ["blue", "green", "red"])
|
||||
assert page.evaluate("result.onInput") == ["blue", "green", "red"]
|
||||
assert page.evaluate("result.onChange") == ["blue", "green", "red"]
|
||||
|
||||
|
||||
def test_select_option_should_select_multiple_options_with_attributes(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("makeMultiple()")
|
||||
page.select_option(
|
||||
"select",
|
||||
value="blue",
|
||||
label="Green",
|
||||
index=4,
|
||||
)
|
||||
assert page.evaluate("result.onInput") == ["blue", "gray", "green"]
|
||||
assert page.evaluate("result.onChange") == ["blue", "gray", "green"]
|
||||
|
||||
|
||||
def test_select_option_should_select_option_with_empty_value(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.set_content(
|
||||
"""
|
||||
<select>
|
||||
<option value="first">First</option>
|
||||
<option value="">Second</option>
|
||||
</select>
|
||||
"""
|
||||
)
|
||||
assert page.locator("select").input_value() == "first"
|
||||
page.select_option("select", value="")
|
||||
assert page.locator("select").input_value() == ""
|
||||
|
||||
|
||||
def test_select_option_should_respect_event_bubbling(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", "blue")
|
||||
assert page.evaluate("result.onBubblingInput") == ["blue"]
|
||||
assert page.evaluate("result.onBubblingChange") == ["blue"]
|
||||
|
||||
|
||||
def test_select_option_should_throw_when_element_is_not_a__select_(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.select_option("body", "")
|
||||
assert "Element is not a <select> element" in exc_info.value.message
|
||||
|
||||
|
||||
def test_select_option_should_return_on_no_matched_values(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.select_option("select", ["42", "abc"], timeout=1000)
|
||||
assert "Timeout 1000" in exc_info.value.message
|
||||
|
||||
|
||||
def test_select_option_should_return_an_array_of_matched_values(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("makeMultiple()")
|
||||
result = page.select_option("select", ["blue", "black", "magenta"])
|
||||
assert result == ["black", "blue", "magenta"]
|
||||
|
||||
|
||||
def test_select_option_should_return_an_array_of_one_element_when_multiple_is_not_set(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
result = page.select_option("select", ["42", "blue", "black", "magenta"])
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
def test_select_option_should_return_on_no_values(server: Server, page: Page) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
result = page.select_option("select", [])
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_select_option_should_unselect_with_null(server: Server, page: Page) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("makeMultiple()")
|
||||
result = page.select_option("select", ["blue", "black", "magenta"])
|
||||
assert result == ["black", "blue", "magenta"]
|
||||
page.select_option("select", None)
|
||||
assert page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
def test_select_option_should_deselect_all_options_when_passed_no_values_for_a_multiple_select(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("makeMultiple()")
|
||||
page.select_option("select", ["blue", "black", "magenta"])
|
||||
page.select_option("select", [])
|
||||
assert page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
def test_select_option_should_deselect_all_options_when_passed_no_values_for_a_select_without_multiple(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", ["blue", "black", "magenta"])
|
||||
page.select_option("select", [])
|
||||
assert page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
def test_select_option_should_work_when_re_defining_top_level_event_class(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.evaluate("window.Event = null")
|
||||
page.select_option("select", "blue")
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
def test_select_options_should_fall_back_to_selecting_by_label(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
page.goto(server.PREFIX + "/input/select.html")
|
||||
page.select_option("select", "Blue")
|
||||
assert page.evaluate("result.onInput") == ["blue"]
|
||||
assert page.evaluate("result.onChange") == ["blue"]
|
||||
@@ -0,0 +1,33 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_be_able_to_save_pdf_file(page: Page, tmp_path: Path) -> None:
|
||||
output_file = tmp_path / "foo.png"
|
||||
page.pdf(path=str(output_file))
|
||||
assert os.path.getsize(output_file) > 0
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
def test_should_be_able_capture_pdf_without_path(page: Page) -> None:
|
||||
buffer = page.pdf()
|
||||
assert buffer
|
||||
@@ -0,0 +1,378 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, Error, Page, Selectors
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
def test_selectors_register_should_work(
|
||||
selectors: Selectors, browser: Browser, browser_name: str
|
||||
) -> None:
|
||||
tag_selector = """
|
||||
{
|
||||
create(root, target) {
|
||||
return target.nodeName;
|
||||
},
|
||||
query(root, selector) {
|
||||
return root.querySelector(selector);
|
||||
},
|
||||
queryAll(root, selector) {
|
||||
return Array.from(root.querySelectorAll(selector));
|
||||
}
|
||||
}"""
|
||||
|
||||
selector_name = f"tag_{browser_name}"
|
||||
selector2_name = f"tag2_{browser_name}"
|
||||
|
||||
# Register one engine before creating context.
|
||||
selectors.register(selector_name, tag_selector)
|
||||
|
||||
context = browser.new_context()
|
||||
# Register another engine after creating context.
|
||||
selectors.register(selector2_name, tag_selector)
|
||||
|
||||
page = context.new_page()
|
||||
page.set_content("<div><span></span></div><div></div>")
|
||||
|
||||
assert page.eval_on_selector(f"{selector_name}=DIV", "e => e.nodeName") == "DIV"
|
||||
assert page.eval_on_selector(f"{selector_name}=SPAN", "e => e.nodeName") == "SPAN"
|
||||
assert page.eval_on_selector_all(f"{selector_name}=DIV", "es => es.length") == 2
|
||||
|
||||
assert page.eval_on_selector(f"{selector2_name}=DIV", "e => e.nodeName") == "DIV"
|
||||
assert page.eval_on_selector(f"{selector2_name}=SPAN", "e => e.nodeName") == "SPAN"
|
||||
assert page.eval_on_selector_all(f"{selector2_name}=DIV", "es => es.length") == 2
|
||||
|
||||
# Selector names are case-sensitive.
|
||||
with pytest.raises(Error) as exc:
|
||||
page.query_selector("tAG=DIV")
|
||||
assert 'Unknown engine "tAG" while parsing selector tAG=DIV' in exc.value.message
|
||||
|
||||
context.close()
|
||||
|
||||
|
||||
def test_selectors_register_should_work_with_path(
|
||||
selectors: Selectors, page: Page, utils: Utils, assetdir: Path
|
||||
) -> None:
|
||||
utils.register_selector_engine(
|
||||
selectors, "foo", path=assetdir / "sectionselectorengine.js"
|
||||
)
|
||||
page.set_content("<section></section>")
|
||||
assert page.eval_on_selector("foo=whatever", "e => e.nodeName") == "SECTION"
|
||||
|
||||
|
||||
def test_selectors_register_should_work_in_main_and_isolated_world(
|
||||
selectors: Selectors, page: Page, utils: Utils
|
||||
) -> None:
|
||||
dummy_selector_script = """{
|
||||
create(root, target) { },
|
||||
query(root, selector) {
|
||||
return window.__answer;
|
||||
},
|
||||
queryAll(root, selector) {
|
||||
return window['__answer'] ? [window['__answer'], document.body, document.documentElement] : [];
|
||||
}
|
||||
}"""
|
||||
|
||||
utils.register_selector_engine(selectors, "main", dummy_selector_script)
|
||||
utils.register_selector_engine(
|
||||
selectors, "isolated", dummy_selector_script, content_script=True
|
||||
)
|
||||
page.set_content("<div><span><section></section></span></div>")
|
||||
page.evaluate('() => window.__answer = document.querySelector("span")')
|
||||
# Works in main if asked.
|
||||
assert page.eval_on_selector("main=ignored", "e => e.nodeName") == "SPAN"
|
||||
assert page.eval_on_selector("css=div >> main=ignored", "e => e.nodeName") == "SPAN"
|
||||
assert page.eval_on_selector_all(
|
||||
"main=ignored", "es => window.__answer !== undefined"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all("main=ignored", "es => es.filter(e => e).length") == 3
|
||||
)
|
||||
# Works in isolated by default.
|
||||
assert page.query_selector("isolated=ignored") is None
|
||||
assert page.query_selector("css=div >> isolated=ignored") is None
|
||||
# $$eval always works in main, to avoid adopting nodes one by one.
|
||||
assert page.eval_on_selector_all(
|
||||
"isolated=ignored", "es => window.__answer !== undefined"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all("isolated=ignored", "es => es.filter(e => e).length")
|
||||
== 3
|
||||
)
|
||||
# At least one engine in main forces all to be in main.
|
||||
assert (
|
||||
page.eval_on_selector("main=ignored >> isolated=ignored", "e => e.nodeName")
|
||||
== "SPAN"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector("isolated=ignored >> main=ignored", "e => e.nodeName")
|
||||
== "SPAN"
|
||||
)
|
||||
# Can be chained to css.
|
||||
assert (
|
||||
page.eval_on_selector("main=ignored >> css=section", "e => e.nodeName")
|
||||
== "SECTION"
|
||||
)
|
||||
|
||||
|
||||
def test_selectors_register_should_handle_errors(
|
||||
selectors: Selectors, page: Page, utils: Utils
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
page.query_selector("neverregister=ignored")
|
||||
assert (
|
||||
'Unknown engine "neverregister" while parsing selector neverregister=ignored'
|
||||
in exc.value.message
|
||||
)
|
||||
|
||||
dummy_selector_engine_script = """{
|
||||
create(root, target) {
|
||||
return target.nodeName;
|
||||
},
|
||||
query(root, selector) {
|
||||
return root.querySelector('dummy');
|
||||
},
|
||||
queryAll(root, selector) {
|
||||
return Array.from(root.query_selector_all('dummy'));
|
||||
}
|
||||
}"""
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
selectors.register("$", dummy_selector_engine_script)
|
||||
assert (
|
||||
exc.value.message
|
||||
== "Selectors.register: Selector engine name may only contain [a-zA-Z0-9_] characters"
|
||||
)
|
||||
|
||||
# Selector names are case-sensitive.
|
||||
utils.register_selector_engine(selectors, "dummy", dummy_selector_engine_script)
|
||||
utils.register_selector_engine(selectors, "duMMy", dummy_selector_engine_script)
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
selectors.register("dummy", dummy_selector_engine_script)
|
||||
assert (
|
||||
exc.value.message
|
||||
== 'Selectors.register: "dummy" selector engine has been already registered'
|
||||
)
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
selectors.register("css", dummy_selector_engine_script)
|
||||
assert (
|
||||
exc.value.message == 'Selectors.register: "css" is a predefined selector engine'
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_layout_selectors(page: Page) -> None:
|
||||
# +--+ +--+
|
||||
# | 1| | 2|
|
||||
# +--+ ++-++
|
||||
# | 3| | 4|
|
||||
# +-------+ ++-++
|
||||
# | 0 | | 5|
|
||||
# | +--+ +--+--+
|
||||
# | | 6| | 7|
|
||||
# | +--+ +--+
|
||||
# | |
|
||||
# O-------+
|
||||
# +--+
|
||||
# | 8|
|
||||
# +--++--+
|
||||
# | 9|
|
||||
# +--+
|
||||
|
||||
boxes = [
|
||||
# x, y, width, height
|
||||
[0, 0, 150, 150],
|
||||
[100, 200, 50, 50],
|
||||
[200, 200, 50, 50],
|
||||
[100, 150, 50, 50],
|
||||
[201, 150, 50, 50],
|
||||
[200, 100, 50, 50],
|
||||
[50, 50, 50, 50],
|
||||
[150, 50, 50, 50],
|
||||
[150, -51, 50, 50],
|
||||
[201, -101, 50, 50],
|
||||
]
|
||||
page.set_content(
|
||||
'<container style="width: 500px; height: 500px; position: relative;"></container>'
|
||||
)
|
||||
page.eval_on_selector(
|
||||
"container",
|
||||
"""(container, boxes) => {
|
||||
for (let i = 0; i < boxes.length; i++) {
|
||||
const div = document.createElement('div');
|
||||
div.style.position = 'absolute';
|
||||
div.style.overflow = 'hidden';
|
||||
div.style.boxSizing = 'border-box';
|
||||
div.style.border = '1px solid black';
|
||||
div.id = 'id' + i;
|
||||
div.textContent = 'id' + i;
|
||||
const box = boxes[i];
|
||||
div.style.left = box[0] + 'px';
|
||||
// Note that top is a flipped y coordinate.
|
||||
div.style.top = (250 - box[1] - box[3]) + 'px';
|
||||
div.style.width = box[2] + 'px';
|
||||
div.style.height = box[3] + 'px';
|
||||
container.appendChild(div);
|
||||
const span = document.createElement('span');
|
||||
span.textContent = '' + i;
|
||||
div.appendChild(span);
|
||||
}
|
||||
}""",
|
||||
boxes,
|
||||
)
|
||||
|
||||
assert page.eval_on_selector("div:right-of(#id6)", "e => e.id") == "id7"
|
||||
assert page.eval_on_selector("div:right-of(#id1)", "e => e.id") == "id2"
|
||||
assert page.eval_on_selector("div:right-of(#id3)", "e => e.id") == "id4"
|
||||
assert page.query_selector("div:right-of(#id4)") is None
|
||||
assert page.eval_on_selector("div:right-of(#id0)", "e => e.id") == "id7"
|
||||
assert page.eval_on_selector("div:right-of(#id8)", "e => e.id") == "id9"
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:right-of(#id3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id2,id5,id7,id8,id9"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:right-of(#id3, 50)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id2,id5,id7,id8"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:right-of(#id3, 49)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id8"
|
||||
)
|
||||
|
||||
assert page.eval_on_selector("div:left-of(#id2)", "e => e.id") == "id1"
|
||||
assert page.query_selector("div:left-of(#id0)") is None
|
||||
assert page.eval_on_selector("div:left-of(#id5)", "e => e.id") == "id0"
|
||||
assert page.eval_on_selector("div:left-of(#id9)", "e => e.id") == "id8"
|
||||
assert page.eval_on_selector("div:left-of(#id4)", "e => e.id") == "id3"
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:left-of(#id5)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id7,id3,id1,id6,id8"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:left-of(#id5, 3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id8"
|
||||
)
|
||||
|
||||
assert page.eval_on_selector("div:above(#id0)", "e => e.id") == "id3"
|
||||
assert page.eval_on_selector("div:above(#id5)", "e => e.id") == "id4"
|
||||
assert page.eval_on_selector("div:above(#id7)", "e => e.id") == "id5"
|
||||
assert page.eval_on_selector("div:above(#id8)", "e => e.id") == "id0"
|
||||
assert page.eval_on_selector("div:above(#id9)", "e => e.id") == "id8"
|
||||
assert page.query_selector("div:above(#id2)") is None
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:above(#id5)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id2,id3,id1"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:above(#id5, 20)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id3"
|
||||
)
|
||||
|
||||
assert page.eval_on_selector("div:below(#id4)", "e => e.id") == "id5"
|
||||
assert page.eval_on_selector("div:below(#id3)", "e => e.id") == "id0"
|
||||
assert page.eval_on_selector("div:below(#id2)", "e => e.id") == "id4"
|
||||
assert page.eval_on_selector("div:below(#id6)", "e => e.id") == "id8"
|
||||
assert page.eval_on_selector("div:below(#id7)", "e => e.id") == "id8"
|
||||
assert page.eval_on_selector("div:below(#id8)", "e => e.id") == "id9"
|
||||
assert page.query_selector("div:below(#id9)") is None
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:below(#id3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id6,id7,id8,id9"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:below(#id3, 105)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id6,id7"
|
||||
)
|
||||
|
||||
assert page.eval_on_selector("div:near(#id0)", "e => e.id") == "id3"
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:near(#id7)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id3,id6"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:near(#id0)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id3,id6,id7,id8,id1,id5"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:near(#id6)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id3,id7"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:near(#id6, 10)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0"
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:near(#id0, 100)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id3,id6,id7,id8,id1,id5,id4,id2"
|
||||
)
|
||||
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:below(#id5):above(#id8)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id6"
|
||||
)
|
||||
assert page.eval_on_selector("div:below(#id5):above(#id8)", "e => e.id") == "id7"
|
||||
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
"div:right-of(#id0) + div:above(#id8)",
|
||||
"els => els.map(e => e.id).join(',')",
|
||||
)
|
||||
== "id5,id6,id3"
|
||||
)
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.query_selector(":near(50)")
|
||||
assert (
|
||||
'"near" engine expects a selector list and optional maximum distance in pixels'
|
||||
in exc_info.value.message
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
page.query_selector('left-of="div"')
|
||||
assert '"left-of" selector cannot be first' in exc_info.value.message
|
||||
@@ -0,0 +1,73 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_fetch_original_request_and_fulfill(page: Page, server: Server) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(response=response)
|
||||
|
||||
page.route("**/*", handle)
|
||||
response = page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert page.title() == "Woof-Woof"
|
||||
|
||||
|
||||
def test_should_fulfill_json(page: Page, server: Server) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
route.fulfill(status=201, headers={"foo": "bar"}, json={"bar": "baz"})
|
||||
|
||||
page.route("**/*", handle)
|
||||
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert response.json() == {"bar": "baz"}
|
||||
|
||||
|
||||
def test_should_fulfill_json_overriding_existing_response(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/tags",
|
||||
lambda request: (
|
||||
request.setHeader("foo", "bar"),
|
||||
request.write('{"tags": ["a", "b"]}'.encode()),
|
||||
request.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
original = {}
|
||||
|
||||
def handle(route: Route) -> None:
|
||||
response = route.fetch()
|
||||
json = response.json()
|
||||
original["tags"] = json["tags"]
|
||||
json["tags"] = ["c"]
|
||||
route.fulfill(response=response, json=json)
|
||||
|
||||
page.route("**/*", handle)
|
||||
|
||||
response = page.goto(server.PREFIX + "/tags")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert response.headers["foo"] == "bar"
|
||||
assert original["tags"] == ["a", "b"]
|
||||
assert response.json() == {"tags": ["c"]}
|
||||
@@ -0,0 +1,147 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.sync_api import Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_not_follow_redirects_when_max_redirects_is_set_to_0_in_route_fetch(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
server.set_redirect("/foo", "/empty.html")
|
||||
|
||||
def handle(route: Route) -> None:
|
||||
response = route.fetch(max_redirects=0)
|
||||
assert response.headers["location"] == "/empty.html"
|
||||
assert response.status == 302
|
||||
route.fulfill(body="hello")
|
||||
|
||||
page.route("**/*", lambda route: handle(route))
|
||||
page.goto(server.PREFIX + "/foo")
|
||||
assert "hello" in page.content()
|
||||
|
||||
|
||||
def test_should_fulfill_intercepted_response(page: Page, server: Server) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(
|
||||
response=response,
|
||||
status=201,
|
||||
headers={"foo": "bar"},
|
||||
content_type="text/plain",
|
||||
body="Yo, page!",
|
||||
)
|
||||
|
||||
page.route("**/*", handle)
|
||||
response = page.goto(server.PREFIX + "/empty.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.headers["foo"] == "bar"
|
||||
assert response.headers["content-type"] == "text/plain"
|
||||
assert page.evaluate("() => document.body.textContent") == "Yo, page!"
|
||||
|
||||
|
||||
def test_should_fulfill_response_with_empty_body(page: Page, server: Server) -> None:
|
||||
def handle(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(
|
||||
response=response, status=201, body="", headers={"content-length": "0"}
|
||||
)
|
||||
|
||||
page.route("**/*", handle)
|
||||
response = page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == ""
|
||||
|
||||
|
||||
def test_should_override_with_defaults_when_intercepted_response_not_provided(
|
||||
page: Page, server: Server, browser_name: str
|
||||
) -> None:
|
||||
def server_handler(request: http.Request) -> None:
|
||||
request.setHeader("foo", "bar")
|
||||
request.write("my content".encode())
|
||||
request.finish()
|
||||
|
||||
server.set_route("/empty.html", server_handler)
|
||||
|
||||
def handle(route: Route) -> None:
|
||||
page.request.fetch(route.request)
|
||||
route.fulfill(status=201)
|
||||
|
||||
page.route("**/*", handle)
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == ""
|
||||
if browser_name == "webkit":
|
||||
assert response.headers == {"content-type": "text/plain"}
|
||||
else:
|
||||
assert response.headers == {}
|
||||
|
||||
|
||||
def test_should_fulfill_with_any_response(page: Page, server: Server) -> None:
|
||||
def server_handler(request: http.Request) -> None:
|
||||
request.setHeader("foo", "bar")
|
||||
request.write("Woo-hoo".encode())
|
||||
request.finish()
|
||||
|
||||
server.set_route("/sample", server_handler)
|
||||
sample_response = page.request.get(server.PREFIX + "/sample")
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(
|
||||
response=sample_response, status=201, content_type="text/plain"
|
||||
),
|
||||
)
|
||||
response = page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.text() == "Woo-hoo"
|
||||
assert response.headers["foo"] == "bar"
|
||||
|
||||
|
||||
def test_should_support_fulfill_after_intercept(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
def handle_route(route: Route) -> None:
|
||||
response = page.request.fetch(route.request)
|
||||
route.fulfill(response=response)
|
||||
|
||||
page.route("**", handle_route)
|
||||
with server.expect_request("/title.html") as request_info:
|
||||
response = page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
request = request_info.value
|
||||
assert request.uri.decode() == "/title.html"
|
||||
original = (assetdir / "title.html").read_text()
|
||||
assert response.text() == original
|
||||
|
||||
|
||||
def test_should_intercept_by_glob(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.route(
|
||||
"http://localhos**?*oo",
|
||||
lambda route: route.fulfill(body="intercepted", status=200),
|
||||
)
|
||||
|
||||
result = page.evaluate(
|
||||
"url => fetch(url).then(r => r.text())", server.PREFIX + "/?foo"
|
||||
)
|
||||
|
||||
assert result == "intercepted"
|
||||
@@ -0,0 +1,105 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, Page, ResourceTiming
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_work(page: Page, server: Server) -> None:
|
||||
with page.expect_event("requestfinished") as request_info:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
request = request_info.value
|
||||
timing = request.timing
|
||||
verify_connections_timing_consistency(timing)
|
||||
assert timing["requestStart"] >= timing["connectEnd"]
|
||||
assert timing["responseStart"] >= timing["requestStart"]
|
||||
assert timing["responseEnd"] >= timing["responseStart"]
|
||||
assert timing["responseEnd"] < 10000
|
||||
|
||||
|
||||
def test_should_work_for_subresource(
|
||||
page: Page, server: Server, is_win: bool, is_mac: bool, is_webkit: bool
|
||||
) -> None:
|
||||
if is_webkit and (is_mac or is_win):
|
||||
pytest.skip()
|
||||
requests = []
|
||||
page.on("requestfinished", lambda request: requests.append(request))
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
assert len(requests) >= 2
|
||||
timing = requests[1].timing
|
||||
verify_connections_timing_consistency(timing)
|
||||
assert timing["requestStart"] >= 0
|
||||
assert timing["responseStart"] > timing["requestStart"]
|
||||
assert timing["responseEnd"] >= timing["responseStart"]
|
||||
assert timing["responseEnd"] < 10000
|
||||
|
||||
|
||||
def test_should_work_for_ssl(
|
||||
browser: Browser, https_server: Server, is_mac: bool, is_webkit: bool
|
||||
) -> None:
|
||||
if is_webkit and is_mac:
|
||||
pytest.skip()
|
||||
page = browser.new_page(ignore_https_errors=True)
|
||||
with page.expect_event("requestfinished") as request_info:
|
||||
page.goto(https_server.EMPTY_PAGE)
|
||||
request = request_info.value
|
||||
timing = request.timing
|
||||
verify_connections_timing_consistency(timing)
|
||||
assert timing["requestStart"] >= timing["connectEnd"]
|
||||
assert timing["responseStart"] >= timing["requestStart"]
|
||||
assert timing["responseEnd"] >= timing["responseStart"]
|
||||
assert timing["responseEnd"] < 10000
|
||||
page.close()
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("webkit") # In WebKit, redirects don"t carry the timing info
|
||||
def test_should_work_for_redirect(page: Page, server: Server) -> None:
|
||||
server.set_redirect("/foo.html", "/empty.html")
|
||||
responses = []
|
||||
page.on("response", lambda response: responses.append(response))
|
||||
page.goto(server.PREFIX + "/foo.html")
|
||||
for r in responses:
|
||||
r.finished()
|
||||
|
||||
assert len(responses) == 2
|
||||
assert responses[0].url == server.PREFIX + "/foo.html"
|
||||
assert responses[1].url == server.PREFIX + "/empty.html"
|
||||
|
||||
timing1 = responses[0].request.timing
|
||||
verify_connections_timing_consistency(timing1)
|
||||
assert timing1["requestStart"] >= timing1["connectEnd"]
|
||||
assert timing1["responseStart"] > timing1["requestStart"]
|
||||
assert timing1["responseEnd"] >= timing1["responseStart"]
|
||||
assert timing1["responseEnd"] < 10000
|
||||
|
||||
timing2 = responses[1].request.timing
|
||||
verify_connections_timing_consistency(timing2)
|
||||
assert timing2["requestStart"] >= 0
|
||||
assert timing2["responseStart"] > timing2["requestStart"]
|
||||
assert timing2["responseEnd"] >= timing2["responseStart"]
|
||||
assert timing2["responseEnd"] < 10000
|
||||
|
||||
|
||||
def verify_timing_value(value: float, previous: float) -> None:
|
||||
assert value == -1 or value > 0 and value >= previous
|
||||
|
||||
|
||||
def verify_connections_timing_consistency(timing: ResourceTiming) -> None:
|
||||
verify_timing_value(timing["domainLookupStart"], -1)
|
||||
verify_timing_value(timing["domainLookupEnd"], timing["domainLookupStart"])
|
||||
verify_timing_value(timing["connectStart"], timing["domainLookupEnd"])
|
||||
verify_timing_value(timing["secureConnectionStart"], timing["connectStart"])
|
||||
verify_timing_value(timing["connectEnd"], timing["secureConnectionStart"])
|
||||
@@ -0,0 +1,374 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Awaitable, Callable, Literal, Optional, Union
|
||||
|
||||
from playwright.sync_api import Browser, Frame, Page, WebSocketRoute
|
||||
from tests.server import Server, WebSocketProtocol
|
||||
|
||||
|
||||
def assert_equal(
|
||||
actual_cb: Callable[[], Union[Any, Awaitable[Any]]], expected: Any
|
||||
) -> None:
|
||||
__tracebackhide__ = True
|
||||
start_time = time.time()
|
||||
attempts = 0
|
||||
while True:
|
||||
actual = actual_cb()
|
||||
if actual == expected:
|
||||
return
|
||||
attempts += 1
|
||||
if time.time() - start_time > 10:
|
||||
raise TimeoutError(f"Timed out after 10 seconds. Last actual was: {actual}")
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
def setup_ws(
|
||||
target: Union[Page, Frame],
|
||||
server: Server,
|
||||
protocol: Union[Literal["blob"], Literal["arraybuffer"]],
|
||||
) -> None:
|
||||
target.goto(server.EMPTY_PAGE)
|
||||
target.evaluate(
|
||||
"""({ port, binaryType }) => {
|
||||
window.log = [];
|
||||
window.ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
window.ws.binaryType = binaryType;
|
||||
window.ws.addEventListener('open', () => window.log.push('open'));
|
||||
window.ws.addEventListener('close', event => window.log.push(`close code=${event.code} reason=${event.reason} wasClean=${event.wasClean}`));
|
||||
window.ws.addEventListener('error', event => window.log.push(`error`));
|
||||
window.ws.addEventListener('message', async event => {
|
||||
let data;
|
||||
if (typeof event.data === 'string')
|
||||
data = event.data;
|
||||
else if (event.data instanceof Blob)
|
||||
data = 'blob:' + event.data.text();
|
||||
else
|
||||
data = 'arraybuffer:' + (new Blob([event.data])).text();
|
||||
window.log.push(`message: data=${data} origin=${event.origin} lastEventId=${event.lastEventId}`);
|
||||
});
|
||||
window.wsOpened = new Promise(f => window.ws.addEventListener('open', () => f()));
|
||||
}""",
|
||||
{"port": server.PORT, "binaryType": protocol},
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_ws_close(page: Page, server: Server) -> None:
|
||||
route: Optional["WebSocketRoute"] = None
|
||||
|
||||
def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
ws.connect_to_server()
|
||||
nonlocal route
|
||||
route = ws
|
||||
|
||||
page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
|
||||
with server.expect_websocket() as ws_task:
|
||||
setup_ws(page, server, "blob")
|
||||
page.evaluate("window.wsOpened")
|
||||
ws = ws_task.value
|
||||
assert route
|
||||
route.send("hello")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=hello origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
|
||||
closed_event = []
|
||||
ws.events.once("close", lambda code, reason: closed_event.append((code, reason)))
|
||||
route.close(code=3009, reason="oops")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=hello origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
"close code=3009 reason=oops wasClean=true",
|
||||
],
|
||||
)
|
||||
assert_equal(lambda: closed_event, [(3009, "oops")])
|
||||
|
||||
|
||||
def test_should_pattern_match(page: Page, server: Server) -> None:
|
||||
page.route_web_socket(re.compile(r".*/ws$"), lambda ws: ws.connect_to_server())
|
||||
page.route_web_socket(
|
||||
"**/mock-ws", lambda ws: ws.on_message(lambda message: ws.send("mock-response"))
|
||||
)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
with server.expect_websocket() as ws_info:
|
||||
page.evaluate(
|
||||
"""async ({ port }) => {
|
||||
window.log = [];
|
||||
window.ws1 = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
window.ws1.addEventListener('message', event => window.log.push(`ws1:${event.data}`));
|
||||
window.ws2 = new WebSocket('ws://localhost:' + port + '/something/something/mock-ws');
|
||||
window.ws2.addEventListener('message', event => window.log.push(`ws2:${event.data}`));
|
||||
await Promise.all([
|
||||
new Promise(f => window.ws1.addEventListener('open', f)),
|
||||
new Promise(f => window.ws2.addEventListener('open', f)),
|
||||
]);
|
||||
}""",
|
||||
{"port": server.PORT},
|
||||
)
|
||||
ws = ws_info.value
|
||||
ws.events.on("message", lambda payload, isBinary: ws.sendMessage(b"response"))
|
||||
|
||||
page.evaluate("window.ws1.send('request')")
|
||||
assert_equal(lambda: page.evaluate("window.log"), ["ws1:response"])
|
||||
|
||||
page.evaluate("window.ws2.send('request')")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"), ["ws1:response", "ws2:mock-response"]
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_server(page: Page, server: Server) -> None:
|
||||
route = None
|
||||
|
||||
def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
server = ws.connect_to_server()
|
||||
|
||||
def _ws_on_message(message: Union[str, bytes]) -> None:
|
||||
if message == "to-respond":
|
||||
ws.send("response")
|
||||
return
|
||||
if message == "to-block":
|
||||
return
|
||||
if message == "to-modify":
|
||||
server.send("modified")
|
||||
return
|
||||
server.send(message)
|
||||
|
||||
ws.on_message(_ws_on_message)
|
||||
|
||||
def _server_on_message(message: Union[str, bytes]) -> None:
|
||||
if message == "to-block":
|
||||
return
|
||||
if message == "to-modify":
|
||||
ws.send("modified")
|
||||
return
|
||||
ws.send(message)
|
||||
|
||||
server.on_message(_server_on_message)
|
||||
server.send("fake")
|
||||
nonlocal route
|
||||
route = ws
|
||||
|
||||
page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
log = []
|
||||
|
||||
def _once_web_socket_connection(ws: WebSocketProtocol) -> None:
|
||||
ws.events.on(
|
||||
"message", lambda data, is_binary: log.append(f"message: {data.decode()}")
|
||||
)
|
||||
ws.events.on(
|
||||
"close",
|
||||
lambda code, reason: log.append(f"close: code={code} reason={reason}"),
|
||||
)
|
||||
|
||||
server.once_web_socket_connection(_once_web_socket_connection)
|
||||
|
||||
with server.expect_websocket() as ws_info:
|
||||
setup_ws(page, server, "blob")
|
||||
page.evaluate("window.wsOpened")
|
||||
ws = ws_info.value
|
||||
assert_equal(lambda: log, ["message: fake"])
|
||||
|
||||
ws.sendMessage(b"to-modify")
|
||||
ws.sendMessage(b"to-block")
|
||||
ws.sendMessage(b"pass-server")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=modified origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=pass-server origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.ws.send('to-respond');
|
||||
window.ws.send('to-modify');
|
||||
window.ws.send('to-block');
|
||||
window.ws.send('pass-client');
|
||||
}"""
|
||||
)
|
||||
assert_equal(
|
||||
lambda: log, ["message: fake", "message: modified", "message: pass-client"]
|
||||
)
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=modified origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=pass-server origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
assert route
|
||||
route.send("another")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=modified origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=pass-server origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=another origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.ws.send('pass-client-2');
|
||||
}"""
|
||||
)
|
||||
assert_equal(
|
||||
lambda: log,
|
||||
[
|
||||
"message: fake",
|
||||
"message: modified",
|
||||
"message: pass-client",
|
||||
"message: pass-client-2",
|
||||
],
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.ws.close(3009, 'problem');
|
||||
}"""
|
||||
)
|
||||
assert_equal(
|
||||
lambda: log,
|
||||
[
|
||||
"message: fake",
|
||||
"message: modified",
|
||||
"message: pass-client",
|
||||
"message: pass-client-2",
|
||||
"close: code=3009 reason=problem",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_without_server(page: Page, server: Server) -> None:
|
||||
route = None
|
||||
|
||||
def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
def _ws_on_message(message: Union[str, bytes]) -> None:
|
||||
if message == "to-respond":
|
||||
ws.send("response")
|
||||
|
||||
ws.on_message(_ws_on_message)
|
||||
nonlocal route
|
||||
route = ws
|
||||
|
||||
page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
setup_ws(page, server, "blob")
|
||||
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
await window.wsOpened;
|
||||
window.ws.send('to-respond');
|
||||
window.ws.send('to-block');
|
||||
window.ws.send('to-respond');
|
||||
}"""
|
||||
)
|
||||
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
assert route
|
||||
route.send("another")
|
||||
# wait for the message to be processed
|
||||
page.wait_for_timeout(100)
|
||||
route.close(code=3008, reason="oops")
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=response origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
f"message: data=another origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
"close code=3008 reason=oops wasClean=true",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_base_url(browser: Browser, server: Server) -> None:
|
||||
context = browser.new_context(base_url=f"http://localhost:{server.PORT}")
|
||||
page = context.new_page()
|
||||
|
||||
def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
ws.on_message(lambda message: ws.send(message))
|
||||
|
||||
page.route_web_socket("/ws", _handle_ws)
|
||||
setup_ws(page, server, "blob")
|
||||
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
await window.wsOpened;
|
||||
window.ws.send('echo');
|
||||
}"""
|
||||
)
|
||||
|
||||
assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=echo origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_work_with_no_trailing_slash(page: Page, server: Server) -> None:
|
||||
log: list[str] = []
|
||||
|
||||
async def handle_ws(ws: WebSocketRoute) -> None:
|
||||
def on_message(message: Union[str, bytes]) -> None:
|
||||
assert isinstance(message, str)
|
||||
log.append(message)
|
||||
ws.send("response")
|
||||
|
||||
ws.on_message(on_message)
|
||||
|
||||
# No trailing slash in the route pattern
|
||||
page.route_web_socket(f"ws://localhost:{server.PORT}", handle_ws)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.evaluate(
|
||||
"""({ port }) => {
|
||||
window.log = [];
|
||||
// No trailing slash in WebSocket URL
|
||||
window.ws = new WebSocket('ws://localhost:' + port);
|
||||
window.ws.addEventListener('message', event => window.log.push(event.data));
|
||||
}""",
|
||||
{"port": server.PORT},
|
||||
)
|
||||
|
||||
assert_equal(lambda: page.evaluate("window.ws.readyState"), 1) # WebSocket.OPEN
|
||||
page.evaluate("window.ws.send('query')")
|
||||
assert_equal(lambda: log, ["query"])
|
||||
assert_equal(lambda: page.evaluate("window.log"), ["response"])
|
||||
@@ -0,0 +1,53 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_expose_screencast_property(page: Page) -> None:
|
||||
assert page.screencast is page.screencast
|
||||
|
||||
|
||||
def test_start_should_deliver_frames_via_callback(page: Page, server: Server) -> None:
|
||||
received: list = []
|
||||
page.screencast.start(on_frame=lambda f: received.append(f["data"]))
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.evaluate("() => document.body.style.backgroundColor = 'red'")
|
||||
# Force a couple of paint cycles so engines that only emit on visual change
|
||||
# still produce a frame. Mirrors upstream `ensureSomeFrames`.
|
||||
for _ in range(3):
|
||||
page.evaluate(
|
||||
"() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))"
|
||||
)
|
||||
page.screenshot()
|
||||
deadline = time.time() + 10
|
||||
while not received and time.time() < deadline:
|
||||
page.wait_for_timeout(100)
|
||||
page.screencast.stop()
|
||||
assert len(received) >= 1
|
||||
assert all(isinstance(d, bytes) and len(d) > 0 for d in received)
|
||||
|
||||
|
||||
def test_starting_twice_should_throw(page: Page) -> None:
|
||||
page.screencast.start(on_frame=lambda f: None)
|
||||
try:
|
||||
with pytest.raises(Exception, match="already started"):
|
||||
page.screencast.start(on_frame=lambda f: None)
|
||||
finally:
|
||||
page.screencast.stop()
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import Page
|
||||
|
||||
|
||||
def test_should_work_with_internal_and(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<div class=foo>hello</div><div class=bar>world</div>
|
||||
<span class=foo>hello2</span><span class=bar>world2</span>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'div >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == []
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'div >> internal:and=".foo"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello"]
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'div >> internal:and=".bar"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["world"]
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'span >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello2", "world2"]
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'.foo >> internal:and="div"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello"]
|
||||
assert (
|
||||
page.eval_on_selector_all(
|
||||
'.bar >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["world2"]
|
||||
@@ -0,0 +1,366 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import multiprocessing
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
Dialog,
|
||||
Error,
|
||||
Page,
|
||||
TimeoutError,
|
||||
sync_playwright,
|
||||
)
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
def test_sync_query_selector(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<h1 id="foo">Bar</h1>
|
||||
"""
|
||||
)
|
||||
e1 = page.query_selector("#foo")
|
||||
assert e1
|
||||
e2 = page.query_selector("h1")
|
||||
assert e2
|
||||
assert e1.inner_text() == e2.inner_text()
|
||||
|
||||
|
||||
def test_page_repr(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert repr(page) == f"<Page url={page.url!r}>"
|
||||
|
||||
|
||||
def test_frame_repr(page: Page, server: Server) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert (
|
||||
repr(page.main_frame)
|
||||
== f"<Frame name={page.main_frame.name} url={page.main_frame.url!r}>"
|
||||
)
|
||||
|
||||
|
||||
def test_browser_context_repr(context: BrowserContext) -> None:
|
||||
assert repr(context) == f"<BrowserContext browser={context.browser}>"
|
||||
|
||||
|
||||
def test_browser_repr(browser: Browser) -> None:
|
||||
assert (
|
||||
repr(browser)
|
||||
== f"<Browser type={browser._impl_obj._browser_type} version={browser.version}>"
|
||||
)
|
||||
|
||||
|
||||
def test_browser_type_repr(browser: Browser) -> None:
|
||||
browser_type = browser._impl_obj._browser_type
|
||||
assert (
|
||||
repr(browser_type)
|
||||
== f"<BrowserType name={browser_type.name} executable_path={browser_type.executable_path}>"
|
||||
)
|
||||
|
||||
|
||||
def test_dialog_repr(page: Page) -> None:
|
||||
def on_dialog(dialog: Dialog) -> None:
|
||||
dialog.accept()
|
||||
assert (
|
||||
repr(dialog)
|
||||
== f"<Dialog type={dialog.type} message={dialog.message} default_value={dialog.default_value}>"
|
||||
)
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
page.evaluate("alert('yo')")
|
||||
|
||||
|
||||
def test_console_repr(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m))
|
||||
page.evaluate('() => console.log("Hello world")')
|
||||
message = messages[0]
|
||||
assert repr(message) == f"<ConsoleMessage type={message.type} text={message.text}>"
|
||||
|
||||
|
||||
def test_sync_click(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<button onclick="window.clicked=true">Bar</button>
|
||||
"""
|
||||
)
|
||||
page.click("text=Bar")
|
||||
assert page.evaluate("()=>window.clicked")
|
||||
|
||||
|
||||
def test_sync_nested_query_selector(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<div id="one">
|
||||
<span class="two">
|
||||
<label>
|
||||
MyValue
|
||||
</label>
|
||||
</span>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
e1 = page.query_selector("#one")
|
||||
assert e1
|
||||
e2 = e1.query_selector(".two")
|
||||
assert e2
|
||||
e3 = e2.query_selector("label")
|
||||
assert e3
|
||||
assert e3.inner_text() == "MyValue"
|
||||
|
||||
|
||||
def test_sync_handle_multiple_pages(context: BrowserContext) -> None:
|
||||
page1 = context.new_page()
|
||||
page2 = context.new_page()
|
||||
assert len(context.pages) == 2
|
||||
page1.set_content("one")
|
||||
page2.set_content("two")
|
||||
assert "one" in page1.content()
|
||||
assert "two" in page2.content()
|
||||
page1.close()
|
||||
assert len(context.pages) == 1
|
||||
page2.close()
|
||||
assert len(context.pages) == 0
|
||||
for page in [page1, page2]:
|
||||
with pytest.raises(Error):
|
||||
page.content()
|
||||
|
||||
|
||||
def test_sync_wait_for_event(page: Page, server: Server) -> None:
|
||||
with page.expect_event("popup", timeout=10000) as popup:
|
||||
page.evaluate("(url) => window.open(url)", server.EMPTY_PAGE)
|
||||
assert popup.value
|
||||
|
||||
|
||||
def test_sync_wait_for_event_raise(page: Page) -> None:
|
||||
with pytest.raises(AssertionError):
|
||||
with page.expect_event("popup", timeout=500):
|
||||
assert False
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
with page.expect_event("popup", timeout=500):
|
||||
page.wait_for_timeout(1_000)
|
||||
assert "Timeout 500ms exceeded" in exc_info.value.message
|
||||
|
||||
|
||||
def test_sync_make_existing_page_sync(page: Page) -> None:
|
||||
page = page
|
||||
assert page.evaluate("() => ({'playwright': true})") == {"playwright": True}
|
||||
page.set_content("<h1>myElement</h1>")
|
||||
page.wait_for_selector("text=myElement")
|
||||
|
||||
|
||||
def test_sync_network_events(page: Page, server: Server) -> None:
|
||||
server.set_route(
|
||||
"/hello-world",
|
||||
lambda request: (
|
||||
request.setHeader("Content-Type", "text/plain"),
|
||||
request.write(b"Hello world"),
|
||||
request.finish(),
|
||||
),
|
||||
)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
messages = []
|
||||
page.on(
|
||||
"request", lambda request: messages.append(f">>{request.method}{request.url}")
|
||||
)
|
||||
page.on(
|
||||
"response",
|
||||
lambda response: messages.append(f"<<{response.status}{response.url}"),
|
||||
)
|
||||
response = page.evaluate("""async ()=> (await fetch("/hello-world")).text()""")
|
||||
assert response == "Hello world"
|
||||
assert messages == [
|
||||
f">>GET{server.PREFIX}/hello-world",
|
||||
f"<<200{server.PREFIX}/hello-world",
|
||||
]
|
||||
|
||||
|
||||
def test_console_should_work(page: Page, browser_name: str) -> None:
|
||||
messages = []
|
||||
page.once("console", lambda m: messages.append(m))
|
||||
page.evaluate('() => console.log("hello", 5, {foo: "bar"})')
|
||||
assert len(messages) == 1
|
||||
message = messages[0]
|
||||
if browser_name != "firefox":
|
||||
assert message.text == "hello 5 {foo: bar}"
|
||||
assert str(message) == "hello 5 {foo: bar}"
|
||||
else:
|
||||
assert message.text == "hello 5 JSHandle@object"
|
||||
assert str(message) == "hello 5 JSHandle@object"
|
||||
assert message.type == "log"
|
||||
assert message.args[0].json_value() == "hello"
|
||||
assert message.args[1].json_value() == 5
|
||||
assert message.args[2].json_value() == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_sync_download(browser: Browser, server: Server) -> None:
|
||||
server.set_route(
|
||||
"/downloadWithFilename",
|
||||
lambda request: (
|
||||
request.setHeader("Content-Type", "application/octet-stream"),
|
||||
request.setHeader("Content-Disposition", "attachment; filename=file.txt"),
|
||||
request.write(b"Hello world"),
|
||||
request.finish(),
|
||||
),
|
||||
)
|
||||
page = browser.new_page(accept_downloads=True)
|
||||
page.set_content(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')
|
||||
|
||||
with page.expect_event("download") as download:
|
||||
page.click("a")
|
||||
assert download.value
|
||||
assert download.value.suggested_filename == "file.txt"
|
||||
path = download.value.path()
|
||||
assert os.path.isfile(path)
|
||||
with open(path, "r") as fd:
|
||||
assert fd.read() == "Hello world"
|
||||
page.close()
|
||||
|
||||
|
||||
def test_sync_workers_page_workers(page: Page, server: Server) -> None:
|
||||
with page.expect_event("worker") as event_worker:
|
||||
page.goto(server.PREFIX + "/worker/worker.html")
|
||||
assert event_worker.value
|
||||
worker = page.workers[0]
|
||||
assert "worker.js" in worker.url
|
||||
|
||||
assert worker.evaluate('() => self["workerFunction"]()') == "worker function result"
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert len(page.workers) == 0
|
||||
|
||||
|
||||
def test_sync_playwright_multiple_times() -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
with sync_playwright() as pw:
|
||||
assert pw.chromium
|
||||
assert (
|
||||
"It looks like you are using Playwright Sync API inside the asyncio loop."
|
||||
in exc.value.message
|
||||
)
|
||||
|
||||
|
||||
def test_sync_set_default_timeout(page: Page) -> None:
|
||||
page.set_default_timeout(1)
|
||||
with pytest.raises(TimeoutError) as exc:
|
||||
page.wait_for_function("false")
|
||||
assert "Timeout 1ms exceeded." in exc.value.message
|
||||
|
||||
|
||||
def test_close_should_reject_all_promises(
|
||||
context: BrowserContext, sync_gather: Callable
|
||||
) -> None:
|
||||
new_page = context.new_page()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
sync_gather(
|
||||
lambda: new_page.evaluate("() => new Promise(r => {})"),
|
||||
lambda: new_page.close(),
|
||||
)
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc_info.value.message
|
||||
|
||||
|
||||
def test_expect_response_should_work(page: Page, server: Server) -> None:
|
||||
with page.expect_response("**/*") as resp:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert resp.value
|
||||
assert resp.value.url == server.EMPTY_PAGE
|
||||
assert resp.value.status == 200
|
||||
assert resp.value.ok
|
||||
assert resp.value.request
|
||||
|
||||
|
||||
def test_expect_response_should_not_hang_when_predicate_throws(page: Page) -> None:
|
||||
with pytest.raises(Exception, match="Oops!"):
|
||||
with page.expect_response("**/*"):
|
||||
raise Exception("Oops!")
|
||||
|
||||
|
||||
def test_expect_response_should_use_context_timeout(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
context.set_default_timeout(1_000)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
with page.expect_response("https://playwright.dev"):
|
||||
pass
|
||||
assert exc_info.type is TimeoutError
|
||||
assert "Timeout 1000ms exceeded" in exc_info.value.message
|
||||
|
||||
|
||||
def _test_sync_playwright_stop_multiple_times() -> None:
|
||||
playwright = sync_playwright().start()
|
||||
playwright.stop()
|
||||
playwright.stop()
|
||||
|
||||
|
||||
def test_sync_playwright_stop_multiple_times() -> None:
|
||||
p = multiprocessing.Process(target=_test_sync_playwright_stop_multiple_times)
|
||||
p.start()
|
||||
p.join()
|
||||
assert p.exitcode == 0
|
||||
|
||||
|
||||
def _test_call_sync_method_after_playwright_close_with_own_loop(
|
||||
browser_name: str,
|
||||
launch_arguments: Dict[str, Any],
|
||||
empty_page: str,
|
||||
) -> None:
|
||||
playwright = sync_playwright().start()
|
||||
browser = playwright[browser_name].launch(**launch_arguments)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto(empty_page)
|
||||
playwright.stop()
|
||||
with pytest.raises(Error) as exc:
|
||||
page.evaluate("1+1")
|
||||
assert "Event loop is closed! Is Playwright already stopped?" in str(exc.value)
|
||||
|
||||
|
||||
def test_call_sync_method_after_playwright_close_with_own_loop(
|
||||
server: Server, browser_name: str, launch_arguments: Dict[str, Any]
|
||||
) -> None:
|
||||
p = multiprocessing.Process(
|
||||
target=_test_call_sync_method_after_playwright_close_with_own_loop,
|
||||
args=[browser_name, launch_arguments, server.EMPTY_PAGE],
|
||||
)
|
||||
p.start()
|
||||
p.join()
|
||||
assert p.exitcode == 0
|
||||
|
||||
|
||||
def test_should_return_proper_api_name_on_error(page: Page) -> None:
|
||||
try:
|
||||
page.evaluate("does_not_exist")
|
||||
|
||||
assert (
|
||||
False
|
||||
), "Accessing undefined JavaScript variable should have thrown exception"
|
||||
except Exception as error:
|
||||
# Each browser returns slightly different error messages, but they should all start with "Page.evaluate:", because that was the Playwright method where the error originated
|
||||
assert str(error).startswith("Page.evaluate:")
|
||||
|
||||
|
||||
def test_click_should_accept_timedelta_for_timeout(page: Page) -> None:
|
||||
with pytest.raises(TimeoutError, match="Timeout 1ms exceeded"):
|
||||
page.click("does-not-exist", timeout=timedelta(milliseconds=1))
|
||||
@@ -0,0 +1,113 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Generator, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, BrowserContext, ElementHandle, JSHandle, Page
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def context(browser: Browser) -> Generator[BrowserContext, None, None]:
|
||||
context = browser.new_context(has_touch=True)
|
||||
yield context
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_send_all_of_the_correct_events(page: Page) -> None:
|
||||
page.set_content(
|
||||
"""
|
||||
<div id="a" style="background: lightblue; width: 50px; height: 50px">a</div>
|
||||
<div id="b" style="background: pink; width: 50px; height: 50px">b</div>
|
||||
"""
|
||||
)
|
||||
page.tap("#a")
|
||||
element_handle = track_events(page.query_selector("#b"))
|
||||
page.tap("#b")
|
||||
assert element_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
"mouseover",
|
||||
"mouseenter",
|
||||
"mousemove",
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"click",
|
||||
]
|
||||
|
||||
|
||||
def test_should_not_send_mouse_events_touchstart_is_canceled(page: Page) -> None:
|
||||
page.set_content("hello world")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
// touchstart is not cancelable unless passive is false
|
||||
document.addEventListener('touchstart', t => t.preventDefault(), {passive: false});
|
||||
}"""
|
||||
)
|
||||
events_handle = track_events(page.query_selector("body"))
|
||||
page.tap("body")
|
||||
assert events_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
]
|
||||
|
||||
|
||||
def test_should_not_send_mouse_events_touchend_is_canceled(page: Page) -> None:
|
||||
page.set_content("hello world")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
// touchstart is not cancelable unless passive is false
|
||||
document.addEventListener('touchend', t => t.preventDefault());
|
||||
}"""
|
||||
)
|
||||
events_handle = track_events(page.query_selector("body"))
|
||||
page.tap("body")
|
||||
assert events_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
]
|
||||
|
||||
|
||||
def track_events(target: Optional[ElementHandle]) -> JSHandle:
|
||||
assert target
|
||||
return target.evaluate_handle(
|
||||
"""target => {
|
||||
const events = [];
|
||||
for (const event of [
|
||||
'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'click',
|
||||
'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave', 'pointermove', 'pointerout', 'pointerover', 'pointerup',
|
||||
'touchstart', 'touchend', 'touchmove', 'touchcancel',])
|
||||
target.addEventListener(event, () => events.push(event), false);
|
||||
return events;
|
||||
}"""
|
||||
)
|
||||
@@ -0,0 +1,443 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Callable, ContextManager
|
||||
|
||||
from playwright.sync_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
BrowserType,
|
||||
Page,
|
||||
Playwright,
|
||||
Response,
|
||||
expect,
|
||||
)
|
||||
from tests.server import Server
|
||||
|
||||
from .conftest import TraceViewerPage
|
||||
|
||||
|
||||
def test_browser_context_output_trace(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = browser.new_context()
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
context.tracing.stop(path=tmp_path / "trace.zip")
|
||||
assert Path(tmp_path / "trace.zip").exists()
|
||||
context.close()
|
||||
|
||||
|
||||
def test_start_stop(browser: Browser) -> None:
|
||||
context = browser.new_context()
|
||||
context.tracing.start()
|
||||
context.tracing.stop()
|
||||
context.close()
|
||||
|
||||
|
||||
def test_browser_context_should_not_throw_when_stopping_without_start_but_not_exporting(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
context.tracing.stop()
|
||||
|
||||
|
||||
def test_browser_context_output_trace_chunk(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = browser.new_context()
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
button = page.locator(".box").first
|
||||
|
||||
context.tracing.start_chunk(title="foo")
|
||||
button.click()
|
||||
context.tracing.stop_chunk(path=tmp_path / "trace1.zip")
|
||||
assert Path(tmp_path / "trace1.zip").exists()
|
||||
|
||||
context.tracing.start_chunk(title="foo")
|
||||
button.click()
|
||||
context.tracing.stop_chunk(path=tmp_path / "trace2.zip")
|
||||
assert Path(tmp_path / "trace2.zip").exists()
|
||||
context.close()
|
||||
|
||||
|
||||
def test_should_collect_sources(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start(sources=True)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.set_content("<button>Click</button>")
|
||||
|
||||
def my_method_outer() -> None:
|
||||
def my_method_inner() -> None:
|
||||
page.get_by_text("Click").click()
|
||||
|
||||
my_method_inner()
|
||||
|
||||
my_method_outer()
|
||||
path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=path)
|
||||
|
||||
with show_trace_viewer(path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
]
|
||||
)
|
||||
trace_viewer.show_source_tab()
|
||||
# Check that stack frames are shown (they might be anonymous in Python)
|
||||
expect(trace_viewer.stack_frames).to_contain_text(
|
||||
[
|
||||
re.compile(r"my_method_inner"),
|
||||
re.compile(r"my_method_outer"),
|
||||
re.compile(r"test_should_collect_sources"),
|
||||
]
|
||||
)
|
||||
|
||||
trace_viewer.select_action("Set content")
|
||||
# Check that the source file is shown
|
||||
expect(trace_viewer.page.locator(".source-tab-file-name")).to_have_attribute(
|
||||
"title", re.compile(r".*test_.*\.py")
|
||||
)
|
||||
expect(trace_viewer.page.locator(".source-line-running")).to_contain_text(
|
||||
'page.set_content("<button>Click</button>")'
|
||||
)
|
||||
|
||||
|
||||
def test_should_collect_trace_with_resources_but_no_js(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page.goto(server.PREFIX + "/frames/frame.html")
|
||||
page.set_content("<button>Click</button>")
|
||||
page.click('"Click"')
|
||||
page.mouse.move(20, 20)
|
||||
page.mouse.dblclick(30, 30)
|
||||
page.request.get(server.EMPTY_PAGE)
|
||||
page.keyboard.insert_text("abc")
|
||||
page.wait_for_timeout(2000) # Give it some time to produce screenshots.
|
||||
page.route("**/empty.html", lambda route: route.continue_())
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
page.close()
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=trace_file_path)
|
||||
|
||||
with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/frames/frame\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
re.compile(r"Mouse move"),
|
||||
re.compile(r"Double click"),
|
||||
re.compile(r"GET \"/empty\.html\""),
|
||||
re.compile(r'Insert "abc"'),
|
||||
re.compile(r"Wait for timeout"),
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r'Navigate to "/one-style\.html"'),
|
||||
re.compile(r"Close"),
|
||||
]
|
||||
)
|
||||
|
||||
trace_viewer.select_action("Set content")
|
||||
expect(trace_viewer.page.locator(".browser-frame-address-bar")).to_have_text(
|
||||
server.PREFIX + "/frames/frame.html"
|
||||
)
|
||||
frame = trace_viewer.snapshot_frame("Set content", 0, False)
|
||||
expect(frame.locator("button")).to_have_text("Click")
|
||||
|
||||
|
||||
def test_should_correctly_determine_sync_apiname(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable,
|
||||
) -> None:
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
|
||||
received_response = threading.Event()
|
||||
|
||||
def _handle_response(response: Response) -> None:
|
||||
response.request.all_headers()
|
||||
response.text()
|
||||
received_response.set()
|
||||
|
||||
page.once("response", _handle_response)
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
received_response.wait()
|
||||
|
||||
page.close()
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=trace_file_path)
|
||||
|
||||
with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/grid\.html"'),
|
||||
re.compile(r"Close"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_should_collect_two_traces(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.set_content("<button>Click</button>")
|
||||
page.click('"Click"')
|
||||
tracing1_path = tmp_path / "trace1.zip"
|
||||
context.tracing.stop(path=tracing1_path)
|
||||
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page.dblclick('"Click"')
|
||||
page.close()
|
||||
tracing2_path = tmp_path / "trace2.zip"
|
||||
context.tracing.stop(path=tracing2_path)
|
||||
|
||||
with show_trace_viewer(tracing1_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
]
|
||||
)
|
||||
|
||||
with show_trace_viewer(tracing2_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r"Double click"),
|
||||
re.compile(r"Close"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_should_work_with_playwright_context_managers(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.set_content("<button>Click</button>")
|
||||
with page.expect_console_message() as message_info:
|
||||
page.evaluate('() => console.log("hello")')
|
||||
page.click('"Click"')
|
||||
assert (message_info.value).text == "hello"
|
||||
|
||||
with page.expect_popup():
|
||||
page.evaluate("window._popup = window.open(document.location.href)")
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=trace_file_path)
|
||||
|
||||
with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r'Wait for event "page\.expect_event\(console\)"'),
|
||||
re.compile(r"Evaluate"),
|
||||
re.compile(r"Click"),
|
||||
re.compile(r'Wait for event "page\.expect_event\(popup\)"'),
|
||||
re.compile(r"Evaluate"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_should_display_wait_for_load_state_even_if_did_not_wait_for_it(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start(screenshots=True, snapshots=True)
|
||||
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
page.wait_for_load_state("load")
|
||||
page.wait_for_load_state("load")
|
||||
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=trace_file_path)
|
||||
|
||||
with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r'Wait for event "frame\.wait_for_load_state"'),
|
||||
re.compile(r'Wait for event "frame\.wait_for_load_state"'),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_should_respect_traces_dir_and_name(
|
||||
browser_type: BrowserType,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
launch_arguments: dict,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
traces_dir = tmp_path / "traces"
|
||||
browser = browser_type.launch(traces_dir=traces_dir, **launch_arguments)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
|
||||
context.tracing.start(name="name1", snapshots=True)
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
context.tracing.stop_chunk(path=tmp_path / "trace1.zip")
|
||||
assert (traces_dir / "name1.trace").exists()
|
||||
assert (traces_dir / "name1.network").exists()
|
||||
|
||||
context.tracing.start_chunk(name="name2")
|
||||
page.goto(server.PREFIX + "/har.html")
|
||||
context.tracing.stop(path=tmp_path / "trace2.zip")
|
||||
assert (traces_dir / "name2.trace").exists()
|
||||
assert (traces_dir / "name2.network").exists()
|
||||
|
||||
browser.close()
|
||||
|
||||
with show_trace_viewer(tmp_path / "trace1.zip") as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/one-style\.html"'),
|
||||
]
|
||||
)
|
||||
frame = trace_viewer.snapshot_frame('Navigate to "/one-style.html"', 0, False)
|
||||
expect(frame.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
expect(frame.locator("body")).to_have_text("hello, world!")
|
||||
|
||||
with show_trace_viewer(tmp_path / "trace2.zip") as trace_viewer:
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/har\.html"'),
|
||||
]
|
||||
)
|
||||
frame = trace_viewer.snapshot_frame('Navigate to "/har.html"', 0, False)
|
||||
expect(frame.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
expect(frame.locator("body")).to_have_text("hello, world!")
|
||||
|
||||
|
||||
def test_should_show_tracing_group_in_action_list(
|
||||
context: BrowserContext,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
context.tracing.start()
|
||||
page = context.new_page()
|
||||
|
||||
context.tracing.group("outer group")
|
||||
page.goto("data:text/html,<!DOCTYPE html><body><div>Hello world</div></body>")
|
||||
context.tracing.group("inner group 1")
|
||||
page.locator("body").click()
|
||||
context.tracing.group_end()
|
||||
context.tracing.group("inner group 2")
|
||||
page.get_by_text("Hello").is_visible()
|
||||
context.tracing.group_end()
|
||||
context.tracing.group_end()
|
||||
|
||||
trace_path = tmp_path / "trace.zip"
|
||||
context.tracing.stop(path=trace_path)
|
||||
|
||||
with show_trace_viewer(trace_path) as trace_viewer:
|
||||
trace_viewer.expand_action("inner group 1")
|
||||
expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r"Create page"),
|
||||
re.compile(r"outer group"),
|
||||
re.compile(r"Navigate to \"data:\""),
|
||||
re.compile(r"inner group 1"),
|
||||
re.compile(r"Click"),
|
||||
re.compile(r"inner group 2"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_should_start_and_stop_har(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
har_path = tmp_path / "test.har"
|
||||
context.tracing.start_har(path=har_path, content="embed", mode="full")
|
||||
page.goto(server.PREFIX + "/empty.html")
|
||||
context.tracing.stop_har()
|
||||
context.close()
|
||||
assert har_path.exists()
|
||||
assert har_path.stat().st_size > 0
|
||||
|
||||
|
||||
def test_should_record_a_har_with_options(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = browser.new_context()
|
||||
har_path = tmp_path / "tracing.har"
|
||||
context.tracing.start_har(
|
||||
path=har_path, mode="minimal", url_filter="**/one-style.css"
|
||||
)
|
||||
page = context.new_page()
|
||||
page.goto(server.PREFIX + "/one-style.html")
|
||||
context.tracing.stop_har()
|
||||
context.close()
|
||||
|
||||
log = json.loads(har_path.read_text())["log"]
|
||||
urls = [e["request"]["url"] for e in log["entries"]]
|
||||
assert urls == [server.PREFIX + "/one-style.css"]
|
||||
assert log["entries"][0]["request"]["bodySize"] == -1
|
||||
|
||||
|
||||
def test_should_record_a_zipped_har_for_apirequestcontext(
|
||||
playwright: Playwright, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
request = playwright.request.new_context()
|
||||
har_path = tmp_path / "tracing.har.zip"
|
||||
request.tracing.start_har(path=har_path, content="attach")
|
||||
request.get(server.PREFIX + "/simple.json")
|
||||
request.tracing.stop_har()
|
||||
request.dispose()
|
||||
|
||||
with zipfile.ZipFile(har_path) as zf:
|
||||
log = json.loads(zf.read("har.har"))["log"]
|
||||
assert any(
|
||||
e["request"]["url"] == server.PREFIX + "/simple.json" for e in log["entries"]
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from playwright.sync_api import BrowserContext, Page, Route
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
def test_context_unroute_all_removes_all_handlers(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
context.route(
|
||||
"**/*",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
context.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
context.unroute_all()
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
def test_page_unroute_all_removes_all_routes(page: Page, server: Server) -> None:
|
||||
page.route(
|
||||
"**/*",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
page.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
page.unroute_all()
|
||||
response = must(page.goto(server.EMPTY_PAGE))
|
||||
assert response.ok
|
||||
|
||||
|
||||
def test_page_route_returns_disposable(page: Page, server: Server) -> None:
|
||||
intercepted: list = []
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
intercepted.append(route.request.url)
|
||||
route.continue_()
|
||||
|
||||
with page.route("**/*", handler):
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert any(server.EMPTY_PAGE in url for url in intercepted)
|
||||
intercepted.clear()
|
||||
page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == []
|
||||
@@ -0,0 +1,115 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.sync_api import Browser, BrowserType, Error
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
def test_should_expose_video_path(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = browser.new_page(
|
||||
record_video_dir=tmp_path, record_video_size={"width": 100, "height": 200}
|
||||
)
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
video = page.video
|
||||
assert video
|
||||
path = video.path()
|
||||
assert repr(page.video) == f"<Video page={page}>"
|
||||
assert str(tmp_path) in str(path)
|
||||
page.wait_for_timeout(1000)
|
||||
page.context.close()
|
||||
|
||||
|
||||
def test_video_should_exist(browser: Browser, tmp_path: Path, server: Server) -> None:
|
||||
page = browser.new_page(record_video_dir=tmp_path)
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
video = page.video
|
||||
assert video
|
||||
path = video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
page.wait_for_timeout(1000)
|
||||
page.context.close()
|
||||
assert os.path.exists(path)
|
||||
|
||||
|
||||
def test_record_video_to_path(browser: Browser, tmp_path: Path, server: Server) -> None:
|
||||
page = browser.new_page(record_video_dir=tmp_path)
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
video = page.video
|
||||
assert video
|
||||
path = video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
page.wait_for_timeout(1000)
|
||||
page.context.close()
|
||||
assert os.path.exists(path)
|
||||
|
||||
|
||||
def test_record_video_to_path_persistent(
|
||||
browser_type: BrowserType, tmp_path: Path, server: Server, launch_arguments: Dict
|
||||
) -> None:
|
||||
context = browser_type.launch_persistent_context(
|
||||
tmp_path, **launch_arguments, record_video_dir=tmp_path
|
||||
)
|
||||
page = context.pages[0]
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
video = page.video
|
||||
assert video
|
||||
path = video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
page.wait_for_timeout(1000)
|
||||
context.close()
|
||||
assert os.path.exists(path)
|
||||
|
||||
|
||||
def test_record_video_can_get_video_path_immediately(
|
||||
browser_type: BrowserType, tmp_path: Path, launch_arguments: Dict
|
||||
) -> None:
|
||||
context = browser_type.launch_persistent_context(
|
||||
tmp_path, **launch_arguments, record_video_dir=tmp_path
|
||||
)
|
||||
page = context.pages[0]
|
||||
video = page.video
|
||||
assert video
|
||||
path = video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
page.wait_for_timeout(1000)
|
||||
context.close()
|
||||
assert os.path.exists(path)
|
||||
|
||||
|
||||
def test_should_error_if_page_not_closed_before_save_as(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = browser.new_page(record_video_dir=tmp_path)
|
||||
page.goto(server.PREFIX + "/grid.html")
|
||||
page.wait_for_timeout(1000) # Give it some time to record.
|
||||
out_path = tmp_path / "some-video.webm"
|
||||
with pytest.raises(Error) as err:
|
||||
video = page.video
|
||||
assert video
|
||||
video.save_as(out_path)
|
||||
assert video
|
||||
assert "Page is not yet closed. Close the page prior to calling save_as" in str(err)
|
||||
assert not os.path.exists(out_path)
|
||||
page.close()
|
||||
|
||||
video.save_as(out_path)
|
||||
assert os.path.exists(out_path)
|
||||
@@ -0,0 +1,74 @@
|
||||
# Copyright (c) Microsoft Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import re
|
||||
from typing import Any, List, cast
|
||||
|
||||
from playwright.sync_api import Error, Frame, Page, Selectors, ViewportSize
|
||||
|
||||
|
||||
class Utils:
|
||||
def attach_frame(self, page: Page, frame_id: str, url: str) -> Frame:
|
||||
handle = page.evaluate_handle(
|
||||
"""async ({ frame_id, url }) => {
|
||||
const frame = document.createElement('iframe');
|
||||
frame.src = url;
|
||||
frame.id = frame_id;
|
||||
document.body.appendChild(frame);
|
||||
await new Promise(x => frame.onload = x);
|
||||
return frame;
|
||||
}""",
|
||||
{"frame_id": frame_id, "url": url},
|
||||
)
|
||||
element_handle = handle.as_element()
|
||||
assert element_handle
|
||||
frame = element_handle.content_frame()
|
||||
assert frame
|
||||
return frame
|
||||
|
||||
def detach_frame(self, page: Page, frame_id: str) -> None:
|
||||
page.evaluate(
|
||||
"frame_id => document.getElementById(frame_id).remove()", frame_id
|
||||
)
|
||||
|
||||
def dump_frames(self, frame: Frame, indentation: str = "") -> List[str]:
|
||||
indentation = indentation or ""
|
||||
description = re.sub(r":\d+/", ":<PORT>/", frame.url)
|
||||
if frame.name:
|
||||
description += " (" + frame.name + ")"
|
||||
result = [indentation + description]
|
||||
sorted_frames = sorted(
|
||||
frame.child_frames, key=lambda frame: frame.url + frame.name
|
||||
)
|
||||
for child in sorted_frames:
|
||||
result = result + utils.dump_frames(child, " " + indentation)
|
||||
return result
|
||||
|
||||
def verify_viewport(self, page: Page, width: int, height: int) -> None:
|
||||
assert cast(ViewportSize, page.viewport_size)["width"] == width
|
||||
assert cast(ViewportSize, page.viewport_size)["height"] == height
|
||||
assert page.evaluate("window.innerWidth") == width
|
||||
assert page.evaluate("window.innerHeight") == height
|
||||
|
||||
def register_selector_engine(
|
||||
self, selectors: Selectors, *args: Any, **kwargs: Any
|
||||
) -> None:
|
||||
try:
|
||||
selectors.register(*args, **kwargs)
|
||||
except Error as exc:
|
||||
if "has been already registered" not in exc.message:
|
||||
raise exc
|
||||
|
||||
|
||||
utils = Utils()
|
||||
Reference in New Issue
Block a user