同步完整源码 - 2026-05-24
This commit is contained in:
@@ -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 asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, Generator
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright._impl._driver import compute_driver_executable
|
||||
from playwright.async_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
BrowserType,
|
||||
FrameLocator,
|
||||
Locator,
|
||||
Page,
|
||||
Playwright,
|
||||
Selectors,
|
||||
async_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")
|
||||
async def playwright() -> AsyncGenerator[Playwright, None]:
|
||||
async with async_playwright() as playwright_object:
|
||||
yield playwright_object
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def browser_type(playwright: Playwright, browser_name: str) -> BrowserType:
|
||||
if browser_name == "chromium":
|
||||
return playwright.chromium
|
||||
if browser_name == "firefox":
|
||||
return playwright.firefox
|
||||
if browser_name == "webkit":
|
||||
return playwright.webkit
|
||||
raise Exception(f"Invalid browser_name: {browser_name}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def browser_factory(
|
||||
launch_arguments: Dict, browser_type: BrowserType
|
||||
) -> AsyncGenerator[Callable[..., Awaitable[Browser]], None]:
|
||||
browsers = []
|
||||
|
||||
async def launch(**kwargs: Any) -> Browser:
|
||||
browser = await browser_type.launch(**launch_arguments, **kwargs)
|
||||
browsers.append(browser)
|
||||
return browser
|
||||
|
||||
yield launch
|
||||
for browser in browsers:
|
||||
await browser.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def browser(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]",
|
||||
) -> AsyncGenerator[Browser, None]:
|
||||
browser = await browser_factory()
|
||||
yield browser
|
||||
await browser.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def browser_version(browser: Browser) -> str:
|
||||
return browser.version
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def context_factory(
|
||||
browser: Browser,
|
||||
) -> AsyncGenerator["Callable[..., Awaitable[BrowserContext]]", None]:
|
||||
contexts = []
|
||||
|
||||
async def launch(**kwargs: Any) -> BrowserContext:
|
||||
context = await browser.new_context(**kwargs)
|
||||
contexts.append(context)
|
||||
return context
|
||||
|
||||
yield launch
|
||||
for context in contexts:
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def default_same_site_cookie_value(browser_name: str, is_linux: bool) -> str:
|
||||
if browser_name == "chromium":
|
||||
return "Lax"
|
||||
if browser_name == "firefox":
|
||||
return "None"
|
||||
if browser_name == "webkit" and is_linux:
|
||||
return "Lax"
|
||||
if browser_name == "webkit" and not is_linux:
|
||||
return "None"
|
||||
raise Exception(f"Invalid browser_name: {browser_name}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def context(
|
||||
context_factory: "Callable[..., asyncio.Future[BrowserContext]]",
|
||||
) -> AsyncGenerator[BrowserContext, None]:
|
||||
context = await context_factory()
|
||||
yield context
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def page(context: BrowserContext) -> AsyncGenerator[Page, None]:
|
||||
page = await context.new_page()
|
||||
yield page
|
||||
await page.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def selectors(playwright: Playwright) -> Selectors:
|
||||
return playwright.selectors
|
||||
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
async def select_action(self, title: str, ordinal: int = 0) -> None:
|
||||
await self.page.locator(".action-title", has_text=title).nth(ordinal).click()
|
||||
|
||||
async def select_snapshot(self, name: str) -> None:
|
||||
await self.page.click(
|
||||
f'.snapshot-tab .tabbed-pane-tab-label:has-text("{name}")'
|
||||
)
|
||||
|
||||
async def snapshot_frame(
|
||||
self, action_name: str, ordinal: int = 0, has_subframe: bool = False
|
||||
) -> FrameLocator:
|
||||
await self.select_action(action_name, ordinal)
|
||||
expected_frames = 4 if has_subframe else 3
|
||||
while len(self.page.frames) < expected_frames:
|
||||
await self.page.wait_for_event("frameattached")
|
||||
return self.page.frame_locator("iframe.snapshot-visible[name=snapshot]")
|
||||
|
||||
async def show_source_tab(self) -> None:
|
||||
await self.page.click("text='Source'")
|
||||
|
||||
async def expand_action(self, title: str, ordinal: int = 0) -> None:
|
||||
await self.actions_tree.locator(".tree-view-entry", has_text=title).nth(
|
||||
ordinal
|
||||
).locator(".codicon-chevron-right").click()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def show_trace_viewer(browser: Browser) -> AsyncGenerator[Callable, None]:
|
||||
"""Fixture that provides a function to show trace viewer for a trace file."""
|
||||
|
||||
@asynccontextmanager
|
||||
async def _show_trace_viewer(
|
||||
trace_path: Path,
|
||||
) -> AsyncGenerator[TraceViewerPage, 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 = await browser.new_page()
|
||||
|
||||
try:
|
||||
await page.goto(
|
||||
f"{server.PREFIX}/index.html?trace={server.PREFIX}/trace.zip"
|
||||
)
|
||||
yield TraceViewerPage(page)
|
||||
finally:
|
||||
await page.close()
|
||||
server.stop()
|
||||
|
||||
yield _show_trace_viewer
|
||||
@@ -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 Optional
|
||||
|
||||
from playwright.async_api import BrowserContext, Error, Page
|
||||
|
||||
|
||||
async def test_add_init_script_evaluate_before_anything_else_on_the_page(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.add_init_script("window.injected = 123")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_work_with_a_path(page: Page, assetdir: Path) -> None:
|
||||
await page.add_init_script(path=assetdir / "injectedfile.js")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_work_with_content(page: Page) -> None:
|
||||
await page.add_init_script("window.injected = 123")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_throw_without_path_and_content(page: Page) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.add_init_script({"foo": "bar"}) # type: ignore
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert error.message == "Either path or script parameter must be specified"
|
||||
|
||||
|
||||
async def test_add_init_script_work_with_browser_context_scripts(
|
||||
page: Page, context: BrowserContext
|
||||
) -> None:
|
||||
await context.add_init_script("window.temp = 123")
|
||||
page = await context.new_page()
|
||||
await page.add_init_script("window.injected = window.temp")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_work_with_browser_context_scripts_with_a_path(
|
||||
page: Page, context: BrowserContext, assetdir: Path
|
||||
) -> None:
|
||||
await context.add_init_script(path=assetdir / "injectedfile.js")
|
||||
page = await context.new_page()
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_work_with_browser_context_scripts_for_already_created_pages(
|
||||
page: Page, context: BrowserContext
|
||||
) -> None:
|
||||
await context.add_init_script("window.temp = 123")
|
||||
await page.add_init_script("window.injected = window.temp")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") == 123
|
||||
|
||||
|
||||
async def test_add_init_script_support_multiple_scripts(page: Page) -> None:
|
||||
await page.add_init_script("window.script1 = 1")
|
||||
await page.add_init_script("window.script2 = 2")
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.script1") == 1
|
||||
assert await page.evaluate("window.script2") == 2
|
||||
|
||||
|
||||
async def test_should_work_with_trailing_comments(page: Page) -> None:
|
||||
await page.add_init_script("// comment")
|
||||
await page.add_init_script("window.secret = 42;")
|
||||
await page.goto("data:text/html,<html></html>")
|
||||
assert await page.evaluate("secret") == 42
|
||||
|
||||
|
||||
async def test_add_init_script_returns_disposable(page: Page) -> None:
|
||||
async with await page.add_init_script("window.injected = 123"):
|
||||
await page.goto(
|
||||
"data:text/html,<script>window.result = window.injected</script>"
|
||||
)
|
||||
assert await page.evaluate("window.result") == 123
|
||||
await page.goto("data:text/html,<script>window.result = window.injected</script>")
|
||||
assert await page.evaluate("window.result") is None
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
# 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
|
||||
import gc
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Page, async_playwright
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
async def test_should_cancel_underlying_protocol_calls(
|
||||
browser_name: str, launch_arguments: Dict
|
||||
) -> None:
|
||||
handler_exception = None
|
||||
|
||||
def exception_handlerdler(loop: asyncio.AbstractEventLoop, context: Dict) -> None:
|
||||
nonlocal handler_exception
|
||||
handler_exception = context["exception"]
|
||||
|
||||
asyncio.get_running_loop().set_exception_handler(exception_handlerdler)
|
||||
|
||||
async with async_playwright() as p:
|
||||
browser = await p[browser_name].launch(**launch_arguments)
|
||||
page = await browser.new_page()
|
||||
task = asyncio.create_task(page.wait_for_selector("will-never-find"))
|
||||
# make sure that the wait_for_selector message was sent to the server (driver)
|
||||
await asyncio.sleep(0.1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
await browser.close()
|
||||
|
||||
# The actual 'Future exception was never retrieved' is logged inside the Future destructor (__del__).
|
||||
gc.collect()
|
||||
|
||||
assert handler_exception is None
|
||||
|
||||
asyncio.get_running_loop().set_exception_handler(None)
|
||||
|
||||
|
||||
async def test_async_playwright_stop_multiple_times() -> None:
|
||||
playwright = await async_playwright().start()
|
||||
await playwright.stop()
|
||||
await playwright.stop()
|
||||
|
||||
|
||||
async def test_cancel_pending_protocol_call_on_playwright_stop(server: Server) -> None:
|
||||
server.set_route("/hang", lambda _: None)
|
||||
playwright = await async_playwright().start()
|
||||
api_request_context = await playwright.request.new_context()
|
||||
pending_task = asyncio.create_task(api_request_context.get(server.PREFIX + "/hang"))
|
||||
await playwright.stop()
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await pending_task
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in str(exc_info.value)
|
||||
|
||||
|
||||
async def test_should_not_throw_with_taskgroup(page: Page) -> None:
|
||||
if sys.version_info < (3, 11):
|
||||
pytest.skip("TaskGroup is only available in Python 3.11+")
|
||||
|
||||
from builtins import ExceptionGroup # type: ignore
|
||||
|
||||
async def raise_exception() -> None:
|
||||
raise ValueError("Something went wrong")
|
||||
|
||||
with pytest.raises(ExceptionGroup) as exc_info:
|
||||
async with asyncio.TaskGroup() as group: # type: ignore
|
||||
group.create_task(page.locator(".this-element-does-not-exist").inner_text())
|
||||
group.create_task(raise_exception())
|
||||
assert len(exc_info.value.exceptions) == 1
|
||||
assert "Something went wrong" in str(exc_info.value.exceptions[0])
|
||||
assert isinstance(exc_info.value.exceptions[0], ValueError)
|
||||
assert await page.evaluate("() => 11 * 11") == 121
|
||||
|
||||
|
||||
def test_stop_does_not_deadlock_with_asyncio_atexit(tmp_path: Path) -> None:
|
||||
# Regression test for https://github.com/microsoft/playwright-python/issues/3004.
|
||||
# asyncio.run() cancels all remaining tasks (including transport.run()) before
|
||||
# calling loop.close(). asyncio-atexit hooks loop.close() to run async cleanup,
|
||||
# so awaiting playwright.stop() at that point used to deadlock on a future that
|
||||
# the (already cancelled) run task would never set.
|
||||
script = tmp_path / "atexit_stop.py"
|
||||
script.write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
import asyncio_atexit
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
|
||||
async def main():
|
||||
pw = await async_playwright().start()
|
||||
asyncio_atexit.register(lambda: stop(pw))
|
||||
|
||||
|
||||
async def stop(pw):
|
||||
await pw.stop()
|
||||
print("STOPPED", flush=True)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
)
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert "STOPPED" in result.stdout
|
||||
|
||||
|
||||
async def test_should_return_proper_api_name_on_error(page: Page) -> None:
|
||||
try:
|
||||
await 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:")
|
||||
@@ -0,0 +1,81 @@
|
||||
# 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 Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserType, Error
|
||||
|
||||
|
||||
async def test_should_create_new_page(browser: Browser) -> None:
|
||||
page1 = await browser.new_page()
|
||||
assert len(browser.contexts) == 1
|
||||
|
||||
page2 = await browser.new_page()
|
||||
assert len(browser.contexts) == 2
|
||||
|
||||
await page1.close()
|
||||
assert len(browser.contexts) == 1
|
||||
|
||||
await page2.close()
|
||||
assert len(browser.contexts) == 0
|
||||
|
||||
|
||||
async def test_should_throw_upon_second_create_new_page(browser: Browser) -> None:
|
||||
page = await browser.new_page()
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.context.new_page()
|
||||
await page.close()
|
||||
assert "Please use browser.new_context()" in exc.value.message
|
||||
|
||||
|
||||
async def test_version_should_work(browser: Browser, is_chromium: bool) -> None:
|
||||
version = browser.version
|
||||
if is_chromium:
|
||||
assert re.match(r"^\d+\.\d+\.\d+\.\d+$", version)
|
||||
else:
|
||||
assert re.match(r"^\d+\.\d+", version)
|
||||
|
||||
|
||||
async def test_should_return_browser_type(
|
||||
browser: Browser, browser_type: BrowserType
|
||||
) -> None:
|
||||
assert browser.browser_type is browser_type
|
||||
|
||||
|
||||
async def test_bind_should_return_endpoint_and_allow_unbind(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**launch_arguments)
|
||||
try:
|
||||
result = await browser.bind("test-server")
|
||||
assert "endpoint" in result
|
||||
assert isinstance(result["endpoint"], str)
|
||||
assert len(result["endpoint"]) > 0
|
||||
await browser.unbind()
|
||||
finally:
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_should_fire_context_event_on_new_context(browser: Browser) -> None:
|
||||
# Ported from upstream tests/library/browser.spec.ts.
|
||||
events = []
|
||||
browser.on("context", lambda ctx: events.append(ctx))
|
||||
context = await browser.new_context()
|
||||
try:
|
||||
assert events == [context]
|
||||
finally:
|
||||
await context.close()
|
||||
@@ -0,0 +1,824 @@
|
||||
# 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 typing import Any, List
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
Error,
|
||||
Page,
|
||||
Playwright,
|
||||
)
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def fails_on_401(browser_name: str, is_headless_shell: bool) -> bool:
|
||||
return browser_name == "chromium" and not is_headless_shell
|
||||
|
||||
|
||||
async def test_page_event_should_create_new_context(browser: Browser) -> None:
|
||||
assert len(browser.contexts) == 0
|
||||
context = await browser.new_context()
|
||||
assert len(browser.contexts) == 1
|
||||
assert context in browser.contexts
|
||||
await context.close()
|
||||
assert len(browser.contexts) == 0
|
||||
assert context.browser == browser
|
||||
|
||||
|
||||
async def test_window_open_should_use_parent_tab_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as page_info:
|
||||
await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
|
||||
popup = await page_info.value
|
||||
assert popup.context == context
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_event_should_isolate_localStorage_and_cookies(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
# Create two incognito contexts.
|
||||
context1 = await browser.new_context()
|
||||
context2 = await browser.new_context()
|
||||
assert len(context1.pages) == 0
|
||||
assert len(context2.pages) == 0
|
||||
|
||||
# Create a page in first incognito context.
|
||||
page1 = await context1.new_page()
|
||||
await page1.goto(server.EMPTY_PAGE)
|
||||
await page1.evaluate(
|
||||
"""() => {
|
||||
localStorage.setItem('name', 'page1')
|
||||
document.cookie = 'name=page1'
|
||||
}"""
|
||||
)
|
||||
|
||||
assert len(context1.pages) == 1
|
||||
assert len(context2.pages) == 0
|
||||
|
||||
# Create a page in second incognito context.
|
||||
page2 = await context2.new_page()
|
||||
await page2.goto(server.EMPTY_PAGE)
|
||||
await page2.evaluate(
|
||||
"""() => {
|
||||
localStorage.setItem('name', 'page2')
|
||||
document.cookie = 'name=page2'
|
||||
}"""
|
||||
)
|
||||
|
||||
assert len(context1.pages) == 1
|
||||
assert len(context2.pages) == 1
|
||||
assert context1.pages[0] == page1
|
||||
assert context2.pages[0] == page2
|
||||
|
||||
# Make sure pages don't share localstorage or cookies.
|
||||
assert await page1.evaluate("localStorage.getItem('name')") == "page1"
|
||||
assert await page1.evaluate("document.cookie") == "name=page1"
|
||||
assert await page2.evaluate("localStorage.getItem('name')") == "page2"
|
||||
assert await page2.evaluate("document.cookie") == "name=page2"
|
||||
|
||||
# Cleanup contexts.
|
||||
await asyncio.gather(context1.close(), context2.close())
|
||||
assert browser.contexts == []
|
||||
|
||||
|
||||
async def test_page_event_should_propagate_default_viewport_to_the_page(
|
||||
browser: Browser, utils: Utils
|
||||
) -> None:
|
||||
context = await browser.new_context(viewport={"width": 456, "height": 789})
|
||||
page = await context.new_page()
|
||||
await utils.verify_viewport(page, 456, 789)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_event_should_respect_device_scale_factor(browser: Browser) -> None:
|
||||
context = await browser.new_context(device_scale_factor=3.5)
|
||||
page = await context.new_page()
|
||||
assert await page.evaluate("window.devicePixelRatio") == 3.5
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_event_should_not_allow_device_scale_factor_with_null_viewport(
|
||||
browser: Browser,
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await browser.new_context(no_viewport=True, device_scale_factor=1)
|
||||
assert (
|
||||
exc_info.value.message
|
||||
== 'Browser.new_context: "deviceScaleFactor" option is not supported with null "viewport"'
|
||||
)
|
||||
|
||||
|
||||
async def test_page_event_should_not_allow_is_mobile_with_null_viewport(
|
||||
browser: Browser,
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await browser.new_context(no_viewport=True, is_mobile=True)
|
||||
assert (
|
||||
exc_info.value.message
|
||||
== 'Browser.new_context: "isMobile" option is not supported with null "viewport"'
|
||||
)
|
||||
|
||||
|
||||
async def test_close_should_work_for_empty_context(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_close_should_abort_wait_for_event(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
async with context.expect_page():
|
||||
await context.close()
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc_info.value.message
|
||||
|
||||
|
||||
async def test_close_should_be_callable_twice(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
await asyncio.gather(
|
||||
context.close(),
|
||||
context.close(),
|
||||
)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_is_closed_should_reflect_state(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
assert context.is_closed() is False
|
||||
await context.close()
|
||||
assert context.is_closed() is True
|
||||
|
||||
|
||||
async def test_user_agent_should_work(browser: Browser, server: Server) -> None:
|
||||
async def baseline() -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
assert "Mozilla" in await page.evaluate("navigator.userAgent")
|
||||
await context.close()
|
||||
|
||||
await baseline()
|
||||
|
||||
async def override() -> None:
|
||||
context = await browser.new_context(user_agent="foobar")
|
||||
page = await context.new_page()
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("user-agent") == "foobar"
|
||||
await context.close()
|
||||
|
||||
await override()
|
||||
|
||||
|
||||
async def test_user_agent_should_work_for_subframes(
|
||||
browser: Browser, server: Server, utils: Utils
|
||||
) -> None:
|
||||
context = await browser.new_context(user_agent="foobar")
|
||||
page = await context.new_page()
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
utils.attach_frame(page, "frame1", server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("user-agent") == "foobar"
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_user_agent_should_emulate_device_user_agent(
|
||||
playwright: Playwright, browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(
|
||||
user_agent=playwright.devices["iPhone 6"]["user_agent"]
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/mobile.html")
|
||||
assert "iPhone" in await page.evaluate("navigator.userAgent")
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_user_agent_should_make_a_copy_of_default_options(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
options: Any = {"user_agent": "foobar"}
|
||||
context = await browser.new_context(**options)
|
||||
options["user_agent"] = "wrong"
|
||||
page = await context.new_page()
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("user-agent") == "foobar"
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_event_should_bypass_csp_meta_tag(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
async def baseline() -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/csp.html")
|
||||
try:
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
except Error:
|
||||
pass
|
||||
assert await page.evaluate("window.__injected") is None
|
||||
await context.close()
|
||||
|
||||
await baseline()
|
||||
|
||||
# By-pass CSP and try one more time.
|
||||
async def override() -> None:
|
||||
context = await browser.new_context(bypass_csp=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/csp.html")
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
assert await page.evaluate("() => window.__injected") == 42
|
||||
await context.close()
|
||||
|
||||
await override()
|
||||
|
||||
|
||||
async def test_page_event_should_bypass_csp_header(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
# Make sure CSP prohibits add_script_tag.
|
||||
server.set_csp("/empty.html", 'default-src "self"')
|
||||
|
||||
async def baseline() -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
try:
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
except Error:
|
||||
pass
|
||||
assert await page.evaluate("() => window.__injected") is None
|
||||
await context.close()
|
||||
|
||||
await baseline()
|
||||
|
||||
# By-pass CSP and try one more time.
|
||||
async def override() -> None:
|
||||
context = await browser.new_context(bypass_csp=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
assert await page.evaluate("window.__injected") == 42
|
||||
await context.close()
|
||||
|
||||
await override()
|
||||
|
||||
|
||||
async def test_page_event_should_bypass_after_cross_process_navigation(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(bypass_csp=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/csp.html")
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
assert await page.evaluate("window.__injected") == 42
|
||||
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX + "/csp.html")
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
assert await page.evaluate("window.__injected") == 42
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_event_should_bypass_csp_in_iframes_as_well(
|
||||
browser: Browser, server: Server, utils: Utils
|
||||
) -> None:
|
||||
async def baseline() -> None:
|
||||
# Make sure CSP prohibits add_script_tag in an iframe.
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")
|
||||
try:
|
||||
await frame.add_script_tag(content="window.__injected = 42;")
|
||||
except Error:
|
||||
pass
|
||||
assert await frame.evaluate("window.__injected") is None
|
||||
await context.close()
|
||||
|
||||
await baseline()
|
||||
|
||||
# By-pass CSP and try one more time.
|
||||
async def override() -> None:
|
||||
context = await browser.new_context(bypass_csp=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")
|
||||
try:
|
||||
await frame.add_script_tag(content="window.__injected = 42;")
|
||||
except Error:
|
||||
pass
|
||||
assert await frame.evaluate("window.__injected") == 42
|
||||
await context.close()
|
||||
|
||||
await override()
|
||||
|
||||
|
||||
async def test_csp_should_work(browser: Browser, is_webkit: bool) -> None:
|
||||
async def baseline() -> None:
|
||||
context = await browser.new_context(java_script_enabled=False)
|
||||
page = await context.new_page()
|
||||
await page.goto('data:text/html, <script>var something = "forbidden"</script>')
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.evaluate("something")
|
||||
if is_webkit:
|
||||
assert "Can't find variable: something" in exc_info.value.message
|
||||
else:
|
||||
assert "something is not defined" in exc_info.value.message
|
||||
await context.close()
|
||||
|
||||
await baseline()
|
||||
|
||||
async def override() -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto('data:text/html, <script>var something = "forbidden"</script>')
|
||||
assert await page.evaluate("something") == "forbidden"
|
||||
await context.close()
|
||||
|
||||
await override()
|
||||
|
||||
|
||||
async def test_csp_should_be_able_to_navigate_after_disabling_javascript(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(java_script_enabled=False)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_pages_should_return_all_of_the_pages(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
second = await context.new_page()
|
||||
all_pages = context.pages
|
||||
assert len(all_pages) == 2
|
||||
assert page in all_pages
|
||||
assert second in all_pages
|
||||
|
||||
|
||||
async def test_pages_should_close_all_belonging_pages_once_closing_context(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
await context.new_page()
|
||||
assert len(context.pages) == 1
|
||||
await context.close()
|
||||
assert context.pages == []
|
||||
|
||||
|
||||
async def test_expose_binding_should_work(context: BrowserContext) -> None:
|
||||
binding_source = []
|
||||
|
||||
def binding(source: Any, a: int, b: int) -> int:
|
||||
binding_source.append(source)
|
||||
return a + b
|
||||
|
||||
await context.expose_binding("add", lambda source, a, b: binding(source, a, b))
|
||||
|
||||
page = await context.new_page()
|
||||
result = await page.evaluate("add(5, 6)")
|
||||
assert binding_source[0]["context"] == context
|
||||
assert binding_source[0]["page"] == page
|
||||
assert binding_source[0]["frame"] == page.main_frame
|
||||
assert result == 11
|
||||
|
||||
|
||||
async def test_expose_function_should_work(context: BrowserContext) -> None:
|
||||
await context.expose_function("add", lambda a, b: a + b)
|
||||
page = await context.new_page()
|
||||
await page.expose_function("mul", lambda a, b: a * b)
|
||||
await context.expose_function("sub", lambda a, b: a - b)
|
||||
result = await page.evaluate(
|
||||
"""async function() {
|
||||
return { mul: await mul(9, 4), add: await add(9, 4), sub: await sub(9, 4) }
|
||||
}"""
|
||||
)
|
||||
|
||||
assert result == {"mul": 36, "add": 13, "sub": 5}
|
||||
|
||||
|
||||
async def test_expose_function_should_throw_for_duplicate_registrations(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.expose_function("foo", lambda: None)
|
||||
await context.expose_function("bar", lambda: None)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await context.expose_function("foo", lambda: None)
|
||||
assert exc_info.value.message == 'Function "foo" has been already registered'
|
||||
page = await context.new_page()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.expose_function("foo", lambda: None)
|
||||
assert (
|
||||
exc_info.value.message
|
||||
== 'Function "foo" has been already registered in the browser context'
|
||||
)
|
||||
await page.expose_function("baz", lambda: None)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await context.expose_function("baz", lambda: None)
|
||||
assert (
|
||||
exc_info.value.message
|
||||
== 'Function "baz" has been already registered in one of the pages'
|
||||
)
|
||||
|
||||
|
||||
async def test_expose_function_should_be_callable_from_inside_add_init_script(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
args = []
|
||||
await context.expose_function("woof", lambda arg: args.append(arg))
|
||||
await context.add_init_script("woof('context')")
|
||||
page = await context.new_page()
|
||||
await page.evaluate("undefined")
|
||||
assert args == ["context"]
|
||||
args = []
|
||||
await page.add_init_script("woof('page')")
|
||||
await page.reload()
|
||||
assert args == ["context", "page"]
|
||||
|
||||
|
||||
async def test_auth_should_fail_without_credentials(
|
||||
context: BrowserContext, server: Server, fails_on_401: bool
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 401
|
||||
except Error as exc:
|
||||
assert fails_on_401
|
||||
assert "net::ERR_INVALID_AUTH_CREDENTIALS" in exc.message
|
||||
|
||||
|
||||
async def test_auth_should_work_with_correct_credentials(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_auth_should_fail_with_wrong_credentials(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "foo", "password": "bar"}
|
||||
)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 401
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_auth_should_return_resource_body(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/playground.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.PREFIX + "/playground.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert await page.title() == "Playground"
|
||||
assert "Playground" in await response.text()
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_work_with_correct_credentials_and_matching_origin(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX,
|
||||
}
|
||||
)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_work_with_correct_credentials_and_matching_origin_case_insensitive(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
}
|
||||
)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_fail_with_correct_credentials_and_mismatching_scheme(
|
||||
browser: Browser, server: Server, fails_on_401: bool
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.replace("http://", "https://"),
|
||||
}
|
||||
)
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 401
|
||||
except Error as exc:
|
||||
assert fails_on_401
|
||||
assert "net::ERR_INVALID_AUTH_CREDENTIALS" in exc.message
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_fail_with_correct_credentials_and_mismatching_hostname(
|
||||
browser: Browser, server: Server, fails_on_401: bool
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
hostname = urlparse(server.PREFIX).hostname
|
||||
assert hostname
|
||||
origin = server.PREFIX.replace(hostname, "mismatching-hostname")
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 401
|
||||
except Error as exc:
|
||||
assert fails_on_401
|
||||
assert "net::ERR_INVALID_AUTH_CREDENTIALS" in exc.message
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_fail_with_correct_credentials_and_mismatching_port(
|
||||
browser: Browser, server: Server, fails_on_401: bool
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
origin = server.PREFIX.replace(str(server.PORT), str(server.PORT + 1))
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 401
|
||||
except Error as exc:
|
||||
assert fails_on_401
|
||||
assert "net::ERR_INVALID_AUTH_CREDENTIALS" in exc.message
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_offline_should_work_with_initial_option(
|
||||
browser: Browser,
|
||||
server: Server,
|
||||
browser_name: str,
|
||||
) -> None:
|
||||
context = await browser.new_context(offline=True)
|
||||
page = await context.new_page()
|
||||
frame_navigated_task = asyncio.create_task(page.wait_for_event("framenavigated"))
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
if browser_name == "firefox":
|
||||
await frame_navigated_task
|
||||
assert exc_info.value
|
||||
await context.set_offline(False)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_offline_should_emulate_navigator_online(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
assert await page.evaluate("window.navigator.onLine")
|
||||
await context.set_offline(True)
|
||||
assert await page.evaluate("window.navigator.onLine") is False
|
||||
await context.set_offline(False)
|
||||
assert await page.evaluate("window.navigator.onLine")
|
||||
|
||||
|
||||
async def test_page_event_should_have_url(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_page() as other_page_info:
|
||||
await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
|
||||
other_page = await other_page_info.value
|
||||
assert other_page.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_page_event_should_have_url_after_domcontentloaded(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_page() as other_page_info:
|
||||
await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
|
||||
other_page = await other_page_info.value
|
||||
await other_page.wait_for_load_state("domcontentloaded")
|
||||
assert other_page.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_page_event_should_have_about_blank_url_with_domcontentloaded(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_page() as other_page_info:
|
||||
await page.evaluate("url => window.open(url)", "about:blank")
|
||||
other_page = await other_page_info.value
|
||||
await other_page.wait_for_load_state("domcontentloaded")
|
||||
assert other_page.url == "about:blank"
|
||||
|
||||
|
||||
async def test_page_event_should_have_about_blank_for_empty_url_with_domcontentloaded(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_page() as other_page_info:
|
||||
await page.evaluate("window.open()")
|
||||
other_page = await other_page_info.value
|
||||
await other_page.wait_for_load_state("domcontentloaded")
|
||||
assert other_page.url == "about:blank"
|
||||
|
||||
|
||||
async def test_page_event_should_report_when_a_new_page_is_created_and_closed(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_page() as page_info:
|
||||
await page.evaluate(
|
||||
"url => window.open(url)", server.CROSS_PROCESS_PREFIX + "/empty.html"
|
||||
)
|
||||
other_page = await page_info.value
|
||||
|
||||
# The url is about:blank in FF when 'page' event is fired.
|
||||
assert server.CROSS_PROCESS_PREFIX in other_page.url
|
||||
assert await other_page.evaluate("['Hello', 'world'].join(' ')") == "Hello world"
|
||||
assert await other_page.query_selector("body")
|
||||
|
||||
all_pages = context.pages
|
||||
assert page in all_pages
|
||||
assert other_page in all_pages
|
||||
|
||||
close_event_received = []
|
||||
other_page.once("close", lambda _: close_event_received.append(True))
|
||||
await other_page.close()
|
||||
assert close_event_received == [True]
|
||||
|
||||
all_pages = context.pages
|
||||
assert page in all_pages
|
||||
assert other_page not in all_pages
|
||||
|
||||
|
||||
async def test_page_event_should_report_initialized_pages(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
async with context.expect_page() as page_info:
|
||||
await context.new_page()
|
||||
new_page = await page_info.value
|
||||
assert new_page.url == "about:blank"
|
||||
|
||||
async with context.expect_page() as popup_info:
|
||||
await new_page.evaluate("window.open('about:blank')")
|
||||
popup = await popup_info.value
|
||||
assert popup.url == "about:blank"
|
||||
|
||||
|
||||
async def test_page_event_should_have_an_opener(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with context.expect_page() as page_info:
|
||||
await page.goto(server.PREFIX + "/popup/window-open.html")
|
||||
popup = await page_info.value
|
||||
assert popup.url == server.PREFIX + "/popup/popup.html"
|
||||
assert await popup.opener() == page
|
||||
assert await page.opener() is None
|
||||
|
||||
|
||||
async def test_page_event_should_fire_page_lifecycle_events(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
events: List[str] = []
|
||||
|
||||
def handle_page(page: Page) -> None:
|
||||
events.append("CREATED: " + page.url)
|
||||
page.on("close", lambda _: events.append("DESTROYED: " + page.url))
|
||||
|
||||
context.on("page", handle_page)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.close()
|
||||
assert events == ["CREATED: about:blank", f"DESTROYED: {server.EMPTY_PAGE}"]
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("webkit")
|
||||
async def test_page_event_should_work_with_shift_clicking(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
# WebKit: Shift+Click does not open a new window.
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content('<a href="/one-style.html">yo</a>')
|
||||
async with context.expect_page() as page_info:
|
||||
await page.click("a", modifiers=["Shift"])
|
||||
popup = await page_info.value
|
||||
assert await popup.opener() is None
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_page_event_should_work_with_ctrl_clicking(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
# Firefox: reports an opener in this case.
|
||||
# WebKit: Ctrl+Click does not open a new tab.
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content('<a href="/one-style.html">yo</a>')
|
||||
async with context.expect_page() as popup_info:
|
||||
await page.click("a", modifiers=["ControlOrMeta"])
|
||||
popup = await popup_info.value
|
||||
assert await popup.opener() is None
|
||||
|
||||
|
||||
async def test_strict_selectors_on_context(browser: Browser, server: Server) -> None:
|
||||
context = await browser.new_context(strict_selectors=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<button>Hello</button>
|
||||
<button>Hello</button>
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error):
|
||||
await page.text_content("button")
|
||||
with pytest.raises(Error):
|
||||
await page.query_selector("button")
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_support_forced_colors(browser: Browser) -> None:
|
||||
context = await browser.new_context(forced_colors="active")
|
||||
page = await context.new_page()
|
||||
assert await page.evaluate("matchMedia('(forced-colors: active)').matches")
|
||||
assert not await page.evaluate("matchMedia('(forced-colors: none)').matches")
|
||||
@@ -0,0 +1,436 @@
|
||||
# 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
|
||||
import datetime
|
||||
from typing import Callable, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Error, Page
|
||||
from tests.server import Server, TestServerRequest
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_should_work(context: BrowserContext, page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "password", "value": "123456"}]
|
||||
)
|
||||
assert await page.evaluate("() => document.cookie") == "password=123456"
|
||||
|
||||
|
||||
async def test_should_roundtrip_cookie(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
# @see https://en.wikipedia.org/wiki/Year_2038_problem
|
||||
date = int(datetime.datetime(2038, 1, 1).timestamp() * 1000)
|
||||
document_cookie = await page.evaluate(
|
||||
"""timestamp => {
|
||||
const date = new Date(timestamp);
|
||||
document.cookie = `username=John Doe;expires=${date.toUTCString()}`;
|
||||
return document.cookie;
|
||||
}""",
|
||||
date,
|
||||
)
|
||||
assert document_cookie == "username=John Doe"
|
||||
cookies = await context.cookies()
|
||||
await context.clear_cookies()
|
||||
assert await context.cookies() == []
|
||||
# TODO: We are waiting for PEP705 so SetCookieParam can be readonly and matches the Cookie type.
|
||||
await context.add_cookies(cookies) # type: ignore
|
||||
assert await context.cookies() == cookies
|
||||
|
||||
|
||||
async def test_should_send_cookie_header(
|
||||
server: Server, context: BrowserContext
|
||||
) -> None:
|
||||
cookie: List[str] = []
|
||||
|
||||
def handler(request: TestServerRequest) -> None:
|
||||
cookie.extend(must(request.requestHeaders.getRawHeaders("cookie")))
|
||||
request.finish()
|
||||
|
||||
server.set_route("/empty.html", handler)
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "cookie", "value": "value"}]
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert cookie == ["cookie=value"]
|
||||
|
||||
|
||||
async def test_should_isolate_cookies_in_browser_contexts(
|
||||
context: BrowserContext, server: Server, browser: Browser
|
||||
) -> None:
|
||||
another_context = await browser.new_context()
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "isolatecookie", "value": "page1value"}]
|
||||
)
|
||||
await another_context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "isolatecookie", "value": "page2value"}]
|
||||
)
|
||||
|
||||
cookies_1 = await context.cookies()
|
||||
cookies_2 = await another_context.cookies()
|
||||
assert len(cookies_1) == 1
|
||||
assert len(cookies_2) == 1
|
||||
assert cookies_1[0]["name"] == "isolatecookie"
|
||||
assert cookies_1[0]["value"] == "page1value"
|
||||
assert cookies_2[0]["name"] == "isolatecookie"
|
||||
assert cookies_2[0]["value"] == "page2value"
|
||||
await another_context.close()
|
||||
|
||||
|
||||
async def test_should_isolate_session_cookies(
|
||||
context: BrowserContext, server: Server, browser: Browser
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/setcookie.html",
|
||||
lambda r: (
|
||||
r.setHeader("Set-Cookie", "session=value"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
page_1 = await context.new_page()
|
||||
await page_1.goto(server.PREFIX + "/setcookie.html")
|
||||
##
|
||||
page_2 = await context.new_page()
|
||||
await page_2.goto(server.EMPTY_PAGE)
|
||||
cookies_2 = await context.cookies()
|
||||
assert len(cookies_2) == 1
|
||||
assert ",".join(list(map(lambda c: c["value"], cookies_2))) == "value"
|
||||
##
|
||||
context_b = await browser.new_context()
|
||||
page_3 = await context_b.new_page()
|
||||
await page_3.goto(server.EMPTY_PAGE)
|
||||
cookies_3 = await context_b.cookies()
|
||||
assert cookies_3 == []
|
||||
await context_b.close()
|
||||
|
||||
|
||||
async def test_should_isolate_persistent_cookies(
|
||||
context: BrowserContext, server: Server, browser: Browser
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/setcookie.html",
|
||||
lambda r: (
|
||||
r.setHeader("Set-Cookie", "persistent=persistent-value; max-age=3600"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/setcookie.html")
|
||||
|
||||
context_1 = context
|
||||
context_2 = await browser.new_context()
|
||||
[page_1, page_2] = await asyncio.gather(context_1.new_page(), context_2.new_page())
|
||||
await asyncio.gather(page_1.goto(server.EMPTY_PAGE), page_2.goto(server.EMPTY_PAGE))
|
||||
[cookies_1, cookies_2] = await asyncio.gather(
|
||||
context_1.cookies(), context_2.cookies()
|
||||
)
|
||||
assert len(cookies_1) == 1
|
||||
assert cookies_1[0]["name"] == "persistent"
|
||||
assert cookies_1[0]["value"] == "persistent-value"
|
||||
assert len(cookies_2) == 0
|
||||
await context_2.close()
|
||||
|
||||
|
||||
async def test_should_isolate_send_cookie_header(
|
||||
server: Server, context: BrowserContext, browser: Browser
|
||||
) -> None:
|
||||
cookie: List[str] = []
|
||||
|
||||
def handler(request: TestServerRequest) -> None:
|
||||
cookie.extend(request.requestHeaders.getRawHeaders("cookie") or [])
|
||||
request.finish()
|
||||
|
||||
server.set_route("/empty.html", handler)
|
||||
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "sendcookie", "value": "value"}]
|
||||
)
|
||||
|
||||
page_1 = await context.new_page()
|
||||
await page_1.goto(server.EMPTY_PAGE)
|
||||
assert cookie == ["sendcookie=value"]
|
||||
cookie.clear()
|
||||
##
|
||||
context_2 = await browser.new_context()
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.EMPTY_PAGE)
|
||||
assert cookie == []
|
||||
await context_2.close()
|
||||
|
||||
|
||||
async def test_should_isolate_cookies_between_launches(
|
||||
browser_factory: Callable[..., "asyncio.Future[Browser]"], server: Server
|
||||
) -> None:
|
||||
browser_1 = await browser_factory()
|
||||
context_1 = await browser_1.new_context()
|
||||
await context_1.add_cookies(
|
||||
[
|
||||
{
|
||||
"url": server.EMPTY_PAGE,
|
||||
"name": "cookie-in-context-1",
|
||||
"value": "value",
|
||||
"expires": int(datetime.datetime.now().timestamp() + 10000),
|
||||
}
|
||||
]
|
||||
)
|
||||
await browser_1.close()
|
||||
|
||||
browser_2 = await browser_factory()
|
||||
context_2 = await browser_2.new_context()
|
||||
cookies = await context_2.cookies()
|
||||
assert cookies == []
|
||||
await browser_2.close()
|
||||
|
||||
|
||||
async def test_should_set_multiple_cookies(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.add_cookies(
|
||||
[
|
||||
{"url": server.EMPTY_PAGE, "name": "multiple-1", "value": "123456"},
|
||||
{"url": server.EMPTY_PAGE, "name": "multiple-2", "value": "bar"},
|
||||
]
|
||||
)
|
||||
assert (
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const cookies = document.cookie.split(';');
|
||||
return cookies.map(cookie => cookie.trim()).sort();
|
||||
}"""
|
||||
)
|
||||
== ["multiple-1=123456", "multiple-2=bar"]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_have_expires_set_to_neg_1_for_session_cookies(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "expires", "value": "123456"}]
|
||||
)
|
||||
cookies = await context.cookies()
|
||||
assert cookies[0]["expires"] == -1
|
||||
|
||||
|
||||
async def test_should_set_cookie_with_reasonable_defaults(
|
||||
context: BrowserContext,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "defaults", "value": "123456"}]
|
||||
)
|
||||
cookies = await context.cookies()
|
||||
cookies.sort(key=lambda r: r["name"])
|
||||
assert cookies == [
|
||||
{
|
||||
"name": "defaults",
|
||||
"value": "123456",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_should_set_a_cookie_with_a_path(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"domain": "localhost",
|
||||
"path": "/grid.html",
|
||||
"name": "gridcookie",
|
||||
"value": "GRID",
|
||||
}
|
||||
]
|
||||
)
|
||||
assert await context.cookies() == [
|
||||
{
|
||||
"name": "gridcookie",
|
||||
"value": "GRID",
|
||||
"domain": "localhost",
|
||||
"path": "/grid.html",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
assert await page.evaluate("document.cookie") == "gridcookie=GRID"
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
assert await page.evaluate("document.cookie") == "gridcookie=GRID"
|
||||
|
||||
|
||||
async def test_should_not_set_a_cookie_with_blank_page_url(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{"url": server.EMPTY_PAGE, "name": "example-cookie", "value": "best"},
|
||||
{"url": "about:blank", "name": "example-cookie-blank", "value": "best"},
|
||||
]
|
||||
)
|
||||
assert (
|
||||
'Blank page can not have cookie "example-cookie-blank"'
|
||||
in exc_info.value.message
|
||||
)
|
||||
|
||||
|
||||
async def test_should_not_set_a_cookie_on_a_data_url_page(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"url": "data:,Hello%2C%20World!",
|
||||
"name": "example-cookie",
|
||||
"value": "best",
|
||||
}
|
||||
]
|
||||
)
|
||||
assert (
|
||||
'Data URL page can not have cookie "example-cookie"' in exc_info.value.message
|
||||
)
|
||||
|
||||
|
||||
async def test_should_default_to_setting_secure_cookie_for_https_websites(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
SECURE_URL = "https://example.com"
|
||||
await context.add_cookies([{"url": SECURE_URL, "name": "foo", "value": "bar"}])
|
||||
[cookie] = await context.cookies(SECURE_URL)
|
||||
assert cookie["secure"]
|
||||
|
||||
|
||||
async def test_should_be_able_to_set_unsecure_cookie_for_http_website(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
HTTP_URL = "http://example.com"
|
||||
await context.add_cookies([{"url": HTTP_URL, "name": "foo", "value": "bar"}])
|
||||
[cookie] = await context.cookies(HTTP_URL)
|
||||
assert not cookie["secure"]
|
||||
|
||||
|
||||
async def test_should_set_a_cookie_on_a_different_domain(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.add_cookies(
|
||||
[{"url": "https://www.example.com", "name": "example-cookie", "value": "best"}]
|
||||
)
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
assert await context.cookies("https://www.example.com") == [
|
||||
{
|
||||
"name": "example-cookie",
|
||||
"value": "best",
|
||||
"domain": "www.example.com",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": True,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_should_set_cookies_for_a_frame(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.add_cookies(
|
||||
[{"url": server.PREFIX, "name": "frame-cookie", "value": "value"}]
|
||||
)
|
||||
await page.evaluate(
|
||||
"""src => {
|
||||
let fulfill;
|
||||
const promise = new Promise(x => fulfill = x);
|
||||
const iframe = document.createElement('iframe');
|
||||
document.body.appendChild(iframe);
|
||||
iframe.onload = fulfill;
|
||||
iframe.src = src;
|
||||
return promise;
|
||||
}""",
|
||||
server.PREFIX + "/grid.html",
|
||||
)
|
||||
|
||||
assert await page.frames[1].evaluate("document.cookie") == "frame-cookie=value"
|
||||
|
||||
|
||||
async def test_should_not_block_third_party_cookies(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
is_chromium: bool,
|
||||
is_firefox: bool,
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""src => {
|
||||
let fulfill;
|
||||
const promise = new Promise(x => fulfill = x);
|
||||
const iframe = document.createElement('iframe');
|
||||
document.body.appendChild(iframe);
|
||||
iframe.onload = fulfill;
|
||||
iframe.src = src;
|
||||
return promise;
|
||||
}""",
|
||||
server.CROSS_PROCESS_PREFIX + "/grid.html",
|
||||
)
|
||||
await page.frames[1].evaluate("document.cookie = 'username=John Doe'")
|
||||
await page.wait_for_timeout(2000)
|
||||
allows_third_party = is_firefox
|
||||
cookies = await context.cookies(server.CROSS_PROCESS_PREFIX + "/grid.html")
|
||||
|
||||
if allows_third_party:
|
||||
assert cookies == [
|
||||
{
|
||||
"domain": "127.0.0.1",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"name": "username",
|
||||
"path": "/",
|
||||
"sameSite": "Lax" if is_chromium else "None",
|
||||
"secure": False,
|
||||
"value": "John Doe",
|
||||
}
|
||||
]
|
||||
else:
|
||||
assert cookies == []
|
||||
@@ -0,0 +1,198 @@
|
||||
# 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 urllib.parse import urlparse
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_clear_cookies(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "cookie1", "value": "1"}]
|
||||
)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1"
|
||||
await context.clear_cookies()
|
||||
assert await context.cookies() == []
|
||||
await page.reload()
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
|
||||
|
||||
async def test_should_isolate_cookies_when_clearing(
|
||||
context: BrowserContext, server: Server, browser: Browser
|
||||
) -> None:
|
||||
another_context = await browser.new_context()
|
||||
await context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "page1cookie", "value": "page1value"}]
|
||||
)
|
||||
await another_context.add_cookies(
|
||||
[{"url": server.EMPTY_PAGE, "name": "page2cookie", "value": "page2value"}]
|
||||
)
|
||||
|
||||
assert len(await context.cookies()) == 1
|
||||
assert len(await another_context.cookies()) == 1
|
||||
|
||||
await context.clear_cookies()
|
||||
assert len(await context.cookies()) == 0
|
||||
assert len(await another_context.cookies()) == 1
|
||||
|
||||
await another_context.clear_cookies()
|
||||
assert len(await context.cookies()) == 0
|
||||
assert len(await another_context.cookies()) == 0
|
||||
await another_context.close()
|
||||
|
||||
|
||||
async def test_should_remove_cookies_by_name(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
{
|
||||
"name": "cookie2",
|
||||
"value": "2",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
]
|
||||
)
|
||||
await page.goto(server.PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1; cookie2=2"
|
||||
await context.clear_cookies(name="cookie1")
|
||||
assert await page.evaluate("document.cookie") == "cookie2=2"
|
||||
|
||||
|
||||
async def test_should_remove_cookies_by_name_regex(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
{
|
||||
"name": "cookie2",
|
||||
"value": "2",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
]
|
||||
)
|
||||
await page.goto(server.PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1; cookie2=2"
|
||||
await context.clear_cookies(name=re.compile("coo.*1"))
|
||||
assert await page.evaluate("document.cookie") == "cookie2=2"
|
||||
|
||||
|
||||
async def test_should_remove_cookies_by_domain(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
{
|
||||
"name": "cookie2",
|
||||
"value": "2",
|
||||
"domain": urlparse(server.CROSS_PROCESS_PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
]
|
||||
)
|
||||
await page.goto(server.PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1"
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie2=2"
|
||||
await context.clear_cookies(domain=urlparse(server.CROSS_PROCESS_PREFIX).hostname)
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
await page.goto(server.PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1"
|
||||
|
||||
|
||||
async def test_should_remove_cookies_by_path(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/api/v1",
|
||||
},
|
||||
{
|
||||
"name": "cookie2",
|
||||
"value": "2",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/api/v2",
|
||||
},
|
||||
{
|
||||
"name": "cookie3",
|
||||
"value": "3",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
]
|
||||
)
|
||||
await page.goto(server.PREFIX + "/api/v1")
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1; cookie3=3"
|
||||
await context.clear_cookies(path="/api/v1")
|
||||
assert await page.evaluate("document.cookie") == "cookie3=3"
|
||||
await page.goto(server.PREFIX + "/api/v2")
|
||||
assert await page.evaluate("document.cookie") == "cookie2=2; cookie3=3"
|
||||
await page.goto(server.PREFIX + "/")
|
||||
assert await page.evaluate("document.cookie") == "cookie3=3"
|
||||
|
||||
|
||||
async def test_should_remove_cookies_by_name_and_domain(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
{
|
||||
"name": "cookie1",
|
||||
"value": "1",
|
||||
"domain": urlparse(server.CROSS_PROCESS_PREFIX).hostname,
|
||||
"path": "/",
|
||||
},
|
||||
]
|
||||
)
|
||||
await page.goto(server.PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1"
|
||||
await context.clear_cookies(name="cookie1", domain=urlparse(server.PREFIX).hostname)
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1"
|
||||
@@ -0,0 +1,268 @@
|
||||
# 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.async_api import Browser, BrowserType, Playwright, expect
|
||||
|
||||
ssl.optionsForClientTLS
|
||||
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()
|
||||
|
||||
|
||||
async def test_should_throw_with_untrusted_client_certs(
|
||||
playwright: Playwright, assetdir: Path
|
||||
) -> None:
|
||||
serverURL = "https://localhost:8000/"
|
||||
request = await 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"):
|
||||
await request.get(serverURL)
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async def test_should_work_with_new_context(browser: Browser, assetdir: Path) -> None:
|
||||
context = await 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 = await context.new_page()
|
||||
await page.goto("https://localhost:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
await page.goto("https://127.0.0.1:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
|
||||
response = await page.context.request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in await response.text()
|
||||
)
|
||||
response = await page.context.request.get("https://127.0.0.1:8000")
|
||||
assert (
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
in await response.text()
|
||||
)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_work_with_new_context_passing_as_content(
|
||||
browser: Browser, assetdir: Path
|
||||
) -> None:
|
||||
context = await 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 = await context.new_page()
|
||||
await page.goto("https://localhost:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
await page.goto("https://127.0.0.1:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
|
||||
response = await page.context.request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in await response.text()
|
||||
)
|
||||
response = await page.context.request.get("https://127.0.0.1:8000")
|
||||
assert (
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
in await response.text()
|
||||
)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_work_with_new_persistent_context(
|
||||
browser_type: BrowserType, assetdir: Path, launch_arguments: Dict
|
||||
) -> None:
|
||||
context = await 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 = await context.new_page()
|
||||
await page.goto("https://localhost:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
)
|
||||
await page.goto("https://127.0.0.1:8000")
|
||||
await expect(page.get_by_test_id("message")).to_have_text(
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_work_with_global_api_request_context(
|
||||
playwright: Playwright, assetdir: Path
|
||||
) -> None:
|
||||
request = await 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 = await request.get("https://localhost:8000")
|
||||
assert (
|
||||
"Sorry, but you need to provide a client certificate to continue."
|
||||
in await response.text()
|
||||
)
|
||||
response = await request.get("https://127.0.0.1:8000")
|
||||
assert (
|
||||
"Hello Alice, your certificate was issued by localhost!"
|
||||
in await response.text()
|
||||
)
|
||||
await request.dispose()
|
||||
@@ -0,0 +1,229 @@
|
||||
# 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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserContext, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_return_no_cookies_in_pristine_browser_context(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
assert await context.cookies() == []
|
||||
|
||||
|
||||
async def test_should_get_a_cookie(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
document_cookie = await page.evaluate(
|
||||
"""() => {
|
||||
document.cookie = 'username=John Doe';
|
||||
return document.cookie;
|
||||
}"""
|
||||
)
|
||||
assert document_cookie == "username=John Doe"
|
||||
assert await context.cookies() == [
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_should_get_a_non_session_cookie(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
# @see https://en.wikipedia.org/wiki/Year_2038_problem
|
||||
date = int(datetime.datetime(2038, 1, 1).timestamp() * 1000)
|
||||
document_cookie = await page.evaluate(
|
||||
"""timestamp => {
|
||||
const date = new Date(timestamp);
|
||||
document.cookie = `username=John Doe;expires=${date.toUTCString()}`;
|
||||
return document.cookie;
|
||||
}""",
|
||||
date,
|
||||
)
|
||||
assert document_cookie == "username=John Doe"
|
||||
cookies = await context.cookies()
|
||||
expires = cookies[0]["expires"]
|
||||
del cookies[0]["expires"]
|
||||
# Browsers start to cap cookies with 400 days max expires value.
|
||||
# See https://github.com/httpwg/http-extensions/pull/1732
|
||||
# Chromium patch: https://chromium.googlesource.com/chromium/src/+/aaa5d2b55478eac2ee642653dcd77a50ac3faff6
|
||||
# We want to make sure that expires date is at least 400 days in future.
|
||||
# We use 355 to prevent flakes and not think about timezones!
|
||||
assert datetime.datetime.fromtimestamp(
|
||||
expires
|
||||
) - datetime.datetime.now() > datetime.timedelta(days=355)
|
||||
assert cookies == [
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_should_properly_report_httpOnly_cookie(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/empty.html",
|
||||
lambda r: (
|
||||
r.setHeader("Set-Cookie", "name=value;httpOnly; Path=/"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
cookies = await context.cookies()
|
||||
assert len(cookies) == 1
|
||||
assert cookies[0]["httpOnly"] is True
|
||||
|
||||
|
||||
async def test_should_properly_report_strict_sameSite_cookie(
|
||||
context: BrowserContext, page: Page, server: Server, is_webkit: bool, is_win: bool
|
||||
) -> None:
|
||||
if is_webkit and is_win:
|
||||
pytest.skip()
|
||||
|
||||
server.set_route(
|
||||
"/empty.html",
|
||||
lambda r: (
|
||||
r.setHeader("Set-Cookie", "name=value;sameSite=Strict"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
cookies = await context.cookies()
|
||||
assert len(cookies) == 1
|
||||
assert cookies[0]["sameSite"] == "Strict"
|
||||
|
||||
|
||||
async def test_should_properly_report_lax_sameSite_cookie(
|
||||
context: BrowserContext, page: Page, server: Server, is_webkit: bool, is_win: bool
|
||||
) -> None:
|
||||
if is_webkit and is_win:
|
||||
pytest.skip()
|
||||
|
||||
server.set_route(
|
||||
"/empty.html",
|
||||
lambda r: (
|
||||
r.setHeader("Set-Cookie", "name=value;sameSite=Lax"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
cookies = await context.cookies()
|
||||
assert len(cookies) == 1
|
||||
assert cookies[0]["sameSite"] == "Lax"
|
||||
|
||||
|
||||
async def test_should_get_multiple_cookies(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
document_cookie = await page.evaluate(
|
||||
"""() => {
|
||||
document.cookie = 'username=John Doe';
|
||||
document.cookie = 'password=1234';
|
||||
return document.cookie.split('; ').sort().join('; ');
|
||||
}"""
|
||||
)
|
||||
cookies = await context.cookies()
|
||||
cookies.sort(key=lambda r: r["name"])
|
||||
assert document_cookie == "password=1234; username=John Doe"
|
||||
assert cookies == [
|
||||
{
|
||||
"name": "password",
|
||||
"value": "1234",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
},
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
async def test_should_get_cookies_from_multiple_urls(
|
||||
context: BrowserContext, default_same_site_cookie_value: str
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{"url": "https://foo.com", "name": "doggo", "value": "woofs"},
|
||||
{"url": "https://bar.com", "name": "catto", "value": "purrs"},
|
||||
{"url": "https://baz.com", "name": "birdo", "value": "tweets"},
|
||||
]
|
||||
)
|
||||
cookies = await context.cookies(["https://foo.com", "https://baz.com"])
|
||||
cookies.sort(key=lambda r: r["name"])
|
||||
|
||||
assert cookies == [
|
||||
{
|
||||
"name": "birdo",
|
||||
"value": "tweets",
|
||||
"domain": "baz.com",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": True,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
},
|
||||
{
|
||||
"name": "doggo",
|
||||
"value": "woofs",
|
||||
"domain": "foo.com",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": True,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,320 @@
|
||||
# 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 typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserContext, Page
|
||||
from tests.utils import must
|
||||
|
||||
from ..server import Server, TestServerRequest
|
||||
|
||||
|
||||
async def test_console_event_should_work(page: Page) -> None:
|
||||
[message, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("console"),
|
||||
page.evaluate("() => console.log('hello')"),
|
||||
)
|
||||
assert message.text == "hello"
|
||||
assert message.page == page
|
||||
|
||||
|
||||
async def test_console_event_should_work_in_popup(page: Page) -> None:
|
||||
[message, popup, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("console"),
|
||||
page.wait_for_event("popup"),
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open('');
|
||||
win.console.log('hello');
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_console_event_should_work_in_popup_2(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
[message, popup, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("console", lambda msg: msg.type == "log"),
|
||||
page.context.wait_for_event("page"),
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
const win = window.open('javascript:console.log("hello")');
|
||||
await new Promise(f => setTimeout(f, 0));
|
||||
win.close();
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_console_event_should_work_in_immediately_closed_popup(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
[message, popup, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("console"),
|
||||
page.wait_for_event("popup"),
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
const win = window.open();
|
||||
win.console.log('hello');
|
||||
win.close();
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
async def test_dialog_event_should_work1(page: Page) -> None:
|
||||
prompt_task: Optional[asyncio.Future[str]] = None
|
||||
|
||||
async def open_dialog() -> None:
|
||||
nonlocal prompt_task
|
||||
prompt_task = asyncio.create_task(page.evaluate("() => prompt('hey?')"))
|
||||
|
||||
[dialog1, dialog2, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("dialog"),
|
||||
page.wait_for_event("dialog"),
|
||||
open_dialog(),
|
||||
)
|
||||
assert dialog1 == dialog2
|
||||
assert dialog1.message == "hey?"
|
||||
assert dialog1.page == page
|
||||
await dialog1.accept("hello")
|
||||
assert await must(prompt_task) == "hello"
|
||||
|
||||
|
||||
async def test_dialog_event_should_work_in_popup(page: Page) -> None:
|
||||
prompt_task: Optional[asyncio.Future[str]] = None
|
||||
|
||||
async def open_dialog() -> None:
|
||||
nonlocal prompt_task
|
||||
prompt_task = asyncio.create_task(
|
||||
page.evaluate("() => window.open('').prompt('hey?')")
|
||||
)
|
||||
|
||||
[dialog, popup, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("dialog"),
|
||||
page.wait_for_event("popup"),
|
||||
open_dialog(),
|
||||
)
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page == popup
|
||||
await dialog.accept("hello")
|
||||
assert await must(prompt_task) == "hello"
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_dialog_event_should_work_in_popup_2(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
promise = asyncio.create_task(
|
||||
page.evaluate("() => window.open('javascript:prompt(\"hey?\")')")
|
||||
)
|
||||
dialog = await page.context.wait_for_event("dialog")
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page is None
|
||||
await dialog.accept("hello")
|
||||
await promise
|
||||
|
||||
|
||||
# console message from javascript: url is not reported at all
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_dialog_event_should_work_in_immdiately_closed_popup(page: Page) -> None:
|
||||
[message, popup, _] = await asyncio.gather(
|
||||
page.context.wait_for_event("console"),
|
||||
page.wait_for_event("popup"),
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open();
|
||||
win.console.log('hello');
|
||||
win.close();
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert message.text == "hello"
|
||||
assert message.page == popup
|
||||
|
||||
|
||||
async 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)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<a href='popup.html' target=_blank>Click me</a>")
|
||||
|
||||
promise = asyncio.create_task(page.click("a"))
|
||||
[dialog, popup] = await asyncio.gather(
|
||||
page.context.wait_for_event("dialog"),
|
||||
page.wait_for_event("popup"),
|
||||
)
|
||||
|
||||
assert dialog.message == "hey?"
|
||||
assert dialog.page == popup
|
||||
await dialog.accept("hello")
|
||||
await promise
|
||||
assert await popup.evaluate("window.result") == "hello"
|
||||
|
||||
|
||||
async def test_console_event_should_work_with_context_manager(page: Page) -> None:
|
||||
async with page.context.expect_console_message() as cm_info:
|
||||
await page.evaluate("() => console.log('hello')")
|
||||
message = await cm_info.value
|
||||
assert message.text == "hello"
|
||||
assert message.page == page
|
||||
|
||||
|
||||
async def test_page_error_event_should_work(page: Page) -> None:
|
||||
async with page.context.expect_event("weberror") as page_error_info:
|
||||
await page.set_content('<script>throw new Error("boom")</script>')
|
||||
page_error = await page_error_info.value
|
||||
assert page_error.page == page
|
||||
assert page_error.error.stack and "boom" in page_error.error.stack
|
||||
|
||||
|
||||
async def test_weberror_event_should_work(context: BrowserContext, page: Page) -> None:
|
||||
async with context.expect_event("weberror") as error_info:
|
||||
await page.goto('data:text/html,<script>throw new Error("Test")</script>')
|
||||
error = await error_info.value
|
||||
assert error.page == page
|
||||
assert error.error.message == "Test"
|
||||
|
||||
|
||||
async 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)
|
||||
|
||||
async with context.expect_event("weberror") as error_info:
|
||||
await page.goto(server.PREFIX + "/error.html")
|
||||
web_error = await error_info.value
|
||||
location = web_error.location
|
||||
assert location["url"] == f"{server.PREFIX}/error.js"
|
||||
assert location["line"] == 2
|
||||
assert location["column"] > 0
|
||||
|
||||
|
||||
async def test_pageload_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
async with context.expect_event("pageload") as info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
event_page = await info.value
|
||||
assert event_page == page
|
||||
|
||||
|
||||
async def test_framenavigated_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
async with context.expect_event("framenavigated") as info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame = await info.value
|
||||
assert frame == page.main_frame
|
||||
assert frame.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_pageclose_event_should_work(context: BrowserContext) -> None:
|
||||
page = await context.new_page()
|
||||
async with context.expect_event("pageclose") as info:
|
||||
await page.close()
|
||||
closed = await info.value
|
||||
assert closed == page
|
||||
|
||||
|
||||
async def test_frameattached_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with context.expect_event("frameattached") as info:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = 'about:blank';
|
||||
document.body.appendChild(iframe);
|
||||
}"""
|
||||
)
|
||||
frame = await info.value
|
||||
assert frame.parent_frame == page.main_frame
|
||||
|
||||
|
||||
async def test_framedetached_event_should_work(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.id = 'x';
|
||||
iframe.src = 'about:blank';
|
||||
document.body.appendChild(iframe);
|
||||
}"""
|
||||
)
|
||||
await page.wait_for_selector("iframe")
|
||||
async with context.expect_event("framedetached") as info:
|
||||
await page.evaluate("() => document.getElementById('x').remove()")
|
||||
frame = await info.value
|
||||
assert frame.parent_frame == page.main_frame
|
||||
|
||||
|
||||
async 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)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with context.expect_event("download") as info:
|
||||
await page.click("a")
|
||||
download = await info.value
|
||||
assert download.suggested_filename == "file.txt"
|
||||
assert download.page == page
|
||||
@@ -0,0 +1,161 @@
|
||||
# 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
|
||||
import base64
|
||||
from typing import AsyncGenerator, Awaitable, Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def browser(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]",
|
||||
) -> AsyncGenerator[Browser, None]:
|
||||
browser = await browser_factory(proxy={"server": "dummy"})
|
||||
yield browser
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_should_use_proxy(
|
||||
context_factory: "Callable[..., asyncio.Future[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
context = await context_factory(proxy={"server": f"localhost:{server.PORT}"})
|
||||
page = await context.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_proxy_should_allow_none_for_optional_settings(
|
||||
context_factory: "Callable[..., asyncio.Future[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
context = await context_factory(
|
||||
proxy={
|
||||
"server": f"localhost:{server.PORT}",
|
||||
"username": None,
|
||||
"password": None,
|
||||
"bypass": None,
|
||||
}
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_use_proxy_for_second_page(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
context = await context_factory(proxy={"server": f"localhost:{server.PORT}"})
|
||||
|
||||
page1 = await context.new_page()
|
||||
await page1.goto("http://non-existent.com/target.html")
|
||||
assert await page1.title() == "Served by the proxy"
|
||||
|
||||
page2 = await context.new_page()
|
||||
await page2.goto("http://non-existent.com/target.html")
|
||||
assert await page2.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_work_with_ip_port_notion(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
context = await context_factory(proxy={"server": f"127.0.0.1:{server.PORT}"})
|
||||
page = await context.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_authenticate(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
def handler(req: TestServerRequest) -> None:
|
||||
auth = req.getHeader("proxy-authorization")
|
||||
if not auth:
|
||||
req.setHeader(
|
||||
b"Proxy-Authenticate", b'Basic realm="Access to internal site"'
|
||||
)
|
||||
req.setResponseCode(407)
|
||||
else:
|
||||
req.write(f"<html><title>{auth}</title></html>".encode("utf-8"))
|
||||
req.finish()
|
||||
|
||||
server.set_route("/target.html", handler)
|
||||
|
||||
context = await context_factory(
|
||||
proxy={
|
||||
"server": f"localhost:{server.PORT}",
|
||||
"username": "user",
|
||||
"password": "secret",
|
||||
}
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Basic " + base64.b64encode(b"user:secret").decode(
|
||||
"utf-8"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_authenticate_with_empty_password(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
def handler(req: TestServerRequest) -> None:
|
||||
auth = req.getHeader("proxy-authorization")
|
||||
if not auth:
|
||||
req.setHeader(
|
||||
b"Proxy-Authenticate", b'Basic realm="Access to internal site"'
|
||||
)
|
||||
req.setResponseCode(407)
|
||||
else:
|
||||
req.write(f"<html><title>{auth}</title></html>".encode("utf-8"))
|
||||
req.finish()
|
||||
|
||||
server.set_route("/target.html", handler)
|
||||
|
||||
context = await context_factory(
|
||||
proxy={"server": f"localhost:{server.PORT}", "username": "user", "password": ""}
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Basic " + base64.b64encode(b"user:").decode("utf-8")
|
||||
@@ -0,0 +1,297 @@
|
||||
# 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 typing import Any, Callable, Coroutine, cast
|
||||
|
||||
from playwright.async_api import BrowserContext, Page, Request, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_work(page: Page, context: BrowserContext, server: Server) -> None:
|
||||
await context.route("**/*", lambda route: asyncio.create_task(route.fallback()))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_fall_back(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route("**/empty.html", _handler1)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
_handler2,
|
||||
)
|
||||
|
||||
def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route("**/empty.html", _handler3)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_fall_back_async_delayed(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
def create_handler(i: int) -> Callable[[Route], Coroutine]:
|
||||
async def handler(route: Route) -> None:
|
||||
intercepted.append(i)
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fallback()
|
||||
|
||||
return handler
|
||||
|
||||
await context.route("**/empty.html", create_handler(1))
|
||||
await context.route("**/empty.html", create_handler(2))
|
||||
await context.route("**/empty.html", create_handler(3))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_chain_once(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.route(
|
||||
"**/madeup.txt",
|
||||
lambda route: asyncio.create_task(
|
||||
route.fulfill(status=200, body="fulfilled one")
|
||||
),
|
||||
times=1,
|
||||
)
|
||||
await context.route(
|
||||
"**/madeup.txt", lambda route: asyncio.create_task(route.fallback()), times=1
|
||||
)
|
||||
|
||||
resp = await page.goto(server.PREFIX + "/madeup.txt")
|
||||
assert resp
|
||||
body = await resp.body()
|
||||
assert body == b"fulfilled one"
|
||||
|
||||
|
||||
async def test_should_fall_back_after_exception(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.route("**/empty.html", lambda route: route.continue_())
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
try:
|
||||
await route.fulfill(response=cast(Any, {}))
|
||||
except Exception:
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", handler)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_amend_http_headers(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
values = []
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
values.append(route.request.headers.get("foo"))
|
||||
values.append(await route.request.header_value("FOO"))
|
||||
await route.continue_()
|
||||
|
||||
await context.route("**/sleep.zzz", handler)
|
||||
|
||||
async def handler_with_header_mods(route: Route) -> None:
|
||||
await route.fallback(headers={**route.request.headers, "FOO": "bar"})
|
||||
|
||||
await context.route("**/*", handler_with_header_mods)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
await page.evaluate("() => fetch('/sleep.zzz')")
|
||||
values.append(server_request_info.value.getHeader("foo"))
|
||||
assert values == ["bar", "bar", "bar"]
|
||||
|
||||
|
||||
async def test_should_delete_header_with_undefined_value(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await 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 = []
|
||||
|
||||
async def capture_and_continue(route: Route, request: Request) -> None:
|
||||
intercepted_request.append(request)
|
||||
await route.continue_()
|
||||
|
||||
await context.route("**/*", capture_and_continue)
|
||||
|
||||
async def delete_foo_header(route: Route, request: Request) -> None:
|
||||
headers = await request.all_headers()
|
||||
del headers["foo"]
|
||||
await route.fallback(headers=headers)
|
||||
|
||||
await context.route(server.PREFIX + "/something", delete_foo_header)
|
||||
|
||||
[server_req, text] = await asyncio.gather(
|
||||
server.wait_for_request("/something"),
|
||||
page.evaluate(
|
||||
"""
|
||||
async url => {
|
||||
const data = await fetch(url, {
|
||||
headers: {
|
||||
foo: 'a',
|
||||
bar: 'b',
|
||||
}
|
||||
});
|
||||
return data.text();
|
||||
}
|
||||
""",
|
||||
server.PREFIX + "/something",
|
||||
),
|
||||
)
|
||||
|
||||
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"
|
||||
|
||||
|
||||
async def test_should_amend_method(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
method = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
method.append(route.request.method)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route("**/*", _handler1)
|
||||
await context.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fallback(method="POST"))
|
||||
)
|
||||
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("() => fetch('/sleep.zzz')"),
|
||||
)
|
||||
|
||||
assert method == ["POST"]
|
||||
assert request.method == b"POST"
|
||||
|
||||
|
||||
async def test_should_override_request_url(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
url = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
url.append(route.request.url)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route(
|
||||
"**/global-var.html",
|
||||
_handler1,
|
||||
)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
asyncio.create_task(route.fallback(url=server.PREFIX + "/global-var.html"))
|
||||
|
||||
await context.route(
|
||||
"**/foo",
|
||||
_handler2,
|
||||
)
|
||||
|
||||
[server_request, response, _] = await asyncio.gather(
|
||||
server.wait_for_request("/global-var.html"),
|
||||
page.wait_for_event("response"),
|
||||
page.goto(server.PREFIX + "/foo"),
|
||||
)
|
||||
|
||||
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 await page.evaluate("() => window['globalVar']") == 123
|
||||
assert server_request.uri == b"/global-var.html"
|
||||
assert server_request.method == b"GET"
|
||||
|
||||
|
||||
async def test_should_amend_post_data(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
post_data = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
post_data.append(route.request.post_data)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route("**/*", _handler1)
|
||||
await context.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fallback(post_data="doggo"))
|
||||
)
|
||||
[server_request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
assert post_data == ["doggo"]
|
||||
assert server_request.post_body == b"doggo"
|
||||
|
||||
|
||||
async def test_should_amend_binary_post_data(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
post_data_buffer = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
post_data_buffer.append(route.request.post_data)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route("**/*", _handler1)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
asyncio.create_task(route.fallback(post_data=b"\x00\x01\x02\x03\x04"))
|
||||
|
||||
await context.route("**/*", _handler2)
|
||||
|
||||
[server_request, result] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
# 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"
|
||||
@@ -0,0 +1,194 @@
|
||||
# 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 pathlib import Path
|
||||
|
||||
import pytest
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.async_api import BrowserContext, Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_fulfill_intercepted_response(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(
|
||||
response=response,
|
||||
status=201,
|
||||
headers={"foo": "bar"},
|
||||
content_type="text/plain",
|
||||
body="Yo, page!",
|
||||
)
|
||||
|
||||
await context.route("**/*", handle)
|
||||
response = await 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 await page.evaluate("() => document.body.textContent") == "Yo, page!"
|
||||
|
||||
|
||||
async def test_should_fulfill_response_with_empty_body(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(
|
||||
response=response, status=201, body="", headers={"content-length": "0"}
|
||||
)
|
||||
|
||||
await context.route("**/*", handle)
|
||||
response = await page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == ""
|
||||
|
||||
|
||||
async 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)
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
await page.request.fetch(route.request)
|
||||
await route.fulfill(status=201)
|
||||
|
||||
await context.route("**/*", handle)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == ""
|
||||
if browser_name == "webkit":
|
||||
assert response.headers == {"content-type": "text/plain"}
|
||||
else:
|
||||
assert response.headers == {}
|
||||
|
||||
|
||||
async 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 = await page.request.get(server.PREFIX + "/sample")
|
||||
await context.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(
|
||||
response=sample_response, status=201, content_type="text/plain"
|
||||
),
|
||||
)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == "Woo-hoo"
|
||||
assert response.headers["foo"] == "bar"
|
||||
|
||||
|
||||
async def test_should_support_fulfill_after_intercept(
|
||||
page: Page, context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
request_future = asyncio.create_task(server.wait_for_request("/title.html"))
|
||||
|
||||
async def handle_route(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(response=response)
|
||||
|
||||
await context.route("**", handle_route)
|
||||
response = await page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
request = await request_future
|
||||
assert request.uri.decode() == "/title.html"
|
||||
original = (assetdir / "title.html").read_text()
|
||||
assert await response.text() == original
|
||||
|
||||
|
||||
async def test_should_give_access_to_the_intercepted_response(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_task: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await context.route("**/title.html", lambda route: route_task.set_result(route))
|
||||
|
||||
eval_task = asyncio.create_task(
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + "/title.html")
|
||||
)
|
||||
|
||||
route = await route_task
|
||||
response = await page.request.fetch(route.request)
|
||||
|
||||
assert response.status == 200
|
||||
assert response.status_text == "OK"
|
||||
assert response.ok is True
|
||||
assert response.url.endswith("/title.html") is True
|
||||
assert response.headers["content-type"] == "text/html; charset=utf-8"
|
||||
assert list(
|
||||
filter(
|
||||
lambda header: header["name"].lower() == "content-type",
|
||||
response.headers_array,
|
||||
)
|
||||
) == [{"name": "Content-Type", "value": "text/html; charset=utf-8"}]
|
||||
|
||||
await asyncio.gather(
|
||||
route.fulfill(response=response),
|
||||
eval_task,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_give_access_to_the_intercepted_response_body(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_task: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await context.route("**/simple.json", lambda route: route_task.set_result(route))
|
||||
|
||||
eval_task = asyncio.create_task(
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + "/simple.json")
|
||||
)
|
||||
|
||||
route = await route_task
|
||||
response = await page.request.fetch(route.request)
|
||||
|
||||
assert await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
await asyncio.gather(
|
||||
route.fulfill(response=response),
|
||||
eval_task,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_show_exception_after_fulfill(page: Page, server: Server) -> None:
|
||||
async def _handle(route: Route) -> None:
|
||||
await route.continue_()
|
||||
raise Exception("Exception text!?")
|
||||
|
||||
await page.route("*/**", _handle)
|
||||
await 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!?"):
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
@@ -0,0 +1,516 @@
|
||||
# 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
|
||||
import re
|
||||
from typing import Awaitable, Callable, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
Error,
|
||||
Page,
|
||||
Request,
|
||||
Route,
|
||||
expect,
|
||||
)
|
||||
from tests.server import Server, TestServerRequest
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_route_should_intercept(context: BrowserContext, server: Server) -> None:
|
||||
intercepted = []
|
||||
|
||||
def handle(route: Route, request: Request) -> None:
|
||||
intercepted.append(True)
|
||||
assert "empty.html" in request.url
|
||||
assert request.headers["user-agent"]
|
||||
assert request.method == "GET"
|
||||
assert request.post_data is None
|
||||
assert request.is_navigation_request()
|
||||
assert request.resource_type == "document"
|
||||
assert request.frame == page.main_frame
|
||||
assert request.frame.url == "about:blank"
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route("**/empty.html", lambda route, request: handle(route, request))
|
||||
page = await context.new_page()
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
assert intercepted == [True]
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_route_should_unroute(context: BrowserContext, server: Server) -> None:
|
||||
page = await context.new_page()
|
||||
|
||||
intercepted: List[int] = []
|
||||
|
||||
def handler(route: Route, request: Request, ordinal: int) -> None:
|
||||
intercepted.append(ordinal)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await context.route("**/*", lambda route, request: handler(route, request, 1))
|
||||
await context.route(
|
||||
"**/empty.html", lambda route, request: handler(route, request, 2)
|
||||
)
|
||||
await context.route(
|
||||
"**/empty.html", lambda route, request: handler(route, request, 3)
|
||||
)
|
||||
|
||||
def handler4(route: Route, request: Request) -> None:
|
||||
handler(route, request, 4)
|
||||
|
||||
await context.route(re.compile("empty.html"), handler4)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [4]
|
||||
|
||||
intercepted = []
|
||||
await context.unroute(re.compile("empty.html"), handler4)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3]
|
||||
|
||||
intercepted = []
|
||||
await context.unroute("**/empty.html")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [1]
|
||||
|
||||
|
||||
async def test_route_should_yield_to_page_route(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route, request: asyncio.create_task(
|
||||
route.fulfill(status=200, body="context")
|
||||
),
|
||||
)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.route(
|
||||
"**/empty.html",
|
||||
lambda route, request: asyncio.create_task(
|
||||
route.fulfill(status=200, body="page")
|
||||
),
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
assert await response.text() == "page"
|
||||
|
||||
|
||||
async def test_route_should_fall_back_to_context_route(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route, request: asyncio.create_task(
|
||||
route.fulfill(status=200, body="context")
|
||||
),
|
||||
)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.route(
|
||||
"**/non-empty.html",
|
||||
lambda route, request: asyncio.create_task(
|
||||
route.fulfill(status=200, body="page")
|
||||
),
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
assert await response.text() == "context"
|
||||
|
||||
|
||||
async def test_should_support_set_cookie_header(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]",
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
context = await context_factory()
|
||||
page = await context.new_page()
|
||||
await page.route(
|
||||
"https://example.com/",
|
||||
lambda route: route.fulfill(
|
||||
headers={
|
||||
"Set-Cookie": "name=value; domain=.example.com; Path=/",
|
||||
},
|
||||
content_type="text/html",
|
||||
body="done",
|
||||
),
|
||||
)
|
||||
await page.goto("https://example.com")
|
||||
cookies = await context.cookies()
|
||||
assert len(cookies) == 1
|
||||
assert cookies[0] == {
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
"name": "name",
|
||||
"value": "value",
|
||||
"domain": ".example.com",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("webkit")
|
||||
async def test_should_ignore_secure_set_cookie_header_for_insecure_request(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]",
|
||||
) -> None:
|
||||
context = await context_factory()
|
||||
page = await context.new_page()
|
||||
await page.route(
|
||||
"http://example.com/",
|
||||
lambda route: route.fulfill(
|
||||
headers={
|
||||
"Set-Cookie": "name=value; domain=.example.com; Path=/; Secure",
|
||||
},
|
||||
content_type="text/html",
|
||||
body="done",
|
||||
),
|
||||
)
|
||||
await page.goto("http://example.com")
|
||||
cookies = await context.cookies()
|
||||
assert len(cookies) == 0
|
||||
|
||||
|
||||
async def test_should_use_set_cookie_header_in_future_requests(
|
||||
context_factory: "Callable[..., Awaitable[BrowserContext]]",
|
||||
server: Server,
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
context = await context_factory()
|
||||
page = await context.new_page()
|
||||
|
||||
await page.route(
|
||||
server.EMPTY_PAGE,
|
||||
lambda route: route.fulfill(
|
||||
headers={
|
||||
"Set-Cookie": "name=value",
|
||||
},
|
||||
content_type="text/html",
|
||||
body="done",
|
||||
),
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert await context.cookies() == [
|
||||
{
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
"name": "name",
|
||||
"value": "value",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
}
|
||||
]
|
||||
|
||||
cookie = ""
|
||||
|
||||
def _handle_request(request: TestServerRequest) -> None:
|
||||
nonlocal cookie
|
||||
cookie = must(request.getHeader("cookie"))
|
||||
request.finish()
|
||||
|
||||
server.set_route("/foo.html", _handle_request)
|
||||
await page.goto(server.PREFIX + "/foo.html")
|
||||
assert cookie == "name=value"
|
||||
|
||||
|
||||
async def test_should_work_with_ignore_https_errors(
|
||||
browser: Browser, https_server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(ignore_https_errors=True)
|
||||
page = await context.new_page()
|
||||
|
||||
await page.route("**/*", lambda route: route.continue_())
|
||||
response = await page.goto(https_server.EMPTY_PAGE)
|
||||
assert must(response).status == 200
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_support_the_times_parameter_with_route_matching(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted: List[int] = []
|
||||
|
||||
async def _handle_request(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
await route.continue_()
|
||||
|
||||
await context.route("**/empty.html", _handle_request, times=1)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(intercepted) == 1
|
||||
|
||||
|
||||
async def test_should_work_if_handler_with_times_parameter_was_removed_from_another_handler(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
async def _handler(route: Route) -> None:
|
||||
intercepted.append("first")
|
||||
await route.continue_()
|
||||
|
||||
await context.route("**/*", _handler, times=1)
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
intercepted.append("second")
|
||||
await context.unroute("**/*", _handler)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/*", _handler2)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == ["second"]
|
||||
intercepted.clear()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == ["second"]
|
||||
|
||||
|
||||
async def test_should_support_async_handler_with_times(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
async def _handler(route: Route) -> None:
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fulfill(
|
||||
body="<html>intercepted</html>",
|
||||
content_type="text/html",
|
||||
)
|
||||
|
||||
await context.route("**/empty.html", _handler, times=1)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await expect(page.locator("body")).to_have_text("intercepted")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await expect(page.locator("body")).not_to_have_text("intercepted")
|
||||
|
||||
|
||||
async def test_should_override_post_body_with_empty_string(
|
||||
context: BrowserContext, server: Server, page: Page
|
||||
) -> None:
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.continue_(
|
||||
post_data="",
|
||||
),
|
||||
)
|
||||
|
||||
req = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.set_content(
|
||||
"""
|
||||
<script>
|
||||
(async () => {
|
||||
await fetch('%s', {
|
||||
method: 'POST',
|
||||
body: 'original',
|
||||
});
|
||||
})()
|
||||
</script>
|
||||
"""
|
||||
% server.EMPTY_PAGE
|
||||
),
|
||||
)
|
||||
|
||||
assert req[0].post_body == b""
|
||||
|
||||
|
||||
async def test_should_chain_fallback(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted: List[int] = []
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler1)
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler2)
|
||||
|
||||
async def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler3)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_chain_fallback_with_dynamic_url(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted: List[int] = []
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
await route.fallback(url=server.EMPTY_PAGE)
|
||||
|
||||
await context.route("**/bar", _handler1)
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
await route.fallback(url="http://localhost/bar")
|
||||
|
||||
await context.route("**/foo", _handler2)
|
||||
|
||||
async def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
await route.fallback(url="http://localhost/foo")
|
||||
|
||||
await context.route("**/empty.html", _handler3)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_not_chain_fulfill(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
failed = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
await context.route("**/empty.html", handler)
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route: asyncio.create_task(route.fulfill(status=200, body="fulfilled")),
|
||||
)
|
||||
await context.route(
|
||||
"**/empty.html", lambda route: asyncio.create_task(route.fallback())
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
body = await response.body()
|
||||
assert body == b"fulfilled"
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
async 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
|
||||
|
||||
await context.route("**/empty.html", handler)
|
||||
await context.route(
|
||||
"**/empty.html", lambda route: asyncio.create_task(route.abort())
|
||||
)
|
||||
await context.route(
|
||||
"**/empty.html", lambda route: asyncio.create_task(route.fallback())
|
||||
)
|
||||
|
||||
with pytest.raises(Error) as excinfo:
|
||||
await 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]
|
||||
|
||||
|
||||
async def test_should_chain_fallback_into_page(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route("**/empty.html", _handler1)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route("**/empty.html", _handler2)
|
||||
|
||||
def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await context.route("**/empty.html", _handler3)
|
||||
|
||||
def _handler4(route: Route) -> None:
|
||||
intercepted.append(4)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler4)
|
||||
|
||||
def _handler5(route: Route) -> None:
|
||||
intercepted.append(5)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler5)
|
||||
|
||||
def _handler6(route: Route) -> None:
|
||||
intercepted.append(6)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler6)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [6, 5, 4, 3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_fall_back_async(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler1)
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler2)
|
||||
|
||||
async def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fallback()
|
||||
|
||||
await context.route("**/empty.html", _handler3)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
@@ -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.async_api import Browser
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_allow_service_workers_by_default(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
|
||||
await page.evaluate("() => window.activationPromise")
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_block_blocks_service_worker_registration(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(service_workers="block")
|
||||
page = await context.new_page()
|
||||
async with page.expect_console_message(
|
||||
lambda m: "Service Worker registration blocked by Playwright" == m.text
|
||||
):
|
||||
await page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
|
||||
await context.close()
|
||||
@@ -0,0 +1,221 @@
|
||||
# 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
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Page, StorageState
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_capture_local_storage(context: BrowserContext) -> None:
|
||||
page1 = await context.new_page()
|
||||
await page1.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fulfill(body="<html></html>"))
|
||||
)
|
||||
await page1.goto("https://www.example.com")
|
||||
await page1.evaluate("localStorage['name1'] = 'value1'")
|
||||
await page1.goto("https://www.domain.com")
|
||||
await page1.evaluate("localStorage['name2'] = 'value2'")
|
||||
|
||||
state = await context.storage_state()
|
||||
origins = state["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"}],
|
||||
}
|
||||
|
||||
|
||||
async 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 = await browser.new_context(storage_state=storage_state)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fulfill(body="<html></html>"))
|
||||
)
|
||||
await page.goto("https://www.example.com")
|
||||
local_storage = await page.evaluate("window.localStorage")
|
||||
assert local_storage == {"name1": "value1"}
|
||||
|
||||
indexed_db = await 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"
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_round_trip_through_the_file(
|
||||
browser: Browser, context: BrowserContext, tmp_path: Path
|
||||
) -> None:
|
||||
page1 = await context.new_page()
|
||||
await page1.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.fulfill(body="<html></html>")),
|
||||
)
|
||||
await page1.goto("https://www.example.com")
|
||||
await page1.evaluate(
|
||||
"""() => {
|
||||
localStorage["name1"] = "value1"
|
||||
document.cookie = "username=John Doe"
|
||||
return document.cookie
|
||||
}"""
|
||||
)
|
||||
|
||||
path = tmp_path / "storage-state.json"
|
||||
state = await context.storage_state(path=path)
|
||||
with open(path, "r") as f:
|
||||
written = json.load(f)
|
||||
assert state == written
|
||||
|
||||
context2 = await browser.new_context(storage_state=path)
|
||||
page2 = await context2.new_page()
|
||||
await page2.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.fulfill(body="<html></html>")),
|
||||
)
|
||||
await page2.goto("https://www.example.com")
|
||||
local_storage = await page2.evaluate("window.localStorage")
|
||||
assert local_storage == {"name1": "value1"}
|
||||
cookie = await page2.evaluate("document.cookie")
|
||||
assert cookie == "username=John Doe"
|
||||
await context2.close()
|
||||
|
||||
|
||||
async def test_set_storage_state_should_apply_state_to_existing_context(
|
||||
browser: Browser, browser_channel: Optional[str]
|
||||
) -> None:
|
||||
if browser_channel and browser_channel.startswith("msedge"):
|
||||
pytest.skip("Network.clearBrowserCache sometimes stalls on msedge")
|
||||
src = await browser.new_context()
|
||||
src_page = await src.new_page()
|
||||
await src_page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.fulfill(body="<html></html>")),
|
||||
)
|
||||
await src_page.goto("https://www.example.com")
|
||||
await src_page.evaluate('() => localStorage.setItem("k", "v")')
|
||||
state = await src.storage_state()
|
||||
await src.close()
|
||||
|
||||
dst = await browser.new_context()
|
||||
dst_page = await dst.new_page()
|
||||
await dst_page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.fulfill(body="<html></html>")),
|
||||
)
|
||||
await dst.set_storage_state(state)
|
||||
await dst_page.goto("https://www.example.com")
|
||||
assert await dst_page.evaluate('() => localStorage.getItem("k")') == "v"
|
||||
await dst.close()
|
||||
|
||||
|
||||
async def test_should_serialiser_storage_state_with_lone_surrogates(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""chars => window.localStorage.setItem('foo', String.fromCharCode(55934))"""
|
||||
)
|
||||
storage_state = await context.storage_state()
|
||||
# 65533 is the Unicode replacement character
|
||||
assert storage_state["origins"][0]["localStorage"][0]["value"] == chr(65533)
|
||||
|
||||
|
||||
async def test_should_serialise_indexed_db(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await 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 await page.context.storage_state() == {"cookies": [], "origins": []}
|
||||
assert await 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,478 @@
|
||||
# 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
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import AsyncContextManager, Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserType, Error, Playwright, Route, expect
|
||||
from tests.conftest import RemoteServer
|
||||
from tests.server import Server, TestServerRequest, WebSocketProtocol
|
||||
from tests.utils import chromium_version_less_than
|
||||
|
||||
from .conftest import TraceViewerPage
|
||||
|
||||
|
||||
async def test_should_print_custom_ws_close_error(
|
||||
server: Server, browser_type: BrowserType
|
||||
) -> None:
|
||||
def _handle_ws(ws: WebSocketProtocol) -> None:
|
||||
def _onMessage(payload: bytes, isBinary: bool) -> None:
|
||||
ws.sendClose(code=4123, reason="Oh my!")
|
||||
|
||||
setattr(ws, "onMessage", _onMessage)
|
||||
|
||||
server.once_web_socket_connection(_handle_ws)
|
||||
with pytest.raises(Error, match="Oh my!"):
|
||||
await browser_type.connect(f"ws://localhost:{server.PORT}/ws")
|
||||
|
||||
|
||||
async 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 = await browser_type.connect(remote_server.ws_endpoint)
|
||||
browser_context = await browser.new_context()
|
||||
assert len(browser_context.pages) == 0
|
||||
page = await browser_context.new_page()
|
||||
assert len(browser_context.pages) == 1
|
||||
assert await page.evaluate("11 * 11") == 121
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await browser.close()
|
||||
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
browser_context = await browser.new_context()
|
||||
page = await browser_context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await browser.close()
|
||||
|
||||
|
||||
async 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 = await browser_type.connect(remote_server.ws_endpoint)
|
||||
assert len(browser1.contexts) == 0
|
||||
await browser1.new_context()
|
||||
assert len(browser1.contexts) == 1
|
||||
|
||||
browser2 = await browser_type.connect(remote_server.ws_endpoint)
|
||||
assert len(browser2.contexts) == 0
|
||||
await browser2.new_context()
|
||||
assert len(browser2.contexts) == 1
|
||||
assert len(browser1.contexts) == 1
|
||||
|
||||
await browser1.close()
|
||||
page2 = await browser2.new_page()
|
||||
# original browser should still work
|
||||
assert await page2.evaluate("7 * 6") == 42
|
||||
|
||||
await browser2.close()
|
||||
|
||||
|
||||
async 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 = await browser_type.connect(remote.ws_endpoint)
|
||||
browser2 = await browser_type.connect(remote.ws_endpoint)
|
||||
|
||||
disconnected1 = []
|
||||
disconnected2 = []
|
||||
browser1.on("disconnected", lambda _: disconnected1.append(True))
|
||||
browser2.on("disconnected", lambda _: disconnected2.append(True))
|
||||
|
||||
page2 = await browser2.new_page()
|
||||
|
||||
await 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.
|
||||
await page2.title()
|
||||
assert len(disconnected2) == 1
|
||||
|
||||
|
||||
async def test_browser_type_connect_disconnected_event_should_be_emitted_when_remote_killed_connection(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
# Launch another server to not affect other tests.
|
||||
remote = launch_server()
|
||||
|
||||
browser = await browser_type.connect(remote.ws_endpoint)
|
||||
|
||||
disconnected = []
|
||||
browser.on("disconnected", lambda _: disconnected.append(True))
|
||||
page = await browser.new_page()
|
||||
remote.kill()
|
||||
with pytest.raises(Error):
|
||||
await page.title()
|
||||
assert len(disconnected) == 1
|
||||
|
||||
|
||||
async def test_browser_type_disconnected_event_should_have_browser_as_argument(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
event_payloads = []
|
||||
browser.on("disconnected", lambda b: event_payloads.append(b))
|
||||
await browser.close()
|
||||
assert event_payloads[0] == browser
|
||||
|
||||
|
||||
async def test_browser_type_connect_set_browser_connected_state(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
assert browser.is_connected()
|
||||
await browser.close()
|
||||
assert browser.is_connected() is False
|
||||
|
||||
|
||||
async 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 = await browser_type.connect(remote_server.ws_endpoint)
|
||||
page = await browser.new_page()
|
||||
|
||||
remote_server.kill()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.evaluate("1 + 1")
|
||||
assert "has been closed" in exc_info.value.message
|
||||
assert browser.is_connected() is False
|
||||
|
||||
|
||||
async def test_browser_type_connect_should_reject_navigation_when_browser_closes(
|
||||
server: Server, browser_type: BrowserType, launch_server: Callable[[], RemoteServer]
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
page = await browser.new_page()
|
||||
await browser.close()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
assert "has been closed" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_not_allow_getting_the_path(
|
||||
browser_type: BrowserType, launch_server: Callable[[], RemoteServer], server: Server
|
||||
) -> None:
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.setHeader("Content-Disposition", "attachment")
|
||||
request.write(b"Hello world")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/download", handle_download)
|
||||
|
||||
remote_server = launch_server()
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
with pytest.raises(Error) as exc:
|
||||
await download.path()
|
||||
assert (
|
||||
exc.value.message
|
||||
== "Path is not available when using browser_type.connect(). Use save_as() to save a local copy."
|
||||
)
|
||||
remote_server.kill()
|
||||
|
||||
|
||||
async def test_prevent_getting_video_path(
|
||||
browser_type: BrowserType,
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
tmp_path: Path,
|
||||
server: Server,
|
||||
) -> None:
|
||||
remote_server = launch_server()
|
||||
browser = await browser_type.connect(remote_server.ws_endpoint)
|
||||
page = await browser.new_page(record_video_dir=tmp_path)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await browser.close()
|
||||
assert page.video
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.video.path()
|
||||
assert (
|
||||
exc.value.message
|
||||
== "Path is not available when using browserType.connect(). Use save_as() to save a local copy."
|
||||
)
|
||||
remote_server.kill()
|
||||
|
||||
|
||||
async 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:
|
||||
await browser_type.connect(remote_server.ws_endpoint)
|
||||
assert "WebSocket error: " in exc.value.message
|
||||
|
||||
|
||||
async def test_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 = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
async def handle_request(route: Route) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
response = await request.get(server.PREFIX + "/simple.json")
|
||||
await route.fulfill(response=response)
|
||||
await request.dispose()
|
||||
|
||||
await page.route("**/*", handle_request)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert await response.json() == {"foo": "bar"}
|
||||
|
||||
remote.kill()
|
||||
|
||||
|
||||
async def test_should_upload_large_file(
|
||||
browser_type: BrowserType,
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
remote = launch_server()
|
||||
|
||||
browser = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
await page.goto(server.PREFIX + "/input/fileupload.html")
|
||||
large_file_path = tmp_path / "200MB.zip"
|
||||
data = b"A" * 1024
|
||||
with large_file_path.open("wb") as f:
|
||||
for i in range(0, 200 * 1024 * 1024, len(data)):
|
||||
f.write(data)
|
||||
input = page.locator('input[type="file"]')
|
||||
events = await input.evaluate_handle(
|
||||
"""
|
||||
e => {
|
||||
const events = [];
|
||||
e.addEventListener('input', () => events.push('input'));
|
||||
e.addEventListener('change', () => events.push('change'));
|
||||
return events;
|
||||
}
|
||||
"""
|
||||
)
|
||||
|
||||
await input.set_input_files(large_file_path)
|
||||
assert await input.evaluate("e => e.files[0].name") == "200MB.zip"
|
||||
assert await events.evaluate("e => e") == ["input", "change"]
|
||||
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/upload"),
|
||||
page.click("input[type=submit]", timeout=60_000),
|
||||
)
|
||||
|
||||
contents = request.args[b"file1"][0]
|
||||
assert len(contents) == 200 * 1024 * 1024
|
||||
assert contents[:1024] == data
|
||||
# flake8: noqa: E203
|
||||
assert contents[len(contents) - 1024 :] == data
|
||||
assert request.post_body
|
||||
match = re.search(
|
||||
rb'^.*Content-Disposition: form-data; name="(?P<name>.*)"; filename="(?P<filename>.*)".*$',
|
||||
request.post_body,
|
||||
re.MULTILINE,
|
||||
)
|
||||
assert match
|
||||
assert match.group("name") == b"file1"
|
||||
assert match.group("filename") == b"200MB.zip"
|
||||
|
||||
|
||||
async def test_should_record_trace_with_source(
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
browser_type: BrowserType,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
remote = launch_server()
|
||||
browser = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
await context.tracing.start(sources=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<button>Click</button>")
|
||||
await page.click("'Click'")
|
||||
path = tmp_path / "trace1.zip"
|
||||
await context.tracing.stop(path=path)
|
||||
|
||||
await context.close()
|
||||
await browser.close()
|
||||
|
||||
async with show_trace_viewer(path) as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
]
|
||||
)
|
||||
await trace_viewer.show_source_tab()
|
||||
await expect(trace_viewer.stack_frames).to_contain_text(
|
||||
[
|
||||
re.compile(r"test_should_record_trace_with_source"),
|
||||
]
|
||||
)
|
||||
await trace_viewer.select_action("Set content")
|
||||
# Check that the source file is shown
|
||||
await expect(
|
||||
trace_viewer.page.locator(".source-tab-file-name")
|
||||
).to_have_attribute("title", re.compile(r".*test_browsertype_connect\.py"))
|
||||
await expect(trace_viewer.page.locator(".source-line-running")).to_contain_text(
|
||||
'page.set_content("<button>Click</button>")'
|
||||
)
|
||||
|
||||
|
||||
async def test_should_record_trace_with_relative_trace_path(
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
server: Server,
|
||||
browser_type: BrowserType,
|
||||
) -> None:
|
||||
remote = launch_server()
|
||||
browser = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
await context.tracing.start(sources=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<button>Click</button>")
|
||||
await page.click("'Click'")
|
||||
try:
|
||||
await context.tracing.stop(path="trace1.zip")
|
||||
|
||||
await context.close()
|
||||
await browser.close()
|
||||
|
||||
# make sure trace1.zip exists
|
||||
assert Path("trace1.zip").exists()
|
||||
finally:
|
||||
Path("trace1.zip").unlink()
|
||||
|
||||
|
||||
async 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 = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
await page.set_content("<input type=file multiple=true/>")
|
||||
input = page.locator("input")
|
||||
files = ["file-to-upload.txt", "file-to-upload-2.txt"]
|
||||
await input.set_input_files([assetdir / file for file in files])
|
||||
assert await input.evaluate("input => [...input.files].map(f => f.name)") == files
|
||||
timestamps = await 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
|
||||
|
||||
|
||||
async def test_should_upload_a_folder(
|
||||
browser_type: BrowserType,
|
||||
launch_server: Callable[[], RemoteServer],
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
browser_name: str,
|
||||
browser_version: str,
|
||||
headless: bool,
|
||||
) -> None:
|
||||
remote = launch_server()
|
||||
|
||||
browser = await browser_type.connect(remote.ws_endpoint)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/input/folderupload.html")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
dir = tmp_path / "file-upload-test"
|
||||
dir.mkdir()
|
||||
(dir / "file1.txt").write_text("file1 content")
|
||||
(dir / "file2").write_text("file2 content")
|
||||
(dir / "sub-dir").mkdir()
|
||||
(dir / "sub-dir" / "really.txt").write_text("sub-dir file content")
|
||||
await input.set_input_files(dir)
|
||||
assert set(
|
||||
await input.evaluate("e => [...e.files].map(f => f.webkitRelativePath)")
|
||||
) == set(
|
||||
[
|
||||
"file-upload-test/file1.txt",
|
||||
"file-upload-test/file2",
|
||||
# https://issues.chromium.org/issues/345393164
|
||||
*(
|
||||
[]
|
||||
if browser_name == "chromium"
|
||||
and headless
|
||||
and chromium_version_less_than(browser_version, "127.0.6533.0")
|
||||
else ["file-upload-test/sub-dir/really.txt"]
|
||||
),
|
||||
]
|
||||
)
|
||||
webkit_relative_paths = await input.evaluate(
|
||||
"e => [...e.files].map(f => f.webkitRelativePath)"
|
||||
)
|
||||
for i, webkit_relative_path in enumerate(webkit_relative_paths):
|
||||
content = await input.evaluate(
|
||||
"""(e, i) => {
|
||||
const reader = new FileReader();
|
||||
const promise = new Promise(fulfill => reader.onload = fulfill);
|
||||
reader.readAsText(e.files[i]);
|
||||
return promise.then(() => reader.result);
|
||||
}""",
|
||||
i,
|
||||
)
|
||||
assert content == (dir / ".." / webkit_relative_path).read_text()
|
||||
@@ -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 asyncio
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from playwright.async_api import BrowserType, Error
|
||||
from tests.server import Server, WebSocketProtocol, find_free_port
|
||||
|
||||
pytestmark = pytest.mark.only_browser("chromium")
|
||||
|
||||
|
||||
async def test_connect_to_an_existing_cdp_session(
|
||||
launch_arguments: Dict, browser_type: BrowserType
|
||||
) -> None:
|
||||
port = find_free_port()
|
||||
browser_server = await browser_type.launch(
|
||||
**launch_arguments, args=[f"--remote-debugging-port={port}"]
|
||||
)
|
||||
cdp_browser = await browser_type.connect_over_cdp(f"http://127.0.0.1:{port}")
|
||||
assert len(cdp_browser.contexts) == 1
|
||||
await cdp_browser.close()
|
||||
await browser_server.close()
|
||||
|
||||
|
||||
async def test_connect_to_an_existing_cdp_session_twice(
|
||||
launch_arguments: Dict, browser_type: BrowserType, server: Server
|
||||
) -> None:
|
||||
port = find_free_port()
|
||||
browser_server = await browser_type.launch(
|
||||
**launch_arguments, args=[f"--remote-debugging-port={port}"]
|
||||
)
|
||||
endpoint_url = f"http://127.0.0.1:{port}"
|
||||
cdp_browser1 = await browser_type.connect_over_cdp(endpoint_url)
|
||||
cdp_browser2 = await browser_type.connect_over_cdp(endpoint_url)
|
||||
assert len(cdp_browser1.contexts) == 1
|
||||
page1 = await cdp_browser1.contexts[0].new_page()
|
||||
await page1.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert len(cdp_browser2.contexts) == 1
|
||||
page2 = await cdp_browser2.contexts[0].new_page()
|
||||
await page2.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert len(cdp_browser1.contexts[0].pages) == 2
|
||||
assert len(cdp_browser2.contexts[0].pages) == 2
|
||||
|
||||
await cdp_browser1.close()
|
||||
await cdp_browser2.close()
|
||||
await browser_server.close()
|
||||
|
||||
|
||||
def _ws_endpoint_from_url(url: str) -> str:
|
||||
response = requests.get(url)
|
||||
assert response.ok
|
||||
response_body = response.json()
|
||||
return response_body["webSocketDebuggerUrl"]
|
||||
|
||||
|
||||
async def test_conect_over_a_ws_endpoint(
|
||||
launch_arguments: Dict, browser_type: BrowserType, server: Server
|
||||
) -> None:
|
||||
port = find_free_port()
|
||||
browser_server = await browser_type.launch(
|
||||
**launch_arguments, args=[f"--remote-debugging-port={port}"]
|
||||
)
|
||||
ws_endpoint = _ws_endpoint_from_url(f"http://127.0.0.1:{port}/json/version/")
|
||||
|
||||
cdp_browser1 = await browser_type.connect_over_cdp(ws_endpoint)
|
||||
assert len(cdp_browser1.contexts) == 1
|
||||
await cdp_browser1.close()
|
||||
|
||||
cdp_browser2 = await browser_type.connect_over_cdp(ws_endpoint)
|
||||
assert len(cdp_browser2.contexts) == 1
|
||||
await cdp_browser2.close()
|
||||
await browser_server.close()
|
||||
|
||||
|
||||
async def test_connect_over_cdp_passing_header_works(
|
||||
browser_type: BrowserType, server: Server
|
||||
) -> None:
|
||||
server.send_on_web_socket_connection(b"incoming")
|
||||
request = asyncio.create_task(server.wait_for_request("/ws"))
|
||||
with pytest.raises(Error):
|
||||
await browser_type.connect_over_cdp(
|
||||
f"ws://127.0.0.1:{server.PORT}/ws",
|
||||
headers={"foo": "bar"},
|
||||
timeout=5000,
|
||||
)
|
||||
assert (await request).getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_should_print_custom_ws_close_error(
|
||||
browser_type: BrowserType, server: Server
|
||||
) -> None:
|
||||
def _handle_ws(ws: WebSocketProtocol) -> None:
|
||||
def _onMessage(payload: bytes, isBinary: bool) -> None:
|
||||
ws.sendClose(code=4123, reason="Oh my!")
|
||||
|
||||
setattr(ws, "onMessage", _onMessage)
|
||||
|
||||
server.once_web_socket_connection(_handle_ws)
|
||||
with pytest.raises(Error, match="Browser logs:\n\nOh my!\n"):
|
||||
await browser_type.connect_over_cdp(
|
||||
f"ws://127.0.0.1:{server.PORT}/ws", headers={"foo": "bar"}
|
||||
)
|
||||
@@ -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.
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, Error, Page
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_work(page: Page) -> None:
|
||||
client = await page.context.new_cdp_session(page)
|
||||
events = []
|
||||
client.on("Runtime.consoleAPICalled", lambda params: events.append(params))
|
||||
await client.send("Runtime.enable")
|
||||
result = await client.send(
|
||||
"Runtime.evaluate",
|
||||
{"expression": "window.foo = 'bar'; console.log('log'); 'result'"},
|
||||
)
|
||||
assert result == {"result": {"type": "string", "value": "result"}}
|
||||
foo = await page.evaluate("() => window.foo")
|
||||
assert foo == "bar"
|
||||
assert events[0]["args"][0]["value"] == "log"
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_receive_events(page: Page, server: Server) -> None:
|
||||
client = await page.context.new_cdp_session(page)
|
||||
await client.send("Network.enable")
|
||||
events = []
|
||||
client.on("Network.requestWillBeSent", lambda event: events.append(event))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(events) == 1
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_be_able_to_detach_session(page: Page) -> None:
|
||||
client = await page.context.new_cdp_session(page)
|
||||
await client.send("Runtime.enable")
|
||||
eval_response = await client.send(
|
||||
"Runtime.evaluate", {"expression": "1 + 2", "returnByValue": True}
|
||||
)
|
||||
assert eval_response["result"]["value"] == 3
|
||||
await client.detach()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await client.send(
|
||||
"Runtime.evaluate", {"expression": "3 + 1", "returnByValue": True}
|
||||
)
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc_info.value.message
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_not_break_page_close(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
session = await page.context.new_cdp_session(page)
|
||||
await session.detach()
|
||||
await page.close()
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_detach_when_page_closes(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
session = await context.new_cdp_session(page)
|
||||
await page.close()
|
||||
with pytest.raises(Error):
|
||||
await session.detach()
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_work_with_main_frame(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
client = await context.new_cdp_session(page.main_frame)
|
||||
await client.send("Runtime.enable")
|
||||
await client.send(
|
||||
"Runtime.evaluate",
|
||||
{"expression": "window.foo = 'bar'"},
|
||||
)
|
||||
assert await page.evaluate("() => window.foo") == "bar"
|
||||
@@ -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.async_api import Page
|
||||
|
||||
|
||||
async def test_check_the_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
await page.check("input")
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_not_check_the_checked_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
await page.check("input")
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_uncheck_the_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
await page.uncheck("input")
|
||||
assert await page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
async def test_not_uncheck_the_unchecked_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
await page.uncheck("input")
|
||||
assert await page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
async def test_check_the_box_by_label(page: Page) -> None:
|
||||
await page.set_content(
|
||||
'<label for="checkbox"><input id="checkbox" type="checkbox"></input></label>'
|
||||
)
|
||||
await page.check("label")
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_check_the_box_outside_label(page: Page) -> None:
|
||||
await page.set_content(
|
||||
'<label for="checkbox">Text</label><div><input id="checkbox" type="checkbox"></input></div>'
|
||||
)
|
||||
await page.check("label")
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_check_the_box_inside_label_without_id(page: Page) -> None:
|
||||
await page.set_content(
|
||||
'<label>Text<span><input id="checkbox" type="checkbox"></input></span></label>'
|
||||
)
|
||||
await page.check("label")
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_check_radio(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<input type='radio'>one</input>
|
||||
<input id='two' type='radio'>two</input>
|
||||
<input type='radio'>three</input>"""
|
||||
)
|
||||
await page.check("#two")
|
||||
assert await page.evaluate("two.checked")
|
||||
|
||||
|
||||
async def test_check_the_box_by_aria_role(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""<div role='checkbox' id='checkbox'>CHECKBOX</div>
|
||||
<script>
|
||||
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true'))
|
||||
</script>"""
|
||||
)
|
||||
await page.check("div")
|
||||
assert await page.evaluate("checkbox.getAttribute ('aria-checked')")
|
||||
@@ -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 json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_output_a_trace(
|
||||
browser: Browser, page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
output_file = tmp_path / "trace.json"
|
||||
await browser.start_tracing(page=page, screenshots=True, path=output_file)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await browser.stop_tracing()
|
||||
assert os.path.getsize(output_file) > 0
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_create_directories_as_needed(
|
||||
browser: Browser, page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
output_file = tmp_path / "these" / "are" / "directories" / "trace.json"
|
||||
await browser.start_tracing(page=page, screenshots=True, path=output_file)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await browser.stop_tracing()
|
||||
assert os.path.getsize(output_file) > 0
|
||||
|
||||
|
||||
async def rafraf(target: Page, count: int = 1) -> None:
|
||||
for _ in range(count):
|
||||
await target.evaluate(
|
||||
"async () => await new Promise(f => window.requestAnimationFrame(() => window.requestAnimationFrame(f)));"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_run_with_custom_categories_if_provided(
|
||||
browser: Browser, page: Page, tmp_path: Path
|
||||
) -> None:
|
||||
output_file = tmp_path / "trace.json"
|
||||
await browser.start_tracing(
|
||||
page=page,
|
||||
path=output_file,
|
||||
categories=["disabled-by-default-cc.debug"],
|
||||
)
|
||||
await rafraf(page)
|
||||
await browser.stop_tracing()
|
||||
with open(output_file, mode="r") as of:
|
||||
trace_json = json.load(of)
|
||||
trace_config = trace_json["metadata"].get("trace-config")
|
||||
trace_events = trace_json["traceEvents"]
|
||||
assert (
|
||||
trace_config is not None and "disabled-by-default-cc.debug" in trace_config
|
||||
) or any(
|
||||
event.get("cat") == "disabled-by-default-cc.debug" for event in trace_events
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_throw_if_tracing_on_two_pages(
|
||||
browser: Browser, page: Page, tmp_path: Path
|
||||
) -> None:
|
||||
output_file_1 = tmp_path / "trace1.json"
|
||||
await browser.start_tracing(page=page, screenshots=True, path=output_file_1)
|
||||
output_file_2 = tmp_path / "trace2.json"
|
||||
with pytest.raises(Exception):
|
||||
await browser.start_tracing(page=page, screenshots=True, path=output_file_2)
|
||||
await browser.stop_tracing()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_return_a_buffer(
|
||||
browser: Browser, page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
output_file = tmp_path / "trace.json"
|
||||
await browser.start_tracing(page=page, path=output_file, screenshots=True)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
value = await browser.stop_tracing()
|
||||
with open(output_file, mode="r") as trace_file:
|
||||
assert trace_file.read() == value.decode()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_work_without_options(
|
||||
browser: Browser, page: Page, server: Server
|
||||
) -> None:
|
||||
await browser.start_tracing()
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
trace = await browser.stop_tracing()
|
||||
assert trace
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_support_a_buffer_without_a_path(
|
||||
browser: Browser, page: Page, server: Server
|
||||
) -> None:
|
||||
await browser.start_tracing(page=page, screenshots=True)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await rafraf(page)
|
||||
trace = await browser.stop_tracing()
|
||||
assert "screenshot" in trace.decode()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,155 @@
|
||||
# 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.async_api import ConsoleMessage, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_console_should_work(page: Page, browser_name: str) -> None:
|
||||
messages: List[ConsoleMessage] = []
|
||||
page.once("console", lambda m: messages.append(m))
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate('() => console.log("hello", 5, {foo: "bar"})')
|
||||
message = await message_info.value
|
||||
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 await message.args[0].json_value() == "hello"
|
||||
assert await message.args[1].json_value() == 5
|
||||
assert await message.args[2].json_value() == {"foo": "bar"}
|
||||
|
||||
|
||||
async def test_console_should_emit_same_log_twice(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m.text))
|
||||
await page.evaluate('() => { for (let i = 0; i < 2; ++i ) console.log("hello"); } ')
|
||||
assert messages == ["hello", "hello"]
|
||||
|
||||
|
||||
async def test_console_should_use_text_for__str__(page: Page) -> None:
|
||||
messages = []
|
||||
page.on("console", lambda m: messages.append(m))
|
||||
await page.evaluate('() => console.log("Hello world")')
|
||||
assert len(messages) == 1
|
||||
assert str(messages[0]) == "Hello world"
|
||||
|
||||
|
||||
async def test_console_should_work_for_different_console_api_calls(page: Page) -> None:
|
||||
messages: List[ConsoleMessage] = []
|
||||
page.on("console", lambda m: messages.append(m))
|
||||
# All console events will be reported before 'page.evaluate' is finished.
|
||||
await 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",
|
||||
]
|
||||
|
||||
|
||||
async def test_console_should_not_fail_for_window_object(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate("console.error(window)")
|
||||
message = await message_info.value
|
||||
if browser_name != "firefox":
|
||||
assert message.text == "Window"
|
||||
else:
|
||||
assert message.text == "JSHandle@object"
|
||||
|
||||
|
||||
# Upstream issue https://bugs.webkit.org/show_bug.cgi?id=229515
|
||||
@pytest.mark.skip_browser("webkit")
|
||||
async def test_console_should_trigger_correct_log(page: Page, server: Server) -> None:
|
||||
await page.goto("about:blank")
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate("async url => fetch(url).catch(e => {})", server.EMPTY_PAGE)
|
||||
message = await message_info.value
|
||||
assert "Access-Control-Allow-Origin" in message.text or "CORS" in message.text
|
||||
assert message.type == "error"
|
||||
|
||||
|
||||
async def test_console_should_have_location_for_console_api_calls(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.goto(server.PREFIX + "/consolelog.html")
|
||||
message = await 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"]
|
||||
|
||||
|
||||
async def test_console_should_not_throw_when_there_are_console_messages_in_detached_iframes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as page_info:
|
||||
await 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')
|
||||
await 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')
|
||||
await new Promise(f => frame.addEventListener('load', f));
|
||||
// 3. After that, remove the iframe.
|
||||
frame.remove();
|
||||
}"""
|
||||
)
|
||||
popup = await page_info.value
|
||||
# 4. Connect to the popup and make sure it doesn't throw.
|
||||
assert await popup.evaluate("1 + 1") == 2
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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.async_api import BrowserContext, BrowserType
|
||||
|
||||
|
||||
async def test_context_managers(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
async with await browser_type.launch(**launch_arguments) as browser:
|
||||
async with await browser.new_context() as context:
|
||||
async with await 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()
|
||||
|
||||
|
||||
async def test_context_managers_not_hang(context: BrowserContext) -> None:
|
||||
with pytest.raises(Exception, match="Oops!"):
|
||||
async with await context.new_page():
|
||||
raise Exception("Oops!")
|
||||
@@ -0,0 +1,43 @@
|
||||
# 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 playwright.async_api import BrowserContext, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_expose_debugger_property(context: BrowserContext) -> None:
|
||||
assert context.debugger is context.debugger
|
||||
assert context.debugger.paused_details is None
|
||||
|
||||
|
||||
async def test_should_pause_and_resume(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
paused_event = asyncio.Event()
|
||||
context.debugger.on("pausedstatechanged", lambda: paused_event.set())
|
||||
|
||||
await context.debugger.request_pause()
|
||||
next_call = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
|
||||
await asyncio.wait_for(paused_event.wait(), timeout=5)
|
||||
assert context.debugger.paused_details is not None
|
||||
|
||||
paused_event.clear()
|
||||
await context.debugger.resume()
|
||||
await asyncio.wait_for(paused_event.wait(), timeout=5)
|
||||
assert context.debugger.paused_details is None
|
||||
|
||||
await next_call
|
||||
@@ -0,0 +1,463 @@
|
||||
# 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
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncGenerator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Dict,
|
||||
List,
|
||||
Literal,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
)
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import (
|
||||
BrowserContext,
|
||||
BrowserType,
|
||||
Cookie,
|
||||
Error,
|
||||
Page,
|
||||
expect,
|
||||
)
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
async def launch_persistent(
|
||||
tmp_path: Path, launch_arguments: Dict, browser_type: BrowserType
|
||||
) -> AsyncGenerator[Callable[..., Awaitable[Tuple[Page, BrowserContext]]], None]:
|
||||
context: Optional[BrowserContext] = None
|
||||
|
||||
async def _launch(**options: Any) -> Tuple[Page, BrowserContext]:
|
||||
nonlocal context
|
||||
if context:
|
||||
raise ValueError("can only launch one persistent context")
|
||||
context = await browser_type.launch_persistent_context(
|
||||
str(tmp_path), **{**launch_arguments, **options}
|
||||
)
|
||||
assert context
|
||||
return (context.pages[0], context)
|
||||
|
||||
yield _launch
|
||||
await must(context).close()
|
||||
|
||||
|
||||
async def test_context_cookies_should_work(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
default_same_site_cookie_value: str,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
document_cookie = await page.evaluate(
|
||||
"""() => {
|
||||
document.cookie = 'username=John Doe';
|
||||
return document.cookie;
|
||||
}"""
|
||||
)
|
||||
|
||||
assert document_cookie == "username=John Doe"
|
||||
assert _filter_cookies(await page.context.cookies()) == [
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_context_add_cookies_should_work(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
default_same_site_cookie_value: Literal["Lax", "None", "Strict"],
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.context.add_cookies(
|
||||
[
|
||||
{
|
||||
"url": server.EMPTY_PAGE,
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
)
|
||||
assert await page.evaluate("() => document.cookie") == "username=John Doe"
|
||||
assert _filter_cookies(await page.context.cookies()) == [
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": default_same_site_cookie_value,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _filter_cookies(cookies: Sequence[Cookie]) -> List[Cookie]:
|
||||
return list(
|
||||
filter(lambda cookie: not cookie["domain"].endswith("microsoft.com"), cookies)
|
||||
)
|
||||
|
||||
|
||||
async def test_context_clear_cookies_should_work(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.context.add_cookies(
|
||||
[
|
||||
{"url": server.EMPTY_PAGE, "name": "cookie1", "value": "1"},
|
||||
{"url": server.EMPTY_PAGE, "name": "cookie2", "value": "2"},
|
||||
]
|
||||
)
|
||||
assert await page.evaluate("document.cookie") == "cookie1=1; cookie2=2"
|
||||
await page.context.clear_cookies()
|
||||
await page.reload()
|
||||
assert _filter_cookies(await page.context.cookies([])) == []
|
||||
assert await page.evaluate("document.cookie") == ""
|
||||
|
||||
|
||||
async def test_should_not_block_third_party_cookies(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
is_firefox: bool,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""src => {
|
||||
let fulfill;
|
||||
const promise = new Promise(x => fulfill = x);
|
||||
const iframe = document.createElement('iframe');
|
||||
document.body.appendChild(iframe);
|
||||
iframe.onload = fulfill;
|
||||
iframe.src = src;
|
||||
return promise;
|
||||
}""",
|
||||
server.CROSS_PROCESS_PREFIX + "/grid.html",
|
||||
)
|
||||
document_cookie = await page.frames[1].evaluate(
|
||||
"""() => {
|
||||
document.cookie = 'username=John Doe';
|
||||
return document.cookie;
|
||||
}"""
|
||||
)
|
||||
|
||||
await page.wait_for_timeout(2000)
|
||||
allows_third_party = is_firefox
|
||||
assert document_cookie == ("username=John Doe" if allows_third_party else "")
|
||||
cookies = await context.cookies(server.CROSS_PROCESS_PREFIX + "/grid.html")
|
||||
if allows_third_party:
|
||||
assert cookies == [
|
||||
{
|
||||
"domain": "127.0.0.1",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"name": "username",
|
||||
"path": "/",
|
||||
"sameSite": "None",
|
||||
"secure": False,
|
||||
"value": "John Doe",
|
||||
}
|
||||
]
|
||||
else:
|
||||
assert cookies == []
|
||||
|
||||
|
||||
async def test_should_support_viewport_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
utils: Utils,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(viewport={"width": 456, "height": 789})
|
||||
await utils.verify_viewport(page, 456, 789)
|
||||
page2 = await context.new_page()
|
||||
await utils.verify_viewport(page2, 456, 789)
|
||||
|
||||
|
||||
async def test_should_support_device_scale_factor_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(device_scale_factor=3)
|
||||
assert await page.evaluate("window.devicePixelRatio") == 3
|
||||
|
||||
|
||||
async def test_should_support_user_agent_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
server: Server,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(user_agent="foobar")
|
||||
assert await page.evaluate("() => navigator.userAgent") == "foobar"
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("user-agent") == "foobar"
|
||||
|
||||
|
||||
async def test_should_support_bypass_csp_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
server: Server,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(bypass_csp=True)
|
||||
await page.goto(server.PREFIX + "/csp.html")
|
||||
await page.add_script_tag(content="window.__injected = 42;")
|
||||
assert await page.evaluate("() => window.__injected") == 42
|
||||
|
||||
|
||||
async def test_should_support_javascript_enabled_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
is_webkit: bool,
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(java_script_enabled=False)
|
||||
await page.goto('data:text/html, <script>var something = "forbidden"</script>')
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.evaluate("something")
|
||||
if is_webkit:
|
||||
assert "Can't find variable: something" in exc.value.message
|
||||
else:
|
||||
assert "something is not defined" in exc.value.message
|
||||
|
||||
|
||||
async def test_should_support_http_credentials_option(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
server.set_auth("/playground.html", "user", "pass")
|
||||
response = await page.goto(server.PREFIX + "/playground.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
|
||||
|
||||
async def test_should_support_offline_option(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(offline=True)
|
||||
with pytest.raises(Error):
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_support_has_touch_option(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(has_touch=True)
|
||||
await page.goto(server.PREFIX + "/mobile.html")
|
||||
assert await page.evaluate('() => "ontouchstart" in window')
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_should_work_in_persistent_context(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
# Firefox does not support mobile.
|
||||
(page, context) = await launch_persistent(
|
||||
viewport={"width": 320, "height": 480}, is_mobile=True
|
||||
)
|
||||
await page.goto(server.PREFIX + "/empty.html")
|
||||
assert await page.evaluate("() => window.innerWidth") == 980
|
||||
|
||||
|
||||
async def test_should_support_color_scheme_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(color_scheme="dark")
|
||||
assert (
|
||||
await page.evaluate('() => matchMedia("(prefers-color-scheme: light)").matches')
|
||||
is False
|
||||
)
|
||||
assert await page.evaluate(
|
||||
'() => matchMedia("(prefers-color-scheme: dark)").matches'
|
||||
)
|
||||
|
||||
|
||||
async def test_should_support_timezone_id_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(timezone_id="America/Jamaica")
|
||||
assert (
|
||||
await page.evaluate("() => new Date(1479579154987).toString()")
|
||||
== "Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_support_contrast_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, _) = await launch_persistent(contrast="more")
|
||||
assert await page.evaluate('() => matchMedia("(prefers-contrast: more)").matches')
|
||||
assert not await page.evaluate(
|
||||
'() => matchMedia("(prefers-contrast: no-preference)").matches'
|
||||
)
|
||||
|
||||
|
||||
async def test_should_support_locale_option(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(locale="fr-FR")
|
||||
assert await page.evaluate("() => navigator.language") == "fr-FR"
|
||||
|
||||
|
||||
async def test_should_support_geolocation_and_permission_option(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(
|
||||
geolocation={"longitude": 10, "latitude": 10}, permissions=["geolocation"]
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
geolocation = await page.evaluate(
|
||||
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
|
||||
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
|
||||
}))"""
|
||||
)
|
||||
assert geolocation == {"latitude": 10, "longitude": 10}
|
||||
|
||||
|
||||
async def test_should_support_ignore_https_errors_option(
|
||||
https_server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(ignore_https_errors=True)
|
||||
response = await page.goto(https_server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
|
||||
|
||||
async def test_should_support_extra_http_headers_option(
|
||||
server: Server,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(extra_http_headers={"foo": "bar"})
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_should_accept_user_data_dir(
|
||||
tmp_path: Path,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
# Note: we need an open page to make sure its functional.
|
||||
assert len(os.listdir(tmp_path)) > 0
|
||||
await context.close()
|
||||
assert len(os.listdir(tmp_path)) > 0
|
||||
|
||||
|
||||
async def test_should_restore_state_from_userDataDir(
|
||||
browser_type: BrowserType,
|
||||
launch_arguments: Dict,
|
||||
server: Server,
|
||||
tmp_path_factory: pytest.TempPathFactory,
|
||||
) -> None:
|
||||
user_data_dir1 = tmp_path_factory.mktemp("test")
|
||||
browser_context = await browser_type.launch_persistent_context(
|
||||
user_data_dir1, **launch_arguments
|
||||
)
|
||||
page = await browser_context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate('() => localStorage.hey = "hello"')
|
||||
await browser_context.close()
|
||||
|
||||
browser_context2 = await browser_type.launch_persistent_context(
|
||||
user_data_dir1, **launch_arguments
|
||||
)
|
||||
page2 = await browser_context2.new_page()
|
||||
await page2.goto(server.EMPTY_PAGE)
|
||||
assert await page2.evaluate("() => localStorage.hey") == "hello"
|
||||
await browser_context2.close()
|
||||
|
||||
user_data_dir2 = tmp_path_factory.mktemp("test")
|
||||
browser_context3 = await browser_type.launch_persistent_context(
|
||||
user_data_dir2, **launch_arguments
|
||||
)
|
||||
page3 = await browser_context3.new_page()
|
||||
await page3.goto(server.EMPTY_PAGE)
|
||||
assert await page3.evaluate("() => localStorage.hey") != "hello"
|
||||
await browser_context3.close()
|
||||
|
||||
|
||||
async def test_should_have_default_url_when_launching_browser(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
urls = list(map(lambda p: p.url, context.pages))
|
||||
assert urls == ["about:blank"]
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_should_throw_if_page_argument_is_passed(
|
||||
browser_type: BrowserType, server: Server, tmp_path: Path, launch_arguments: Dict
|
||||
) -> None:
|
||||
options = {**launch_arguments, "args": [server.EMPTY_PAGE]}
|
||||
with pytest.raises(Error) as exc:
|
||||
await browser_type.launch_persistent_context(tmp_path, **options)
|
||||
assert "can not specify page" in exc.value.message
|
||||
|
||||
|
||||
async def test_should_fire_close_event_for_a_persistent_context(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
fired_event: "asyncio.Future[bool]" = asyncio.Future()
|
||||
context.on("close", lambda _: fired_event.set_result(True))
|
||||
await context.close()
|
||||
await fired_event
|
||||
|
||||
|
||||
async def test_should_support_reduced_motion(
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent(reduced_motion="reduce")
|
||||
assert await page.evaluate("matchMedia('(prefers-reduced-motion: reduce)').matches")
|
||||
|
||||
|
||||
async def test_should_support_har_option(
|
||||
assetdir: Path,
|
||||
launch_persistent: "Callable[..., asyncio.Future[Tuple[Page, BrowserContext]]]",
|
||||
) -> None:
|
||||
(page, context) = await launch_persistent()
|
||||
await page.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
await expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
@@ -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 typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Playwright
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_work(playwright: Playwright, launch_arguments: Dict) -> None:
|
||||
device_descriptor = playwright.devices["Pixel 2"]
|
||||
device_type = device_descriptor["default_browser_type"]
|
||||
browser = await playwright[device_type].launch(**launch_arguments)
|
||||
context = await browser.new_context(
|
||||
**device_descriptor,
|
||||
)
|
||||
page = await context.new_page()
|
||||
assert device_descriptor["default_browser_type"] == "chromium"
|
||||
assert browser.browser_type.name == "chromium"
|
||||
|
||||
assert "Pixel 2" in device_descriptor["user_agent"]
|
||||
assert "Pixel 2" in await page.evaluate("navigator.userAgent")
|
||||
|
||||
assert device_descriptor["device_scale_factor"] > 2
|
||||
assert await page.evaluate("window.devicePixelRatio") > 2
|
||||
|
||||
assert device_descriptor["viewport"]["height"] > 700
|
||||
assert device_descriptor["viewport"]["height"] < 800
|
||||
inner_height = await page.evaluate("window.screen.availHeight")
|
||||
assert inner_height > 700
|
||||
assert inner_height < 800
|
||||
|
||||
assert device_descriptor["viewport"]["width"] > 400
|
||||
assert device_descriptor["viewport"]["width"] < 500
|
||||
inner_width = await page.evaluate("window.screen.availWidth")
|
||||
assert inner_width > 400
|
||||
assert inner_width < 500
|
||||
|
||||
assert device_descriptor["has_touch"]
|
||||
assert device_descriptor["is_mobile"]
|
||||
|
||||
await browser.close()
|
||||
@@ -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.
|
||||
|
||||
from playwright.async_api import Browser, Dialog, Page
|
||||
|
||||
|
||||
async def test_should_fire(page: Page) -> None:
|
||||
result = []
|
||||
|
||||
async def on_dialog(dialog: Dialog) -> None:
|
||||
result.append(True)
|
||||
assert dialog.type == "alert"
|
||||
assert dialog.default_value == ""
|
||||
assert dialog.message == "yo"
|
||||
await dialog.accept()
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
await page.evaluate("alert('yo')")
|
||||
assert result
|
||||
|
||||
|
||||
async def test_should_allow_accepting_prompts(page: Page) -> None:
|
||||
result = []
|
||||
|
||||
async def on_dialog(dialog: Dialog) -> None:
|
||||
result.append(True)
|
||||
assert dialog.type == "prompt"
|
||||
assert dialog.default_value == "yes."
|
||||
assert dialog.message == "question?"
|
||||
await dialog.accept("answer!")
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
assert await page.evaluate("prompt('question?', 'yes.')") == "answer!"
|
||||
assert result
|
||||
|
||||
|
||||
async def test_should_dismiss_the_prompt(page: Page) -> None:
|
||||
result = []
|
||||
|
||||
async def on_dialog(dialog: Dialog) -> None:
|
||||
result.append(True)
|
||||
await dialog.dismiss()
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
assert await page.evaluate("prompt('question?')") is None
|
||||
assert result
|
||||
|
||||
|
||||
async def test_should_accept_the_confirm_prompt(page: Page) -> None:
|
||||
result = []
|
||||
|
||||
async def on_dialog(dialog: Dialog) -> None:
|
||||
result.append(True)
|
||||
await dialog.accept()
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
assert await page.evaluate("confirm('boolean?')") is True
|
||||
assert result
|
||||
|
||||
|
||||
async def test_should_dismiss_the_confirm_prompt(page: Page) -> None:
|
||||
result = []
|
||||
|
||||
async def on_dialog(dialog: Dialog) -> None:
|
||||
result.append(True)
|
||||
await dialog.dismiss()
|
||||
|
||||
page.on("dialog", on_dialog)
|
||||
assert await page.evaluate("confirm('boolean?')") is False
|
||||
assert result
|
||||
|
||||
|
||||
async def test_should_be_able_to_close_context_with_open_alert(
|
||||
browser: Browser,
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
async with page.expect_event("dialog"):
|
||||
await page.evaluate("() => setTimeout(() => alert('hello'), 0)", None)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_auto_dismiss_the_prompt_without_listeners(page: Page) -> None:
|
||||
result = await page.evaluate('() => prompt("question?")')
|
||||
assert not result
|
||||
|
||||
|
||||
async def test_should_auto_dismiss_the_alert_without_listeners(page: Page) -> None:
|
||||
await page.set_content(
|
||||
'<div onclick="window.alert(123); window._clicked=true">Click me</div>'
|
||||
)
|
||||
await page.click("div")
|
||||
assert await page.evaluate('"window._clicked"')
|
||||
|
||||
|
||||
async def test_dismiss_should_swallow_target_closed_error(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
async with page.expect_event("dialog") as dialog_info:
|
||||
await page.evaluate("() => setTimeout(() => alert('hello'), 0)", None)
|
||||
dialog = await dialog_info.value
|
||||
await page.close()
|
||||
# Dialog.dismiss should be a no-op once the target is closed.
|
||||
await dialog.dismiss()
|
||||
await context.close()
|
||||
@@ -0,0 +1,191 @@
|
||||
# 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.async_api import Page, Selectors
|
||||
from tests.server import Server
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async def test_should_dispatch_click_event(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
assert await page.evaluate("() => result") == "Clicked"
|
||||
|
||||
|
||||
async def test_should_dispatch_click_event_properties(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
assert await page.evaluate("() => bubbles")
|
||||
assert await page.evaluate("() => cancelable")
|
||||
assert await page.evaluate("() => composed")
|
||||
|
||||
|
||||
async def test_should_dispatch_click_svg(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<svg height="100" width="100">
|
||||
<circle onclick="javascript:window.__CLICKED=42" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
|
||||
</svg>
|
||||
"""
|
||||
)
|
||||
await page.dispatch_event("circle", "click")
|
||||
assert await page.evaluate("() => window.__CLICKED") == 42
|
||||
|
||||
|
||||
async def test_should_dispatch_click_on_a_span_with_an_inline_element_inside(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<style>
|
||||
span::before {
|
||||
content: 'q';
|
||||
}
|
||||
</style>
|
||||
<span onclick='javascript:window.CLICKED=42'></span>
|
||||
"""
|
||||
)
|
||||
await page.dispatch_event("span", "click")
|
||||
assert await page.evaluate("() => window.CLICKED") == 42
|
||||
|
||||
|
||||
async def test_should_dispatch_click_after_navigation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
assert await page.evaluate("() => result") == "Clicked"
|
||||
|
||||
|
||||
async def test_should_dispatch_click_after_a_cross_origin_navigation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX + "/input/button.html")
|
||||
await page.dispatch_event("button", "click")
|
||||
assert await page.evaluate("() => result") == "Clicked"
|
||||
|
||||
|
||||
async def test_should_not_fail_when_element_is_blocked_on_hover(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""<style>
|
||||
container { display: block; position: relative; width: 200px; height: 50px; }
|
||||
div, button { position: absolute; left: 0; top: 0; bottom: 0; right: 0; }
|
||||
div { pointer-events: none; }
|
||||
container:hover div { pointer-events: auto; background: red; }
|
||||
</style>
|
||||
<container>
|
||||
<button onclick="window.clicked=true">Click me</button>
|
||||
<div></div>
|
||||
</container>"""
|
||||
)
|
||||
await page.dispatch_event("button", "click")
|
||||
assert await page.evaluate("() => window.clicked")
|
||||
|
||||
|
||||
async def test_should_dispatch_click_when_node_is_added_in_shadow_dom(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
watchdog = page.dispatch_event("span", "click")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const div = document.createElement('div');
|
||||
div.attachShadow({mode: 'open'});
|
||||
document.body.appendChild(div);
|
||||
}"""
|
||||
)
|
||||
await page.evaluate("() => new Promise(f => setTimeout(f, 100))")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const span = document.createElement('span');
|
||||
span.textContent = 'Hello from shadow';
|
||||
span.addEventListener('click', () => window.clicked = true);
|
||||
document.querySelector('div').shadowRoot.appendChild(span);
|
||||
}"""
|
||||
)
|
||||
await watchdog
|
||||
assert await page.evaluate("() => window.clicked")
|
||||
|
||||
|
||||
async def test_should_be_atomic(selectors: Selectors, page: Page, utils: Utils) -> None:
|
||||
await utils.register_selector_engine(
|
||||
selectors,
|
||||
"dispatch_event",
|
||||
"""{
|
||||
create(root, target) { },
|
||||
query(root, selector) {
|
||||
const result = root.querySelector(selector);
|
||||
if (result)
|
||||
Promise.resolve().then(() => result.onclick = "");
|
||||
return result;
|
||||
},
|
||||
queryAll(root, selector) {
|
||||
const result = Array.from(root.querySelectorAll(selector));
|
||||
for (const e of result)
|
||||
Promise.resolve().then(() => result.onclick = "");
|
||||
return result;
|
||||
}
|
||||
}""",
|
||||
)
|
||||
await page.set_content('<div onclick="window._clicked=true">Hello</div>')
|
||||
await page.dispatch_event("dispatch_event=div", "click")
|
||||
assert await page.evaluate("() => window._clicked")
|
||||
|
||||
|
||||
async def test_should_dispatch_drag_drop_events(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/drag-n-drop.html")
|
||||
dataTransfer = await page.evaluate_handle("() => new DataTransfer()")
|
||||
await page.dispatch_event("#source", "dragstart", {"dataTransfer": dataTransfer})
|
||||
await page.dispatch_event("#target", "drop", {"dataTransfer": dataTransfer})
|
||||
assert await page.evaluate(
|
||||
"""() => {
|
||||
return source.parentElement === target;
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
async def test_should_dispatch_drag_and_drop_events_element_handle(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/drag-n-drop.html")
|
||||
dataTransfer = await page.evaluate_handle("() => new DataTransfer()")
|
||||
source = await page.query_selector("#source")
|
||||
assert source
|
||||
await source.dispatch_event("dragstart", {"dataTransfer": dataTransfer})
|
||||
target = await page.query_selector("#target")
|
||||
assert target
|
||||
await target.dispatch_event("drop", {"dataTransfer": dataTransfer})
|
||||
assert await page.evaluate(
|
||||
"""() => {
|
||||
return source.parentElement === target;
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
async def test_should_dispatch_click_event_element_handle(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await button.dispatch_event("click")
|
||||
assert await page.evaluate("() => result") == "Clicked"
|
||||
@@ -0,0 +1,388 @@
|
||||
# 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
|
||||
import os
|
||||
from asyncio.futures import Future
|
||||
from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, Download, Error, Page
|
||||
from tests.server import Server, TestServerRequest
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
def assert_file_content(path: Path, content: str) -> None:
|
||||
with open(path, "r") as fd:
|
||||
assert fd.read() == content
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def after_each_hook(server: Server) -> Generator[None, None, None]:
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.setHeader("Content-Disposition", "attachment")
|
||||
request.write(b"Hello world")
|
||||
request.finish()
|
||||
|
||||
def handle_download_with_file_name(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)
|
||||
server.set_route("/downloadWithFilename", handle_download_with_file_name)
|
||||
yield
|
||||
|
||||
|
||||
async def test_should_report_downloads_with_accept_downloads_false(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
f'<a href="{server.PREFIX}/downloadWithFilename">download</a>'
|
||||
)
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
assert download.page is page
|
||||
assert download.url == f"{server.PREFIX}/downloadWithFilename"
|
||||
assert download.suggested_filename == "file.txt"
|
||||
assert (
|
||||
repr(download)
|
||||
== f"<Download url={download.url!r} suggested_filename={download.suggested_filename!r}>"
|
||||
)
|
||||
assert await download.path()
|
||||
assert await download.failure() is None
|
||||
|
||||
|
||||
async def test_should_report_downloads_with_accept_downloads_true(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
path = await download.path()
|
||||
assert os.path.isfile(path)
|
||||
assert_file_content(path, "Hello world")
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_save_to_user_specified_path(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
await download.save_as(user_path)
|
||||
assert user_path.exists()
|
||||
assert user_path.read_text("utf-8") == "Hello world"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_save_to_user_specified_path_without_updating_original_path(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
await download.save_as(user_path)
|
||||
assert user_path.exists()
|
||||
assert user_path.read_text("utf-8") == "Hello world"
|
||||
|
||||
originalPath = Path(await download.path())
|
||||
assert originalPath.exists()
|
||||
assert originalPath.read_text("utf-8") == "Hello world"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_save_to_two_different_paths_with_multiple_save_as_calls(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
await download.save_as(user_path)
|
||||
assert user_path.exists()
|
||||
assert user_path.read_text("utf-8") == "Hello world"
|
||||
|
||||
anotheruser_path = tmp_path / "download (2).txt"
|
||||
await download.save_as(anotheruser_path)
|
||||
assert anotheruser_path.exists()
|
||||
assert anotheruser_path.read_text("utf-8") == "Hello world"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_save_to_overwritten_filepath(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
await download.save_as(user_path)
|
||||
assert len(list(tmp_path.glob("*.*"))) == 1
|
||||
await download.save_as(user_path)
|
||||
assert len(list(tmp_path.glob("*.*"))) == 1
|
||||
assert user_path.exists()
|
||||
assert user_path.read_text("utf-8") == "Hello world"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_create_subdirectories_when_saving_to_non_existent_user_specified_path(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
nested_path = tmp_path / "these" / "are" / "directories" / "download.txt"
|
||||
await download.save_as(nested_path)
|
||||
assert nested_path.exists()
|
||||
assert nested_path.read_text("utf-8") == "Hello world"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_error_when_saving_with_downloads_disabled(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=False)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
with pytest.raises(Error) as exc:
|
||||
await download.save_as(user_path)
|
||||
assert (
|
||||
"Pass 'accept_downloads=True' when you are creating your browser context"
|
||||
in exc.value.message
|
||||
)
|
||||
assert (
|
||||
"Pass 'accept_downloads=True' when you are creating your browser context."
|
||||
== await download.failure()
|
||||
)
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_error_when_saving_after_deletion(
|
||||
tmp_path: Path, browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
user_path = tmp_path / "download.txt"
|
||||
await download.delete()
|
||||
with pytest.raises(Error) as exc:
|
||||
await download.save_as(user_path)
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc.value.message
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_report_non_navigation_downloads(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
# Mac WebKit embedder does not download in this case, although Safari does.
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.write(b"Hello world")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/download", handle_download)
|
||||
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
f'<a download="file.txt" href="{server.PREFIX}/download">download</a>'
|
||||
)
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
assert download.suggested_filename == "file.txt"
|
||||
path = await download.path()
|
||||
assert os.path.exists(path)
|
||||
assert_file_content(path, "Hello world")
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_report_download_path_within_page_on_download_handler_for_files(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
on_download_path: Future[Path] = asyncio.Future()
|
||||
|
||||
async def on_download(download: Download) -> None:
|
||||
on_download_path.set_result(await download.path())
|
||||
|
||||
page.once(
|
||||
"download",
|
||||
lambda res: asyncio.create_task(on_download(res)),
|
||||
)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
await page.click("a")
|
||||
path = await on_download_path
|
||||
assert_file_content(path, "Hello world")
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_download_report_download_path_within_page_on_handle_for_blobs(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
on_download_path: "asyncio.Future[Path]" = asyncio.Future()
|
||||
|
||||
async def on_download(download: Download) -> None:
|
||||
on_download_path.set_result(await download.path())
|
||||
|
||||
page.once(
|
||||
"download",
|
||||
lambda res: asyncio.create_task(on_download(res)),
|
||||
)
|
||||
|
||||
await page.goto(server.PREFIX + "/download-blob.html")
|
||||
await page.click("a")
|
||||
path = await on_download_path
|
||||
assert_file_content(path, "Hello world")
|
||||
await page.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_report_alt_click_downloads(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
# Firefox does not download on alt-click by default.
|
||||
# Our WebKit embedder does not download on alt-click, although Safari does.
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.write(b"Hello world")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/download", handle_download)
|
||||
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a", modifiers=["Alt"])
|
||||
download = await download_info.value
|
||||
path = await download.path()
|
||||
assert os.path.exists(path)
|
||||
assert_file_content(path, "Hello world")
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_report_new_window_downloads(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(
|
||||
f'<a target=_blank href="{server.PREFIX}/download">download</a>'
|
||||
)
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
path = await download.path()
|
||||
assert os.path.exists(path)
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_delete_file(browser: Browser, server: Server) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
path = await download.path()
|
||||
assert os.path.exists(path)
|
||||
await download.delete()
|
||||
assert os.path.exists(path) is False
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_delete_downloads_on_context_destruction(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download1 = await download_info.value
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download2 = await download_info.value
|
||||
path1 = await download1.path()
|
||||
path2 = await download2.path()
|
||||
assert os.path.exists(path1)
|
||||
assert os.path.exists(path2)
|
||||
await page.context.close()
|
||||
assert os.path.exists(path1) is False
|
||||
assert os.path.exists(path2) is False
|
||||
|
||||
|
||||
async def test_should_delete_downloads_on_browser_gone(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
browser = await browser_factory()
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download1 = await download_info.value
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download2 = await download_info.value
|
||||
path1 = await download1.path()
|
||||
path2 = await download2.path()
|
||||
assert os.path.exists(path1)
|
||||
assert os.path.exists(path2)
|
||||
await browser.close()
|
||||
assert os.path.exists(path1) is False
|
||||
assert os.path.exists(path2) is False
|
||||
assert os.path.exists(os.path.join(path1, "..")) is False
|
||||
|
||||
|
||||
async def test_download_cancel_should_work(browser: Browser, server: Server) -> None:
|
||||
def handle_download(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "application/octet-stream")
|
||||
request.setHeader("Content-Disposition", "attachment")
|
||||
# Chromium requires a large enough payload to trigger the download event soon enough
|
||||
request.write(b"a" * 4096)
|
||||
request.write(b"foo")
|
||||
|
||||
server.set_route("/downloadWithDelay", handle_download)
|
||||
page = await browser.new_page(accept_downloads=True)
|
||||
await page.set_content(f'<a href="{server.PREFIX}/downloadWithDelay">download</a>')
|
||||
async with page.expect_download() as download_info:
|
||||
await page.click("a")
|
||||
download = await download_info.value
|
||||
await download.cancel()
|
||||
assert await download.failure() == "canceled"
|
||||
await page.close()
|
||||
@@ -0,0 +1,794 @@
|
||||
# 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 typing import Optional, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, ElementHandle, Error, FloatRect, Page
|
||||
from tests.server import Server
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async def test_bounding_box(page: Page, server: Server) -> None:
|
||||
await page.set_viewport_size({"width": 500, "height": 500})
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
element_handle = await page.query_selector(".box:nth-of-type(13)")
|
||||
assert element_handle
|
||||
box = await element_handle.bounding_box()
|
||||
assert box == {"x": 100, "y": 50, "width": 50, "height": 50}
|
||||
|
||||
|
||||
async def test_bounding_box_handle_nested_frames(page: Page, server: Server) -> None:
|
||||
await page.set_viewport_size({"width": 500, "height": 500})
|
||||
await page.goto(server.PREFIX + "/frames/nested-frames.html")
|
||||
nested_frame = page.frame(name="dos")
|
||||
assert nested_frame
|
||||
element_handle = await nested_frame.query_selector("div")
|
||||
assert element_handle
|
||||
box = await element_handle.bounding_box()
|
||||
assert box == {"x": 24, "y": 224, "width": 268, "height": 18}
|
||||
|
||||
|
||||
async def test_bounding_box_return_null_for_invisible_elements(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content('<div style="display:none">hi</div>')
|
||||
element = await page.query_selector("div")
|
||||
assert element
|
||||
assert await element.bounding_box() is None
|
||||
|
||||
|
||||
async def test_bounding_box_force_a_layout(page: Page, server: Server) -> None:
|
||||
await page.set_viewport_size({"width": 500, "height": 500})
|
||||
await page.set_content('<div style="width: 100px; height: 100px">hello</div>')
|
||||
element_handle = await page.query_selector("div")
|
||||
assert element_handle
|
||||
await page.evaluate('element => element.style.height = "200px"', element_handle)
|
||||
box = await element_handle.bounding_box()
|
||||
assert box == {"x": 8, "y": 8, "width": 100, "height": 200}
|
||||
|
||||
|
||||
async def test_bounding_box_with_SVG_nodes(page: Page, server: Server) -> None:
|
||||
await 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 = await page.query_selector("#therect")
|
||||
assert element
|
||||
pw_bounding_box = await element.bounding_box()
|
||||
web_bounding_box = await 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")
|
||||
async def test_bounding_box_with_page_scale(browser: Browser, server: Server) -> None:
|
||||
context = await browser.new_context(
|
||||
viewport={"width": 400, "height": 400}, is_mobile=True
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await 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 = await 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
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_bounding_box_when_inline_box_child_is_outside_of_viewport(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await 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 = await page.query_selector("span")
|
||||
assert handle
|
||||
box = await handle.bounding_box()
|
||||
web_bounding_box = await handle.evaluate(
|
||||
"""e => {
|
||||
rect = e.getBoundingClientRect();
|
||||
return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
|
||||
}"""
|
||||
)
|
||||
|
||||
def roundbox(b: Optional[FloatRect]) -> FloatRect:
|
||||
assert b
|
||||
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)
|
||||
|
||||
|
||||
async def test_content_frame(page: Page, server: Server, utils: Utils) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
element_handle = await page.query_selector("#frame1")
|
||||
assert element_handle
|
||||
frame = await element_handle.content_frame()
|
||||
assert frame == page.frames[1]
|
||||
|
||||
|
||||
async def test_content_frame_for_non_iframes(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = cast(ElementHandle, await frame.evaluate_handle("document.body"))
|
||||
assert await element_handle.content_frame() is None
|
||||
|
||||
|
||||
async def test_content_frame_for_document_element(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = cast(
|
||||
ElementHandle, await frame.evaluate_handle("document.documentElement")
|
||||
)
|
||||
assert await element_handle.content_frame() is None
|
||||
|
||||
|
||||
async def test_owner_frame(page: Page, server: Server, utils: Utils) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = cast(ElementHandle, await frame.evaluate_handle("document.body"))
|
||||
assert await element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
async def test_owner_frame_for_cross_process_iframes(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(
|
||||
page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html"
|
||||
)
|
||||
frame = page.frames[1]
|
||||
element_handle = cast(ElementHandle, await frame.evaluate_handle("document.body"))
|
||||
assert await element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
async def test_owner_frame_for_document(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.frames[1]
|
||||
element_handle = cast(ElementHandle, await frame.evaluate_handle("document"))
|
||||
assert await element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
async def test_owner_frame_for_iframe_elements(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.main_frame
|
||||
element_handle = cast(
|
||||
ElementHandle, await frame.evaluate_handle('document.querySelector("#frame1")')
|
||||
)
|
||||
assert await element_handle.owner_frame() == frame
|
||||
|
||||
|
||||
async def test_owner_frame_for_cross_frame_evaluations(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
frame = page.main_frame
|
||||
element_handle = cast(
|
||||
ElementHandle,
|
||||
await frame.evaluate_handle(
|
||||
'document.querySelector("#frame1").contentWindow.document.body'
|
||||
),
|
||||
)
|
||||
assert await element_handle.owner_frame() == frame.child_frames[0]
|
||||
|
||||
|
||||
async def test_owner_frame_for_detached_elements(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
div_handle = cast(
|
||||
ElementHandle,
|
||||
await page.evaluate_handle(
|
||||
"""() => {
|
||||
div = document.createElement('div');
|
||||
document.body.appendChild(div);
|
||||
return div;
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert div_handle
|
||||
|
||||
assert await div_handle.owner_frame() == page.main_frame
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
div = document.querySelector('div')
|
||||
document.body.removeChild(div)
|
||||
}"""
|
||||
)
|
||||
assert await div_handle.owner_frame() == page.main_frame
|
||||
|
||||
|
||||
async def test_owner_frame_for_adopted_elements(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"url => window.__popup = window.open(url)", server.EMPTY_PAGE
|
||||
)
|
||||
popup = await popup_info.value
|
||||
div_handle = cast(
|
||||
ElementHandle,
|
||||
await page.evaluate_handle(
|
||||
"""() => {
|
||||
div = document.createElement('div');
|
||||
document.body.appendChild(div);
|
||||
return div;
|
||||
}"""
|
||||
),
|
||||
)
|
||||
assert div_handle
|
||||
assert await div_handle.owner_frame() == page.main_frame
|
||||
await popup.wait_for_load_state("domcontentloaded")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
div = document.querySelector('div');
|
||||
window.__popup.document.body.appendChild(div);
|
||||
}"""
|
||||
)
|
||||
assert await div_handle.owner_frame() == popup.main_frame
|
||||
|
||||
|
||||
async def test_click(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await button.click()
|
||||
assert await page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
async def test_click_with_node_removed(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.evaluate('delete window["Node"]')
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await button.click()
|
||||
assert await page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
async def test_click_for_shadow_dom_v1(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/shadow.html")
|
||||
button_handle = cast(ElementHandle, await page.evaluate_handle("button"))
|
||||
await button_handle.click()
|
||||
assert await page.evaluate("clicked")
|
||||
|
||||
|
||||
async def test_click_for_TextNodes(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
buttonTextNode = cast(
|
||||
ElementHandle,
|
||||
await page.evaluate_handle('document.querySelector("button").firstChild'),
|
||||
)
|
||||
await buttonTextNode.click()
|
||||
assert await page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
async def test_click_throw_for_detached_nodes(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await page.evaluate("button => button.remove()", button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await button.click()
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_click_throw_for_hidden_nodes_with_force(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await page.evaluate('button => button.style.display = "none"', button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await button.click(force=True)
|
||||
assert "Element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_click_throw_for_recursively_hidden_nodes_with_force(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await page.evaluate('button => button.parentElement.style.display = "none"', button)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await button.click(force=True)
|
||||
assert "Element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_click_throw_for__br__elements_with_force(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content("hello<br>goodbye")
|
||||
br = await page.query_selector("br")
|
||||
assert br
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await br.click(force=True)
|
||||
assert "Element is outside of the viewport" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_double_click_the_button(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.double = false;
|
||||
button = document.querySelector('button');
|
||||
button.addEventListener('dblclick', event => {
|
||||
window.double = true;
|
||||
});
|
||||
}"""
|
||||
)
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
await button.dblclick()
|
||||
assert await page.evaluate("double")
|
||||
assert await page.evaluate("result") == "Clicked"
|
||||
|
||||
|
||||
async def test_hover(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/scrollable.html")
|
||||
button = await page.query_selector("#button-6")
|
||||
assert button
|
||||
await button.hover()
|
||||
assert (
|
||||
await page.evaluate('document.querySelector("button:hover").id') == "button-6"
|
||||
)
|
||||
|
||||
|
||||
async def test_hover_when_node_is_removed(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/scrollable.html")
|
||||
await page.evaluate('delete window["Node"]')
|
||||
button = await page.query_selector("#button-6")
|
||||
assert button
|
||||
await button.hover()
|
||||
assert (
|
||||
await page.evaluate('document.querySelector("button:hover").id') == "button-6"
|
||||
)
|
||||
|
||||
|
||||
async def test_scroll(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/offscreenbuttons.html")
|
||||
for i in range(11):
|
||||
button = await page.query_selector(f"#btn{i}")
|
||||
assert button
|
||||
before = await button.evaluate(
|
||||
"""button => {
|
||||
return button.getBoundingClientRect().right - window.innerWidth
|
||||
}"""
|
||||
)
|
||||
|
||||
assert before == 10 * i
|
||||
await button.scroll_into_view_if_needed()
|
||||
after = await button.evaluate(
|
||||
"""button => {
|
||||
return button.getBoundingClientRect().right - window.innerWidth
|
||||
}"""
|
||||
)
|
||||
|
||||
assert after <= 0
|
||||
await page.evaluate("() => window.scrollTo(0, 0)")
|
||||
|
||||
|
||||
async def test_scroll_should_throw_for_detached_element(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content("<div>Hello</div>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
await div.evaluate("div => div.remove()")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await div.scroll_into_view_if_needed()
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
async def waiting_helper(page: Page, after: str) -> None:
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
done = []
|
||||
|
||||
async def scroll() -> None:
|
||||
done.append(False)
|
||||
await div.scroll_into_view_if_needed()
|
||||
done.append(True)
|
||||
|
||||
promise = asyncio.create_task(scroll())
|
||||
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
|
||||
await page.evaluate("() => new Promise(f => setTimeout(f, 1000))")
|
||||
assert done == [False]
|
||||
await div.evaluate(after)
|
||||
await promise
|
||||
assert done == [False, True]
|
||||
|
||||
|
||||
async def test_should_wait_for_display_none_to_become_visible(page: Page) -> None:
|
||||
await page.set_content('<div style="display:none">Hello</div>')
|
||||
await waiting_helper(page, 'div => div.style.display = "block"')
|
||||
|
||||
|
||||
async def test_should_work_for_visibility_hidden_element(page: Page) -> None:
|
||||
await page.set_content('<div style="visibility:hidden">Hello</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
await div.scroll_into_view_if_needed()
|
||||
|
||||
|
||||
async def test_should_work_for_zero_sized_element(page: Page) -> None:
|
||||
await page.set_content('<div style="height:0">Hello</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
await div.scroll_into_view_if_needed()
|
||||
|
||||
|
||||
async def test_should_wait_for_nested_display_none_to_become_visible(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content('<span style="display:none"><div>Hello</div></span>')
|
||||
await waiting_helper(page, 'div => div.parentElement.style.display = "block"')
|
||||
|
||||
|
||||
async def test_should_timeout_waiting_for_visible(page: Page) -> None:
|
||||
await page.set_content('<div style="display:none">Hello</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await 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
|
||||
|
||||
|
||||
async def test_fill_input(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
handle = await page.query_selector("input")
|
||||
assert handle
|
||||
await handle.fill("some value")
|
||||
assert await page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
async def test_fill_input_when_Node_is_removed(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.evaluate('delete window["Node"]')
|
||||
handle = await page.query_selector("input")
|
||||
assert handle
|
||||
await handle.fill("some value")
|
||||
assert await page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
async def test_select_textarea(
|
||||
page: Page, server: Server, is_firefox: bool, is_webkit: bool
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.evaluate('textarea => textarea.value = "some value"')
|
||||
await textarea.select_text()
|
||||
if is_firefox or is_webkit:
|
||||
assert await textarea.evaluate("el => el.selectionStart") == 0
|
||||
assert await textarea.evaluate("el => el.selectionEnd") == 10
|
||||
else:
|
||||
assert (
|
||||
await page.evaluate("() => window.getSelection().toString()")
|
||||
== "some value"
|
||||
)
|
||||
|
||||
|
||||
async def test_select_input(
|
||||
page: Page, server: Server, is_firefox: bool, is_webkit: bool
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
await input.evaluate('input => input.value = "some value"')
|
||||
await input.select_text()
|
||||
if is_firefox or is_webkit:
|
||||
assert await input.evaluate("el => el.selectionStart") == 0
|
||||
assert await input.evaluate("el => el.selectionEnd") == 10
|
||||
else:
|
||||
assert (
|
||||
await page.evaluate("() => window.getSelection().toString()")
|
||||
== "some value"
|
||||
)
|
||||
|
||||
|
||||
async def test_select_text_select_plain_div(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
div = await page.query_selector("div.plain")
|
||||
assert div
|
||||
await div.select_text()
|
||||
assert await page.evaluate("() => window.getSelection().toString()") == "Plain div"
|
||||
|
||||
|
||||
async def test_select_text_timeout_waiting_for_invisible_element(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.evaluate('e => e.style.display = "none"')
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await textarea.select_text(timeout=3000)
|
||||
assert "element is not visible" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_select_text_wait_for_visible(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.evaluate('textarea => textarea.value = "some value"')
|
||||
await textarea.evaluate('e => e.style.display = "none"')
|
||||
done = []
|
||||
|
||||
async def select_text() -> None:
|
||||
done.append(False)
|
||||
await textarea.select_text(timeout=3000)
|
||||
done.append(True)
|
||||
|
||||
promise = asyncio.create_task(select_text())
|
||||
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
|
||||
await page.evaluate("() => new Promise(f => setTimeout(f, 1000))")
|
||||
await textarea.evaluate('e => e.style.display = "block"')
|
||||
await promise
|
||||
assert done == [False, True]
|
||||
|
||||
|
||||
async def test_a_nice_preview(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/dom.html")
|
||||
outer = await page.query_selector("#outer")
|
||||
inner = await page.query_selector("#inner")
|
||||
assert inner
|
||||
check = await page.query_selector("#check")
|
||||
text = await inner.evaluate_handle("e => e.firstChild")
|
||||
await 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"/>'
|
||||
)
|
||||
|
||||
|
||||
async def test_get_attribute(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = await page.query_selector("#outer")
|
||||
assert handle
|
||||
assert await handle.get_attribute("name") == "value"
|
||||
assert await page.get_attribute("#outer", "name") == "value"
|
||||
|
||||
|
||||
async def test_inner_html(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = await page.query_selector("#outer")
|
||||
assert handle
|
||||
assert await handle.inner_html() == '<div id="inner">Text,\nmore text</div>'
|
||||
assert await page.inner_html("#outer") == '<div id="inner">Text,\nmore text</div>'
|
||||
|
||||
|
||||
async def test_inner_text(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = await page.query_selector("#inner")
|
||||
assert handle
|
||||
assert await handle.inner_text() == "Text, more text"
|
||||
assert await page.inner_text("#inner") == "Text, more text"
|
||||
|
||||
|
||||
async def test_inner_text_should_throw(page: Page, server: Server) -> None:
|
||||
await page.set_content("<svg>text</svg>")
|
||||
with pytest.raises(Error) as exc_info1:
|
||||
await page.inner_text("svg")
|
||||
assert " Node is not an HTMLElement" in exc_info1.value.message
|
||||
|
||||
handle = await page.query_selector("svg")
|
||||
assert handle
|
||||
with pytest.raises(Error) as exc_info2:
|
||||
await handle.inner_text()
|
||||
assert " Node is not an HTMLElement" in exc_info2.value.message
|
||||
|
||||
|
||||
async def test_text_content(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/dom.html")
|
||||
handle = await page.query_selector("#inner")
|
||||
assert handle
|
||||
assert await handle.text_content() == "Text,\nmore text"
|
||||
assert await page.text_content("#inner") == "Text,\nmore text"
|
||||
|
||||
|
||||
async def test_check_the_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox"></input>')
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
await input.check()
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
|
||||
|
||||
async def test_uncheck_the_box(page: Page) -> None:
|
||||
await page.set_content('<input id="checkbox" type="checkbox" checked></input>')
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
await input.uncheck()
|
||||
assert await page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
async def test_select_single_option(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
select = await page.query_selector("select")
|
||||
assert select
|
||||
await select.select_option(value="blue")
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_focus_a_button(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/button.html")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
assert await button.evaluate("button => document.activeElement === button") is False
|
||||
await button.focus()
|
||||
assert await button.evaluate("button => document.activeElement === button")
|
||||
|
||||
|
||||
async def test_is_visible_and_is_hidden_should_work(page: Page) -> None:
|
||||
await page.set_content("<div>Hi</div><span></span>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
assert await div.is_visible()
|
||||
assert await div.is_hidden() is False
|
||||
assert await page.is_visible("div")
|
||||
assert await page.is_hidden("div") is False
|
||||
span = await page.query_selector("span")
|
||||
assert span
|
||||
assert await span.is_visible() is False
|
||||
assert await span.is_hidden()
|
||||
assert await page.is_visible("span") is False
|
||||
assert await page.is_hidden("span")
|
||||
|
||||
|
||||
async def test_is_enabled_and_is_disabled_should_work(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<button disabled>button1</button>
|
||||
<button>button2</button>
|
||||
<div>div</div>
|
||||
"""
|
||||
)
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
assert await div.is_enabled()
|
||||
assert await div.is_disabled() is False
|
||||
assert await page.is_enabled("div")
|
||||
assert await page.is_disabled("div") is False
|
||||
button1 = await page.query_selector(":text('button1')")
|
||||
assert button1
|
||||
assert await button1.is_enabled() is False
|
||||
assert await button1.is_disabled()
|
||||
assert await page.is_enabled(":text('button1')") is False
|
||||
assert await page.is_disabled(":text('button1')")
|
||||
button2 = await page.query_selector(":text('button2')")
|
||||
assert button2
|
||||
assert await button2.is_enabled()
|
||||
assert await button2.is_disabled() is False
|
||||
assert await page.is_enabled(":text('button2')")
|
||||
assert await page.is_disabled(":text('button2')") is False
|
||||
|
||||
|
||||
async def test_is_editable_should_work(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"<input id=input1 disabled><textarea></textarea><input id=input2>"
|
||||
)
|
||||
await page.eval_on_selector("textarea", "t => t.readOnly = true")
|
||||
input1 = await page.query_selector("#input1")
|
||||
assert input1
|
||||
assert await input1.is_editable() is False
|
||||
assert await page.is_editable("#input1") is False
|
||||
input2 = await page.query_selector("#input2")
|
||||
assert input2
|
||||
assert await input2.is_editable()
|
||||
assert await page.is_editable("#input2")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
assert await textarea.is_editable() is False
|
||||
assert await page.is_editable("textarea") is False
|
||||
|
||||
|
||||
async def test_is_checked_should_work(page: Page) -> None:
|
||||
await page.set_content('<input type="checkbox" checked><div>Not a checkbox</div>')
|
||||
handle = await page.query_selector("input")
|
||||
assert handle
|
||||
assert await handle.is_checked()
|
||||
assert await page.is_checked("input")
|
||||
await handle.evaluate("input => input.checked = false")
|
||||
assert await handle.is_checked() is False
|
||||
assert await page.is_checked("input") is False
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.is_checked("div")
|
||||
assert "Not a checkbox or radio button" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_input_value(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
element = await page.query_selector("input")
|
||||
assert element
|
||||
await element.fill("my-text-content")
|
||||
assert await element.input_value() == "my-text-content"
|
||||
|
||||
await element.fill("")
|
||||
assert await element.input_value() == ""
|
||||
|
||||
|
||||
async def test_set_checked(page: Page) -> None:
|
||||
await page.set_content("`<input id='checkbox' type='checkbox'></input>`")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
await input.set_checked(True)
|
||||
assert await page.evaluate("checkbox.checked")
|
||||
await input.set_checked(False)
|
||||
assert await page.evaluate("checkbox.checked") is False
|
||||
|
||||
|
||||
async def test_should_allow_disposing_twice(page: Page) -> None:
|
||||
await page.set_content("<section>39</section>")
|
||||
element = await page.query_selector("section")
|
||||
assert element
|
||||
await element.dispose()
|
||||
await element.dispose()
|
||||
@@ -0,0 +1,158 @@
|
||||
# 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 typing import List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import ElementHandle, Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def give_it_a_chance_to_resolve(page: Page) -> None:
|
||||
for i in range(5):
|
||||
await page.evaluate(
|
||||
"() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))"
|
||||
)
|
||||
|
||||
|
||||
async def wait_for_state(div: ElementHandle, state: str, done: List[bool]) -> None:
|
||||
await div.wait_for_element_state(state) # type: ignore
|
||||
done[0] = True
|
||||
|
||||
|
||||
async def wait_for_state_to_throw(
|
||||
div: ElementHandle, state: str
|
||||
) -> pytest.ExceptionInfo[Error]:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await div.wait_for_element_state(state) # type: ignore
|
||||
return exc_info
|
||||
|
||||
|
||||
async def test_should_wait_for_visible(page: Page) -> None:
|
||||
await page.set_content('<div style="display:none">content</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(div, "visible", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
assert div
|
||||
await div.evaluate('div => div.style.display = "block"')
|
||||
await promise
|
||||
|
||||
|
||||
async def test_should_wait_for_already_visible(page: Page) -> None:
|
||||
await page.set_content("<div>content</div>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
await div.wait_for_element_state("visible")
|
||||
|
||||
|
||||
async def test_should_timeout_waiting_for_visible(page: Page) -> None:
|
||||
await page.set_content('<div style="display:none">content</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await div.wait_for_element_state("visible", timeout=1000)
|
||||
assert "Timeout 1000ms exceeded" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_throw_waiting_for_visible_when_detached(page: Page) -> None:
|
||||
await page.set_content('<div style="display:none">content</div>')
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
promise = asyncio.create_task(wait_for_state_to_throw(div, "visible"))
|
||||
await div.evaluate("div => div.remove()")
|
||||
exc_info = await promise
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_wait_for_hidden(page: Page) -> None:
|
||||
await page.set_content("<div>content</div>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(div, "hidden", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
await div.evaluate('div => div.style.display = "none"')
|
||||
await promise
|
||||
|
||||
|
||||
async def test_should_wait_for_already_hidden(page: Page) -> None:
|
||||
await page.set_content("<div></div>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
await div.wait_for_element_state("hidden")
|
||||
|
||||
|
||||
async def test_should_wait_for_hidden_when_detached(page: Page) -> None:
|
||||
await page.set_content("<div>content</div>")
|
||||
div = await page.query_selector("div")
|
||||
assert div
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(div, "hidden", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
assert div
|
||||
await div.evaluate("div => div.remove()")
|
||||
await promise
|
||||
|
||||
|
||||
async def test_should_wait_for_enabled_button(page: Page, server: Server) -> None:
|
||||
await page.set_content("<button disabled><span>Target</span></button>")
|
||||
span = await page.query_selector("text=Target")
|
||||
assert span
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(span, "enabled", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
await span.evaluate("span => span.parentElement.disabled = false")
|
||||
await promise
|
||||
|
||||
|
||||
async def test_should_throw_waiting_for_enabled_when_detached(page: Page) -> None:
|
||||
await page.set_content("<button disabled>Target</button>")
|
||||
button = await page.query_selector("button")
|
||||
assert button
|
||||
promise = asyncio.create_task(wait_for_state_to_throw(button, "enabled"))
|
||||
await button.evaluate("button => button.remove()")
|
||||
exc_info = await promise
|
||||
assert "Element is not attached to the DOM" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_wait_for_disabled_button(page: Page) -> None:
|
||||
await page.set_content("<button><span>Target</span></button>")
|
||||
span = await page.query_selector("text=Target")
|
||||
assert span
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(span, "disabled", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
await span.evaluate("span => span.parentElement.disabled = true")
|
||||
await promise
|
||||
|
||||
|
||||
async def test_should_wait_for_editable_input(page: Page, server: Server) -> None:
|
||||
await page.set_content("<input readonly>")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
done = [False]
|
||||
promise = asyncio.create_task(wait_for_state(input, "editable", done))
|
||||
await give_it_a_chance_to_resolve(page)
|
||||
assert done[0] is False
|
||||
await input.evaluate("input => input.readOnly = false")
|
||||
await promise
|
||||
@@ -0,0 +1,151 @@
|
||||
# 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 playwright.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async def test_should_think_that_it_is_focused_by_default(page: Page) -> None:
|
||||
assert await page.evaluate("document.hasFocus()")
|
||||
|
||||
|
||||
async def test_should_think_that_all_pages_are_focused(page: Page) -> None:
|
||||
page2 = await page.context.new_page()
|
||||
assert await page.evaluate("document.hasFocus()")
|
||||
assert await page2.evaluate("document.hasFocus()")
|
||||
await page2.close()
|
||||
|
||||
|
||||
async def test_should_focus_popups_by_default(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate("url => { window.open(url); }", server.EMPTY_PAGE)
|
||||
popup = await popup_info.value
|
||||
assert await popup.evaluate("document.hasFocus()")
|
||||
assert await page.evaluate("document.hasFocus()")
|
||||
|
||||
|
||||
async def test_should_provide_target_for_keyboard_events(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page2 = await page.context.new_page()
|
||||
await asyncio.gather(
|
||||
page.goto(server.PREFIX + "/input/textarea.html"),
|
||||
page2.goto(server.PREFIX + "/input/textarea.html"),
|
||||
)
|
||||
await asyncio.gather(
|
||||
page.focus("input"),
|
||||
page2.focus("input"),
|
||||
)
|
||||
text = "first"
|
||||
text2 = "second"
|
||||
await asyncio.gather(
|
||||
page.keyboard.type(text),
|
||||
page2.keyboard.type(text2),
|
||||
)
|
||||
results = await asyncio.gather(
|
||||
page.evaluate("result"),
|
||||
page2.evaluate("result"),
|
||||
)
|
||||
assert results == [text, text2]
|
||||
|
||||
|
||||
async def test_should_not_affect_mouse_event_target_page(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
page2 = await page.context.new_page()
|
||||
click_counter = """() => {
|
||||
document.onclick = () => window.click_count = (window.click_count || 0) + 1;
|
||||
}"""
|
||||
await asyncio.gather(
|
||||
page.evaluate(click_counter),
|
||||
page2.evaluate(click_counter),
|
||||
page.focus("body"),
|
||||
page2.focus("body"),
|
||||
)
|
||||
await asyncio.gather(
|
||||
page.mouse.click(1, 1),
|
||||
page2.mouse.click(1, 1),
|
||||
)
|
||||
counters = await asyncio.gather(
|
||||
page.evaluate("window.click_count"),
|
||||
page2.evaluate("window.click_count"),
|
||||
)
|
||||
assert counters == [1, 1]
|
||||
|
||||
|
||||
async def test_should_change_document_activeElement(page: Page, server: Server) -> None:
|
||||
page2 = await page.context.new_page()
|
||||
await asyncio.gather(
|
||||
page.goto(server.PREFIX + "/input/textarea.html"),
|
||||
page2.goto(server.PREFIX + "/input/textarea.html"),
|
||||
)
|
||||
await asyncio.gather(
|
||||
page.focus("input"),
|
||||
page2.focus("textarea"),
|
||||
)
|
||||
active = await asyncio.gather(
|
||||
page.evaluate("document.activeElement.tagName"),
|
||||
page2.evaluate("document.activeElement.tagName"),
|
||||
)
|
||||
assert active == ["INPUT", "TEXTAREA"]
|
||||
|
||||
|
||||
async def test_should_change_focused_iframe(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
[frame1, frame2] = await asyncio.gather(
|
||||
utils.attach_frame(page, "frame1", server.PREFIX + "/input/textarea.html"),
|
||||
utils.attach_frame(page, "frame2", server.PREFIX + "/input/textarea.html"),
|
||||
)
|
||||
logger = """() => {
|
||||
self._events = [];
|
||||
const element = document.querySelector('input');
|
||||
element.onfocus = element.onblur = (e) => self._events.push(e.type);
|
||||
}"""
|
||||
await asyncio.gather(
|
||||
frame1.evaluate(logger),
|
||||
frame2.evaluate(logger),
|
||||
)
|
||||
focused = await asyncio.gather(
|
||||
frame1.evaluate("document.hasFocus()"),
|
||||
frame2.evaluate("document.hasFocus()"),
|
||||
)
|
||||
assert focused == [False, False]
|
||||
await frame1.focus("input")
|
||||
events = await asyncio.gather(
|
||||
frame1.evaluate("self._events"),
|
||||
frame2.evaluate("self._events"),
|
||||
)
|
||||
assert events == [["focus"], []]
|
||||
focused = await asyncio.gather(
|
||||
frame1.evaluate("document.hasFocus()"),
|
||||
frame2.evaluate("document.hasFocus()"),
|
||||
)
|
||||
assert focused == [True, False]
|
||||
await frame2.focus("input")
|
||||
events = await asyncio.gather(
|
||||
frame1.evaluate("self._events"),
|
||||
frame2.evaluate("self._events"),
|
||||
)
|
||||
assert events == [["focus", "blur"], ["focus"]]
|
||||
focused = await asyncio.gather(
|
||||
frame1.evaluate("document.hasFocus()"),
|
||||
frame2.evaluate("document.hasFocus()"),
|
||||
)
|
||||
assert focused == [False, True]
|
||||
@@ -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.async_api import Page, TimeoutError, expect
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_to_be_in_viewport_should_work(page: Page, server: Server) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div id=big style="height: 10000px;"></div>
|
||||
<div id=small>foo</div>
|
||||
"""
|
||||
)
|
||||
await expect(page.locator("#big")).to_be_in_viewport()
|
||||
await expect(page.locator("#small")).not_to_be_in_viewport()
|
||||
await page.locator("#small").scroll_into_view_if_needed()
|
||||
await expect(page.locator("#small")).to_be_in_viewport()
|
||||
await expect(page.locator("#small")).to_be_in_viewport(ratio=1)
|
||||
|
||||
|
||||
async def test_to_be_in_viewport_should_respect_ratio_option(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<style>body, div, html { padding: 0; margin: 0; }</style>
|
||||
<div id=big style="height: 400vh;"></div>
|
||||
"""
|
||||
)
|
||||
await expect(page.locator("div")).to_be_in_viewport()
|
||||
await expect(page.locator("div")).to_be_in_viewport(ratio=0.1)
|
||||
await expect(page.locator("div")).to_be_in_viewport(ratio=0.2)
|
||||
|
||||
await expect(page.locator("div")).to_be_in_viewport(ratio=0.25)
|
||||
# In this test, element's ratio is 0.25.
|
||||
await expect(page.locator("div")).not_to_be_in_viewport(ratio=0.26)
|
||||
|
||||
await expect(page.locator("div")).not_to_be_in_viewport(ratio=0.3)
|
||||
await expect(page.locator("div")).not_to_be_in_viewport(ratio=0.7)
|
||||
await expect(page.locator("div")).not_to_be_in_viewport(ratio=0.8)
|
||||
|
||||
|
||||
async def test_to_be_in_viewport_should_have_good_stack(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
with pytest.raises(AssertionError) as exc_info:
|
||||
await expect(page.locator("body")).not_to_be_in_viewport(timeout=1000)
|
||||
assert 'unexpected value "viewport ratio' in str(exc_info.value)
|
||||
|
||||
|
||||
async def test_to_be_in_viewport_should_report_intersection_even_if_fully_covered_by_other_element(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<h1>hello</h1>
|
||||
<div style="position: relative; height: 10000px; top: -5000px;></div>
|
||||
"""
|
||||
)
|
||||
await expect(page.locator("h1")).to_be_in_viewport()
|
||||
|
||||
|
||||
async def test_should_have_timeout_error_name(page: Page) -> None:
|
||||
with pytest.raises(TimeoutError) as exc_info:
|
||||
await page.wait_for_selector("#not-found", timeout=1)
|
||||
assert exc_info.value.name == "TimeoutError"
|
||||
@@ -0,0 +1,125 @@
|
||||
# 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 pathlib import Path
|
||||
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, List, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserContext, BrowserType
|
||||
|
||||
from ..server import Server
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
async def launch_persistent_context(
|
||||
browser_type: BrowserType,
|
||||
browser_channel: Optional[str],
|
||||
tmp_path: Path,
|
||||
launch_arguments: Dict[str, Any],
|
||||
is_headless_shell: bool,
|
||||
) -> AsyncGenerator[Callable[..., Awaitable[BrowserContext]], 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] = []
|
||||
|
||||
async def launch(extension_path: str, **kwargs: Any) -> BrowserContext:
|
||||
context = await 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:
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_give_access_to_the_service_worker(
|
||||
launch_persistent_context: Callable[..., Awaitable[BrowserContext]],
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
extension_path = str(assetdir / "extension-mv3-simple")
|
||||
context = await launch_persistent_context(extension_path)
|
||||
service_workers = context.service_workers
|
||||
service_worker = (
|
||||
service_workers[0]
|
||||
if len(service_workers)
|
||||
else await context.wait_for_event("serviceworker")
|
||||
)
|
||||
assert service_worker
|
||||
assert service_worker in context.service_workers
|
||||
while not await service_worker.evaluate("globalThis.MAGIC") == 42:
|
||||
await context.pages[0].wait_for_timeout(100)
|
||||
await context.close()
|
||||
assert len(context.background_pages) == 0
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_give_access_to_the_service_worker_when_recording_video(
|
||||
launch_persistent_context: Callable[..., Awaitable[BrowserContext]],
|
||||
tmp_path: Path,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
extension_path = str(assetdir / "extension-mv3-simple")
|
||||
context = await 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 await context.wait_for_event("serviceworker")
|
||||
)
|
||||
assert service_worker
|
||||
assert service_worker in context.service_workers
|
||||
while not await service_worker.evaluate("globalThis.MAGIC") == 42:
|
||||
await context.pages[0].wait_for_timeout(100)
|
||||
await context.close()
|
||||
assert len(context.background_pages) == 0
|
||||
|
||||
|
||||
# https://github.com/microsoft/playwright/issues/32762
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_should_report_console_messages_from_content_script(
|
||||
launch_persistent_context: Callable[..., Awaitable[BrowserContext]],
|
||||
assetdir: Path,
|
||||
server: Server,
|
||||
) -> None:
|
||||
extension_path = str(assetdir / "extension-mv3-with-logging")
|
||||
context = await launch_persistent_context(extension_path)
|
||||
page = await context.new_page()
|
||||
[message, _] = await asyncio.gather(
|
||||
page.context.wait_for_event(
|
||||
"console",
|
||||
lambda e: "Test console log from a third-party execution context" in e.text,
|
||||
),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
assert "Test console log from a third-party execution context" in message.text
|
||||
await context.close()
|
||||
@@ -0,0 +1,473 @@
|
||||
# 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
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, cast
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
Error,
|
||||
FilePayload,
|
||||
FormData,
|
||||
Page,
|
||||
)
|
||||
from tests.server import Server, TestServerRequest
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_get_should_work(context: BrowserContext, server: Server) -> None:
|
||||
response = await 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 await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
async def test_fetch_should_work(context: BrowserContext, server: Server) -> None:
|
||||
response = await 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 await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
async 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"):
|
||||
await context.request.fetch(server.PREFIX + "/test")
|
||||
|
||||
|
||||
async def test_should_add_session_cookies_to_request(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"url": server.EMPTY_PAGE,
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": "Lax",
|
||||
}
|
||||
]
|
||||
)
|
||||
[server_req, response] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.get(server.EMPTY_PAGE),
|
||||
)
|
||||
assert server_req.getHeader("Cookie") == "username=John Doe"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
async def test_should_support_query_params(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
expected_params = {"p1": "v1", "парам2": "знач2"}
|
||||
[server_req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
getattr(context.request, method)(
|
||||
server.EMPTY_PAGE + "?p1=foo", params=expected_params
|
||||
),
|
||||
)
|
||||
assert list(map(lambda x: x.decode(), server_req.args["p1".encode()])) == [
|
||||
"foo",
|
||||
"v1",
|
||||
]
|
||||
assert server_req.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
async def test_should_support_params_passed_as_object(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
params = {
|
||||
"param1": "value1",
|
||||
"парам2": "знач2",
|
||||
}
|
||||
[server_req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
getattr(context.request, method)(server.EMPTY_PAGE, params=params),
|
||||
)
|
||||
assert server_req.args["param1".encode()][0].decode() == "value1"
|
||||
assert len(server_req.args["param1".encode()]) == 1
|
||||
assert server_req.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
async def test_should_support_params_passed_as_strings(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
params = "?param1=value1¶m1=value2&парам2=знач2"
|
||||
[server_req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
getattr(context.request, method)(server.EMPTY_PAGE, params=params),
|
||||
)
|
||||
assert list(map(lambda x: x.decode(), server_req.args["param1".encode()])) == [
|
||||
"value1",
|
||||
"value2",
|
||||
]
|
||||
assert len(server_req.args["param1".encode()]) == 2
|
||||
assert server_req.args["парам2".encode()][0].decode() == "знач2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
async def test_should_support_fail_on_status_code(
|
||||
context: BrowserContext, server: Server, method: str
|
||||
) -> None:
|
||||
with pytest.raises(Error, match="404 Not Found"):
|
||||
await 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"]
|
||||
)
|
||||
async def test_should_support_ignore_https_errors_option(
|
||||
context: BrowserContext, https_server: Server, method: str
|
||||
) -> None:
|
||||
response = await getattr(context.request, method)(
|
||||
https_server.EMPTY_PAGE, ignore_https_errors=True
|
||||
)
|
||||
assert response.ok
|
||||
assert response.status == 200
|
||||
|
||||
|
||||
async def test_should_not_add_context_cookie_if_cookie_header_passed_as_parameter(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.add_cookies(
|
||||
[
|
||||
{
|
||||
"name": "username",
|
||||
"value": "John Doe",
|
||||
"url": server.EMPTY_PAGE,
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"secure": False,
|
||||
"sameSite": "Lax",
|
||||
}
|
||||
]
|
||||
)
|
||||
[server_req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.get(server.EMPTY_PAGE, headers={"Cookie": "foo=bar"}),
|
||||
)
|
||||
assert server_req.getHeader("Cookie") == "foo=bar"
|
||||
|
||||
|
||||
async def test_should_support_http_credentials_send_immediately_for_browser_context(
|
||||
context_factory: "Callable[..., asyncio.Future[BrowserContext]]", server: Server
|
||||
) -> None:
|
||||
context = await context_factory(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
"send": "always",
|
||||
}
|
||||
)
|
||||
# First request
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"), context.request.get(server.EMPTY_PAGE)
|
||||
)
|
||||
expected_auth = "Basic " + base64.b64encode(b"user:pass").decode()
|
||||
assert server_request.getHeader("authorization") == expected_auth
|
||||
assert response.status == 200
|
||||
|
||||
# Second request
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.get(server.CROSS_PROCESS_PREFIX + "/empty.html"),
|
||||
)
|
||||
# Not sent to another origin.
|
||||
assert server_request.getHeader("authorization") is None
|
||||
assert response.status == 200
|
||||
|
||||
|
||||
async def test_support_http_credentials_send_immediately_for_browser_new_page(
|
||||
server: Server, browser: Browser
|
||||
) -> None:
|
||||
page = await browser.new_page(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
"send": "always",
|
||||
}
|
||||
)
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"), page.request.get(server.EMPTY_PAGE)
|
||||
)
|
||||
assert (
|
||||
server_request.getHeader("authorization")
|
||||
== "Basic " + base64.b64encode(b"user:pass").decode()
|
||||
)
|
||||
assert response.status == 200
|
||||
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.request.get(server.CROSS_PROCESS_PREFIX + "/empty.html"),
|
||||
)
|
||||
# Not sent to another origin.
|
||||
assert server_request.getHeader("authorization") is None
|
||||
assert response.status == 200
|
||||
|
||||
await page.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["delete", "patch", "post", "put"])
|
||||
async def test_should_support_post_data(
|
||||
context: BrowserContext, method: str, server: Server
|
||||
) -> None:
|
||||
async def support_post_data(fetch_data: Any, request_post_data: Any) -> None:
|
||||
[request, response] = await asyncio.gather(
|
||||
server.wait_for_request("/simple.json"),
|
||||
getattr(context.request, method)(
|
||||
server.PREFIX + "/simple.json", data=fetch_data
|
||||
),
|
||||
)
|
||||
assert request.method.decode() == method.upper()
|
||||
assert request.post_body == request_post_data
|
||||
assert response.status == 200
|
||||
assert response.url == server.PREFIX + "/simple.json"
|
||||
assert request.getHeader("Content-Length") == str(len(must(request.post_body)))
|
||||
|
||||
await support_post_data("My request", "My request".encode())
|
||||
await support_post_data(b"My request", "My request".encode())
|
||||
await support_post_data(["my", "request"], json.dumps(["my", "request"]).encode())
|
||||
await support_post_data({"my": "request"}, json.dumps({"my": "request"}).encode())
|
||||
with pytest.raises(Error, match="Unsupported 'data' type: <class 'function'>"):
|
||||
await support_post_data(lambda: None, None)
|
||||
|
||||
|
||||
async def test_should_support_application_x_www_form_urlencoded(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
[request, response] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(
|
||||
server.PREFIX + "/empty.html",
|
||||
form={
|
||||
"firstName": "John",
|
||||
"lastName": "Doe",
|
||||
"file": "f.js",
|
||||
},
|
||||
),
|
||||
)
|
||||
assert request.method == b"POST"
|
||||
assert request.getHeader("Content-Type") == "application/x-www-form-urlencoded"
|
||||
assert request.post_body
|
||||
body = request.post_body.decode()
|
||||
assert request.getHeader("Content-Length") == str(len(body))
|
||||
params = parse_qs(request.post_body)
|
||||
assert params[b"firstName"] == [b"John"]
|
||||
assert params[b"lastName"] == [b"Doe"]
|
||||
assert params[b"file"] == [b"f.js"]
|
||||
|
||||
|
||||
async 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);",
|
||||
}
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(
|
||||
server.PREFIX + "/empty.html",
|
||||
multipart={
|
||||
"firstName": "John",
|
||||
"lastName": "Doe",
|
||||
"file": file,
|
||||
},
|
||||
),
|
||||
)
|
||||
assert request.method == b"POST"
|
||||
assert cast(str, request.getHeader("Content-Type")).startswith(
|
||||
"multipart/form-data; "
|
||||
)
|
||||
assert must(request.getHeader("Content-Length")) == str(
|
||||
len(must(request.post_body))
|
||||
)
|
||||
assert request.args[b"firstName"] == [b"John"]
|
||||
assert request.args[b"lastName"] == [b"Doe"]
|
||||
assert request.args[b"file"][0] == file["buffer"]
|
||||
|
||||
|
||||
async 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")
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(server.EMPTY_PAGE, form=form),
|
||||
)
|
||||
assert request.getHeader("Content-Type") == "application/x-www-form-urlencoded"
|
||||
params = parse_qs(must(request.post_body))
|
||||
assert params[b"name"] == [b"John", b"Doe"]
|
||||
assert params[b"email"] == [b"john@example.com"]
|
||||
|
||||
|
||||
async def test_should_support_form_data_set_overwrites_previous_values(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
form = FormData()
|
||||
form.append("name", "first")
|
||||
form.append("name", "second")
|
||||
form.set("name", "final")
|
||||
form.set("age", 30)
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(server.EMPTY_PAGE, form=form),
|
||||
)
|
||||
params = parse_qs(must(request.post_body))
|
||||
assert params[b"name"] == [b"final"]
|
||||
assert params[b"age"] == [b"30"]
|
||||
|
||||
|
||||
async 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"):
|
||||
await context.request.post(server.EMPTY_PAGE, form=form)
|
||||
|
||||
|
||||
async 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")
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(server.EMPTY_PAGE, multipart=form),
|
||||
)
|
||||
assert cast(str, request.getHeader("Content-Type")).startswith(
|
||||
"multipart/form-data; "
|
||||
)
|
||||
assert request.args[b"user"] == [b"alice"]
|
||||
assert request.args[b"files"] == [file1["buffer"], file2["buffer"]]
|
||||
|
||||
|
||||
async 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)
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.post(server.EMPTY_PAGE, multipart=form),
|
||||
)
|
||||
assert cast(str, request.getHeader("Content-Type")).startswith(
|
||||
"multipart/form-data; "
|
||||
)
|
||||
assert request.args[b"attachment"] == [b"a,b,c\n1,2,3\n"]
|
||||
|
||||
|
||||
async def test_should_add_default_headers(
|
||||
context: BrowserContext, page: Page, server: Server
|
||||
) -> None:
|
||||
[request, response] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
context.request.get(server.EMPTY_PAGE),
|
||||
)
|
||||
assert request.getHeader("Accept") == "*/*"
|
||||
assert request.getHeader("Accept-Encoding") == "gzip,deflate,br"
|
||||
assert request.getHeader("User-Agent") == await page.evaluate(
|
||||
"() => navigator.userAgent"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_after_context_dispose(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.close(reason="Test ended.")
|
||||
with pytest.raises(Error, match="Test ended."):
|
||||
await context.request.get(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_retry_ECONNRESET(context: BrowserContext, server: Server) -> None:
|
||||
request_count = 0
|
||||
|
||||
def _handle_request(req: TestServerRequest) -> None:
|
||||
nonlocal request_count
|
||||
request_count += 1
|
||||
if request_count <= 3:
|
||||
assert req.transport
|
||||
req.transport.abortConnection()
|
||||
return
|
||||
req.setHeader("content-type", "text/plain")
|
||||
req.write(b"Hello!")
|
||||
req.finish()
|
||||
|
||||
server.set_route("/test", _handle_request)
|
||||
response = await context.request.fetch(server.PREFIX + "/test", max_retries=3)
|
||||
assert response.status == 200
|
||||
assert await response.text() == "Hello!"
|
||||
assert request_count == 4
|
||||
@@ -0,0 +1,555 @@
|
||||
# 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
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import APIResponse, Error, Playwright, StorageState
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["fetch", "delete", "get", "head", "patch", "post", "put"]
|
||||
)
|
||||
async def test_should_work(playwright: Playwright, method: str, server: Server) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
response: APIResponse = await 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 await response.text() == ("" if method == "head" else '{"foo": "bar"}\n')
|
||||
|
||||
|
||||
async def test_should_dispose_global_request(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
response = await request.get(server.PREFIX + "/simple.json")
|
||||
assert await response.json() == {"foo": "bar"}
|
||||
await response.dispose()
|
||||
with pytest.raises(Error, match="Response has been disposed"):
|
||||
await response.body()
|
||||
|
||||
|
||||
async def test_should_dispose_with_custom_error_message(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
await request.dispose(reason="My reason")
|
||||
with pytest.raises(Error, match="My reason"):
|
||||
await request.get(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_support_global_user_agent_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
api_request_context = await playwright.request.new_context(user_agent="My Agent")
|
||||
response = await api_request_context.get(server.PREFIX + "/empty.html")
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
api_request_context.get(server.EMPTY_PAGE),
|
||||
)
|
||||
assert response.ok is True
|
||||
assert response.url == server.EMPTY_PAGE
|
||||
assert request.getHeader("user-agent") == "My Agent"
|
||||
|
||||
|
||||
async def test_should_support_global_timeout_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context(timeout=100)
|
||||
server.set_route("/empty.html", lambda req: None)
|
||||
with pytest.raises(Error, match="Timeout 100ms exceeded"):
|
||||
await request.get(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_support_timeout_option_in_get_method(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
server.set_route("/empty.html", lambda req: None)
|
||||
with pytest.raises(Error, match="APIRequestContext.get: Timeout 123ms exceeded."):
|
||||
await request.get(server.EMPTY_PAGE, timeout=123)
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(
|
||||
extra_http_headers={"My-Secret": "Value"}
|
||||
)
|
||||
[req1, req2, req3, _] = await asyncio.gather(
|
||||
server.wait_for_request("/a/redirect1"),
|
||||
server.wait_for_request("/b/c/redirect2"),
|
||||
server.wait_for_request("/simple.json"),
|
||||
request.get(f"{server.PREFIX}/a/redirect1"),
|
||||
)
|
||||
assert req1.getHeader("my-secret") == "Value"
|
||||
assert req2.getHeader("my-secret") == "Value"
|
||||
assert req3.getHeader("my-secret") == "Value"
|
||||
|
||||
|
||||
async def test_should_support_global_http_credentials_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request1 = await playwright.request.new_context()
|
||||
response1 = await request1.get(server.EMPTY_PAGE)
|
||||
assert response1.status == 401
|
||||
await response1.dispose()
|
||||
|
||||
request2 = await playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
response2 = await request2.get(server.EMPTY_PAGE)
|
||||
assert response2.status == 200
|
||||
assert response2.ok is True
|
||||
await response2.dispose()
|
||||
|
||||
|
||||
async def test_should_return_error_with_wrong_credentials(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = await playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "wrong"}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
assert response.ok is False
|
||||
|
||||
|
||||
async def test_should_work_with_correct_credentials_and_matching_origin(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = await playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX,
|
||||
}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async def test_should_return_error_with_correct_credentials_and_mismatching_scheme(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/empty.html", "user", "pass")
|
||||
request = await playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.replace("http://", "https://"),
|
||||
}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(
|
||||
http_credentials={"username": "user", "password": "pass", "origin": origin}
|
||||
)
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
assert response.status == 401
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async def test_support_http_credentials_send_immediately(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context(
|
||||
http_credentials={
|
||||
"username": "user",
|
||||
"password": "pass",
|
||||
"origin": server.PREFIX.upper(),
|
||||
"send": "always",
|
||||
}
|
||||
)
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"), request.get(server.EMPTY_PAGE)
|
||||
)
|
||||
assert (
|
||||
server_request.getHeader("authorization")
|
||||
== "Basic " + base64.b64encode(b"user:pass").decode()
|
||||
)
|
||||
assert response.status == 200
|
||||
|
||||
server_request, response = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.get(server.CROSS_PROCESS_PREFIX + "/empty.html"),
|
||||
)
|
||||
# Not sent to another origin.
|
||||
assert server_request.getHeader("authorization") is None
|
||||
assert response.status == 200
|
||||
|
||||
|
||||
async def test_should_support_global_ignore_https_errors_option(
|
||||
playwright: Playwright, https_server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context(ignore_https_errors=True)
|
||||
response = await request.get(https_server.EMPTY_PAGE)
|
||||
assert response.status == 200
|
||||
assert response.ok is True
|
||||
assert response.url == https_server.EMPTY_PAGE
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async def test_should_resolve_url_relative_to_global_base_url_option(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context(base_url=server.PREFIX)
|
||||
response = await request.get("/empty.html")
|
||||
assert response.status == 200
|
||||
assert response.ok is True
|
||||
assert response.url == server.EMPTY_PAGE
|
||||
await response.dispose()
|
||||
|
||||
|
||||
async def test_should_use_playwright_as_a_user_agent(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
[server_req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.get(server.EMPTY_PAGE),
|
||||
)
|
||||
assert str(server_req.getHeader("User-Agent")).startswith("Playwright/")
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async def test_should_return_empty_body(playwright: Playwright, server: Server) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
response = await request.get(server.EMPTY_PAGE)
|
||||
body = await response.body()
|
||||
assert len(body) == 0
|
||||
assert await response.text() == ""
|
||||
await request.dispose()
|
||||
with pytest.raises(Error, match="Response has been disposed"):
|
||||
await response.body()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(storage_state=expected)
|
||||
path = tmp_path / "storage-state.json"
|
||||
actual = await request.storage_state(path=path)
|
||||
assert actual == expected
|
||||
|
||||
written = path.read_text("utf8")
|
||||
assert json.loads(written) == expected
|
||||
|
||||
request2 = await playwright.request.new_context(storage_state=path)
|
||||
state2 = await request2.storage_state()
|
||||
assert state2 == expected
|
||||
|
||||
|
||||
serialization_data = [
|
||||
[{"foo": "bar"}],
|
||||
[["foo", "bar", 2021]],
|
||||
["foo"],
|
||||
[True],
|
||||
[2021],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("serialization", serialization_data)
|
||||
async def test_should_json_stringify_body_when_content_type_is_application_json(
|
||||
playwright: Playwright, server: Server, serialization: Any
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
[req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.post(
|
||||
server.EMPTY_PAGE,
|
||||
headers={"content-type": "application/json"},
|
||||
data=serialization,
|
||||
),
|
||||
)
|
||||
body = req.post_body
|
||||
assert body
|
||||
assert body.decode() == json.dumps(serialization)
|
||||
await request.dispose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("serialization", serialization_data)
|
||||
async def test_should_not_double_stringify_body_when_content_type_is_application_json(
|
||||
playwright: Playwright, server: Server, serialization: Any
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
stringified_value = json.dumps(serialization)
|
||||
[req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.post(
|
||||
server.EMPTY_PAGE,
|
||||
headers={"content-type": "application/json"},
|
||||
data=stringified_value,
|
||||
),
|
||||
)
|
||||
|
||||
body = req.post_body
|
||||
assert body
|
||||
assert body.decode() == stringified_value
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async def test_should_accept_already_serialized_data_as_bytes_when_content_type_is_application_json(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
stringified_value = json.dumps({"foo": "bar"}).encode()
|
||||
[req, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.post(
|
||||
server.EMPTY_PAGE,
|
||||
headers={"content-type": "application/json"},
|
||||
data=stringified_value,
|
||||
),
|
||||
)
|
||||
body = req.post_body
|
||||
assert body == stringified_value
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async def test_should_contain_default_user_agent(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
[server_request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
request.get(server.EMPTY_PAGE),
|
||||
)
|
||||
user_agent = server_request.getHeader("user-agent")
|
||||
assert user_agent
|
||||
assert "python" in user_agent
|
||||
assert f"{sys.version_info.major}.{sys.version_info.minor}" in user_agent
|
||||
|
||||
|
||||
async 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 = await 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:
|
||||
await request.fetch(
|
||||
server.PREFIX + "/a/redirect1",
|
||||
method=method,
|
||||
max_redirects=max_redirects,
|
||||
)
|
||||
assert "Max redirect count exceeded" in str(exc_info)
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context()
|
||||
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
|
||||
response = await request.fetch(
|
||||
server.PREFIX + "/a/redirect1", method=method, max_redirects=0
|
||||
)
|
||||
assert response.headers["location"] == "/b/c/redirect2"
|
||||
assert response.status == 302
|
||||
|
||||
|
||||
async def test_should_throw_an_error_when_max_redirects_is_less_than_0(
|
||||
playwright: Playwright,
|
||||
server: Server,
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
|
||||
with pytest.raises(AssertionError) as exc_info:
|
||||
await 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)
|
||||
|
||||
|
||||
async def test_should_serialize_request_data(
|
||||
playwright: Playwright, server: Server
|
||||
) -> None:
|
||||
request = await playwright.request.new_context()
|
||||
server.set_route("/echo", lambda req: (req.write(req.post_body), req.finish()))
|
||||
for data, expected in [
|
||||
({"foo": None}, '{"foo": null}'),
|
||||
([], "[]"),
|
||||
({}, "{}"),
|
||||
("", ""),
|
||||
]:
|
||||
response = await request.post(server.PREFIX + "/echo", data=data)
|
||||
assert response.status == 200
|
||||
assert await response.text() == expected
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async def test_should_retry_ECONNRESET(playwright: Playwright, server: Server) -> None:
|
||||
request_count = 0
|
||||
|
||||
def _handle_request(req: TestServerRequest) -> None:
|
||||
nonlocal request_count
|
||||
request_count += 1
|
||||
if request_count <= 3:
|
||||
assert req.transport
|
||||
req.transport.abortConnection()
|
||||
return
|
||||
req.setHeader("content-type", "text/plain")
|
||||
req.write(b"Hello!")
|
||||
req.finish()
|
||||
|
||||
server.set_route("/test", _handle_request)
|
||||
request = await playwright.request.new_context()
|
||||
response = await request.fetch(server.PREFIX + "/test", max_retries=3)
|
||||
assert response.status == 200
|
||||
assert await response.text() == "Hello!"
|
||||
assert request_count == 4
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(fail_on_status_code=True)
|
||||
with pytest.raises(Error, match="404 Not Found"):
|
||||
await request.fetch(server.EMPTY_PAGE)
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(fail_on_status_code=False)
|
||||
response = await request.fetch(server.EMPTY_PAGE)
|
||||
assert response.status == 404
|
||||
await request.dispose()
|
||||
|
||||
|
||||
async 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 = await playwright.request.new_context(max_redirects=1)
|
||||
with pytest.raises(Error, match="Max redirect count exceeded"):
|
||||
await request.fetch(server.EMPTY_PAGE)
|
||||
assert redirect_count == 2
|
||||
await request.dispose()
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_fill_textarea(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
await page.fill("textarea", "some value")
|
||||
assert await page.evaluate("result") == "some value"
|
||||
|
||||
|
||||
async def test_is_enabled_for_non_editable_button(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<button>button</button>
|
||||
"""
|
||||
)
|
||||
button = page.locator("button")
|
||||
assert await button.is_enabled() is True
|
||||
|
||||
|
||||
async def test_fill_input(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
await page.fill("input", "some value")
|
||||
assert await page.evaluate("result") == "some value"
|
||||
@@ -0,0 +1,110 @@
|
||||
# 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.async_api import Page
|
||||
|
||||
|
||||
async def test_should_work(page: Page) -> None:
|
||||
await page.set_content("<div id=d1 tabIndex=0></div>")
|
||||
assert await page.evaluate("() => document.activeElement.nodeName") == "BODY"
|
||||
await page.focus("#d1")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "d1"
|
||||
|
||||
|
||||
async def test_should_emit_focus_event(page: Page) -> None:
|
||||
await page.set_content("<div id=d1 tabIndex=0></div>")
|
||||
focused = []
|
||||
await page.expose_function("focusEvent", lambda: focused.append(True))
|
||||
await page.evaluate("() => d1.addEventListener('focus', focusEvent)")
|
||||
await page.focus("#d1")
|
||||
assert focused == [True]
|
||||
|
||||
|
||||
async def test_should_emit_blur_event(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"<div id=d1 tabIndex=0>DIV1</div><div id=d2 tabIndex=0>DIV2</div>"
|
||||
)
|
||||
await page.focus("#d1")
|
||||
focused = []
|
||||
blurred = []
|
||||
await page.expose_function("focusEvent", lambda: focused.append(True))
|
||||
await page.expose_function("blurEvent", lambda: blurred.append(True))
|
||||
await page.evaluate("() => d1.addEventListener('blur', blurEvent)")
|
||||
await page.evaluate("() => d2.addEventListener('focus', focusEvent)")
|
||||
await page.focus("#d2")
|
||||
assert focused == [True]
|
||||
assert blurred == [True]
|
||||
|
||||
|
||||
async def test_should_traverse_focus(page: Page) -> None:
|
||||
await page.set_content('<input id="i1"><input id="i2">')
|
||||
focused = []
|
||||
await page.expose_function("focusEvent", lambda: focused.append(True))
|
||||
await page.evaluate("() => i2.addEventListener('focus', focusEvent)")
|
||||
|
||||
await page.focus("#i1")
|
||||
await page.keyboard.type("First")
|
||||
await page.keyboard.press("Tab")
|
||||
await page.keyboard.type("Last")
|
||||
|
||||
assert focused == [True]
|
||||
assert await page.eval_on_selector("#i1", "e => e.value") == "First"
|
||||
assert await page.eval_on_selector("#i2", "e => e.value") == "Last"
|
||||
|
||||
|
||||
async def test_should_traverse_focus_in_all_directions(page: Page) -> None:
|
||||
await page.set_content('<input value="1"><input value="2"><input value="3">')
|
||||
await page.keyboard.press("Tab")
|
||||
assert await page.evaluate("() => document.activeElement.value") == "1"
|
||||
await page.keyboard.press("Tab")
|
||||
assert await page.evaluate("() => document.activeElement.value") == "2"
|
||||
await page.keyboard.press("Tab")
|
||||
assert await page.evaluate("() => document.activeElement.value") == "3"
|
||||
await page.keyboard.press("Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.value") == "2"
|
||||
await page.keyboard.press("Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.value") == "1"
|
||||
|
||||
|
||||
@pytest.mark.only_platform("darwin")
|
||||
@pytest.mark.only_browser("webkit")
|
||||
async def test_should_traverse_only_form_elements(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<input id="input-1">
|
||||
<button id="button">button</button>
|
||||
<a href id="link">link</a>
|
||||
<input id="input-2">
|
||||
"""
|
||||
)
|
||||
await page.keyboard.press("Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "input-1"
|
||||
await page.keyboard.press("Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "input-2"
|
||||
await page.keyboard.press("Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "input-1"
|
||||
await page.keyboard.press("Alt+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "button"
|
||||
await page.keyboard.press("Alt+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "link"
|
||||
await page.keyboard.press("Alt+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "input-2"
|
||||
await page.keyboard.press("Alt+Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "link"
|
||||
await page.keyboard.press("Alt+Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "button"
|
||||
await page.keyboard.press("Alt+Shift+Tab")
|
||||
assert await page.evaluate("() => document.activeElement.id") == "input-1"
|
||||
@@ -0,0 +1,298 @@
|
||||
# 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 typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async def test_evaluate_handle(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
main_frame = page.main_frame
|
||||
assert main_frame.page == page
|
||||
window_handle = await main_frame.evaluate_handle("window")
|
||||
assert window_handle
|
||||
|
||||
|
||||
async def test_frame_element(page: Page, server: Server, utils: Utils) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame1 = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
assert frame1
|
||||
await utils.attach_frame(page, "frame2", server.EMPTY_PAGE)
|
||||
frame3 = await utils.attach_frame(page, "frame3", server.EMPTY_PAGE)
|
||||
assert frame3
|
||||
frame1handle1 = await page.query_selector("#frame1")
|
||||
assert frame1handle1
|
||||
frame1handle2 = await frame1.frame_element()
|
||||
frame3handle1 = await page.query_selector("#frame3")
|
||||
assert frame3handle1
|
||||
frame3handle2 = await frame3.frame_element()
|
||||
assert await frame1handle1.evaluate("(a, b) => a === b", frame1handle2)
|
||||
assert await frame3handle1.evaluate("(a, b) => a === b", frame3handle2)
|
||||
assert await frame1handle1.evaluate("(a, b) => a === b", frame3handle1) is False
|
||||
|
||||
|
||||
async def test_frame_element_with_content_frame(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
handle = await frame.frame_element()
|
||||
content_frame = await handle.content_frame()
|
||||
assert content_frame == frame
|
||||
|
||||
|
||||
async def test_frame_element_throw_when_detached(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
frame1 = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
await page.eval_on_selector("#frame1", "e => e.remove()")
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await frame1.frame_element()
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert error.message == "Frame.frame_element: Frame has been detached."
|
||||
|
||||
|
||||
async def test_evaluate_throw_for_detached_frames(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
frame1 = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
assert frame1
|
||||
await utils.detach_frame(page, "frame1")
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await frame1.evaluate("7 * 8")
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "Frame was detached" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_isolated_between_frames(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
assert len(page.frames) == 2
|
||||
[frame1, frame2] = page.frames
|
||||
assert frame1 != frame2
|
||||
|
||||
await asyncio.gather(
|
||||
frame1.evaluate("window.a = 1"), frame2.evaluate("window.a = 2")
|
||||
)
|
||||
[a1, a2] = await asyncio.gather(
|
||||
frame1.evaluate("window.a"), frame2.evaluate("window.a")
|
||||
)
|
||||
assert a1 == 1
|
||||
assert a2 == 2
|
||||
|
||||
|
||||
async def test_should_handle_nested_frames(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/frames/nested-frames.html")
|
||||
assert utils.dump_frames(page.main_frame) == [
|
||||
"http://localhost:<PORT>/frames/nested-frames.html",
|
||||
" http://localhost:<PORT>/frames/frame.html (aframe)",
|
||||
" http://localhost:<PORT>/frames/two-frames.html (2frames)",
|
||||
" http://localhost:<PORT>/frames/frame.html (dos)",
|
||||
" http://localhost:<PORT>/frames/frame.html (uno)",
|
||||
]
|
||||
|
||||
|
||||
async def test_should_send_events_when_frames_are_manipulated_dynamically(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
# validate frameattached events
|
||||
attached_frames = []
|
||||
page.on("frameattached", lambda frame: attached_frames.append(frame))
|
||||
await utils.attach_frame(page, "frame1", "./assets/frame.html")
|
||||
assert len(attached_frames) == 1
|
||||
assert "/assets/frame.html" in attached_frames[0].url
|
||||
|
||||
# validate framenavigated events
|
||||
navigated_frames = []
|
||||
page.on("framenavigated", lambda frame: navigated_frames.append(frame))
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
frame = document.getElementById('frame1')
|
||||
frame.src = './empty.html'
|
||||
return new Promise(x => frame.onload = x)
|
||||
}"""
|
||||
)
|
||||
|
||||
assert len(navigated_frames) == 1
|
||||
assert navigated_frames[0].url == server.EMPTY_PAGE
|
||||
|
||||
# validate framedetached events
|
||||
detached_frames = []
|
||||
page.on("framedetached", lambda frame: detached_frames.append(frame))
|
||||
await utils.detach_frame(page, "frame1")
|
||||
assert len(detached_frames) == 1
|
||||
assert detached_frames[0].is_detached()
|
||||
|
||||
|
||||
async def test_framenavigated_when_navigating_on_anchor_urls(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_event("framenavigated"):
|
||||
await page.goto(server.EMPTY_PAGE + "#foo")
|
||||
assert page.url == server.EMPTY_PAGE + "#foo"
|
||||
|
||||
|
||||
async def test_persist_main_frame_on_cross_process_navigation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
main_frame = page.main_frame
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
|
||||
assert page.main_frame == main_frame
|
||||
|
||||
|
||||
async def test_should_not_send_attach_detach_events_for_main_frame(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
has_events = []
|
||||
page.on("frameattached", lambda frame: has_events.append(True))
|
||||
page.on("framedetached", lambda frame: has_events.append(True))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert has_events == []
|
||||
|
||||
|
||||
async def test_detach_child_frames_on_navigation(page: Page, server: Server) -> None:
|
||||
attached_frames = []
|
||||
detached_frames = []
|
||||
navigated_frames = []
|
||||
page.on("frameattached", lambda frame: attached_frames.append(frame))
|
||||
page.on("framedetached", lambda frame: detached_frames.append(frame))
|
||||
page.on("framenavigated", lambda frame: navigated_frames.append(frame))
|
||||
await page.goto(server.PREFIX + "/frames/nested-frames.html")
|
||||
assert len(attached_frames) == 4
|
||||
assert len(detached_frames) == 0
|
||||
assert len(navigated_frames) == 5
|
||||
|
||||
attached_frames = []
|
||||
detached_frames = []
|
||||
navigated_frames = []
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(attached_frames) == 0
|
||||
assert len(detached_frames) == 4
|
||||
assert len(navigated_frames) == 1
|
||||
|
||||
|
||||
async def test_framesets(page: Page, server: Server) -> None:
|
||||
attached_frames = []
|
||||
detached_frames = []
|
||||
navigated_frames = []
|
||||
page.on("frameattached", lambda frame: attached_frames.append(frame))
|
||||
page.on("framedetached", lambda frame: detached_frames.append(frame))
|
||||
page.on("framenavigated", lambda frame: navigated_frames.append(frame))
|
||||
await page.goto(server.PREFIX + "/frames/frameset.html")
|
||||
assert len(attached_frames) == 4
|
||||
assert len(detached_frames) == 0
|
||||
assert len(navigated_frames) == 5
|
||||
|
||||
attached_frames = []
|
||||
detached_frames = []
|
||||
navigated_frames = []
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(attached_frames) == 0
|
||||
assert len(detached_frames) == 4
|
||||
assert len(navigated_frames) == 1
|
||||
|
||||
|
||||
async def test_frame_from_inside_shadow_dom(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/shadow.html")
|
||||
await page.evaluate(
|
||||
"""async url => {
|
||||
frame = document.createElement('iframe');
|
||||
frame.src = url;
|
||||
document.body.shadowRoot.appendChild(frame);
|
||||
await new Promise(x => frame.onload = x);
|
||||
}""",
|
||||
server.EMPTY_PAGE,
|
||||
)
|
||||
assert len(page.frames) == 2
|
||||
assert page.frames[1].url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_frame_name(page: Page, server: Server, utils: Utils) -> None:
|
||||
await utils.attach_frame(page, "theFrameId", server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""url => {
|
||||
frame = document.createElement('iframe');
|
||||
frame.name = 'theFrameName';
|
||||
frame.src = url;
|
||||
document.body.appendChild(frame);
|
||||
return new Promise(x => frame.onload = x);
|
||||
}""",
|
||||
server.EMPTY_PAGE,
|
||||
)
|
||||
assert page.frames[0].name == ""
|
||||
assert page.frames[1].name == "theFrameId"
|
||||
assert page.frames[2].name == "theFrameName"
|
||||
|
||||
|
||||
async def test_frame_parent(page: Page, server: Server, utils: Utils) -> None:
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame2", server.EMPTY_PAGE)
|
||||
assert page.frames[0].parent_frame is None
|
||||
assert page.frames[1].parent_frame == page.main_frame
|
||||
assert page.frames[2].parent_frame == page.main_frame
|
||||
|
||||
|
||||
async def test_should_report_different_frame_instance_when_frame_re_attaches(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
frame1 = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.frame = document.querySelector('#frame1')
|
||||
window.frame.remove()
|
||||
}"""
|
||||
)
|
||||
|
||||
assert frame1.is_detached()
|
||||
async with page.expect_event("frameattached") as frame2_info:
|
||||
await page.evaluate("() => document.body.appendChild(window.frame)")
|
||||
|
||||
frame2 = await frame2_info.value
|
||||
assert frame2.is_detached() is False
|
||||
assert frame1 != frame2
|
||||
|
||||
|
||||
async def test_strict_mode(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<button>Hello</button>
|
||||
<button>Hello</button>
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error):
|
||||
await page.text_content("button", strict=True)
|
||||
with pytest.raises(Error):
|
||||
await page.query_selector("button", strict=True)
|
||||
@@ -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.
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server, context: BrowserContext) -> None:
|
||||
await context.grant_permissions(["geolocation"])
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.set_geolocation({"latitude": 10, "longitude": 10})
|
||||
geolocation = await page.evaluate(
|
||||
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
|
||||
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
|
||||
}))"""
|
||||
)
|
||||
assert geolocation == {"latitude": 10, "longitude": 10}
|
||||
|
||||
|
||||
async def test_should_throw_when_invalid_longitude(context: BrowserContext) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
await context.set_geolocation({"latitude": 10, "longitude": 200})
|
||||
assert (
|
||||
"geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed."
|
||||
in exc.value.message
|
||||
)
|
||||
|
||||
|
||||
async def test_should_isolate_contexts(
|
||||
page: Page, server: Server, context: BrowserContext, browser: Browser
|
||||
) -> None:
|
||||
await context.grant_permissions(["geolocation"])
|
||||
await context.set_geolocation({"latitude": 10, "longitude": 10})
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
context2 = await browser.new_context(
|
||||
permissions=["geolocation"], geolocation={"latitude": 10.5, "longitude": 10.5}
|
||||
)
|
||||
|
||||
page2 = await context2.new_page()
|
||||
await page2.goto(server.EMPTY_PAGE)
|
||||
|
||||
geolocation = await page.evaluate(
|
||||
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
|
||||
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
|
||||
}))"""
|
||||
)
|
||||
assert geolocation == {"latitude": 10, "longitude": 10}
|
||||
|
||||
geolocation2 = await page2.evaluate(
|
||||
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
|
||||
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
|
||||
}))"""
|
||||
)
|
||||
assert geolocation2 == {"latitude": 10.5, "longitude": 10.5}
|
||||
|
||||
await context2.close()
|
||||
|
||||
|
||||
async def test_should_use_context_options(browser: Browser, server: Server) -> None:
|
||||
context = await browser.new_context(
|
||||
geolocation={"latitude": 10, "longitude": 10}, permissions=["geolocation"]
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
geolocation = await page.evaluate(
|
||||
"""() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
|
||||
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
|
||||
}))"""
|
||||
)
|
||||
assert geolocation == {"latitude": 10, "longitude": 10}
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_watch_position_should_be_notified(
|
||||
page: Page, server: Server, context: BrowserContext
|
||||
) -> None:
|
||||
await context.grant_permissions(["geolocation"])
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
messages = []
|
||||
page.on("console", lambda message: messages.append(message.text))
|
||||
|
||||
await context.set_geolocation({"latitude": 0, "longitude": 0})
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
navigator.geolocation.watchPosition(pos => {
|
||||
const coords = pos.coords;
|
||||
console.log(`lat=${coords.latitude} lng=${coords.longitude}`);
|
||||
}, err => {});
|
||||
}"""
|
||||
)
|
||||
|
||||
async with page.expect_console_message(lambda m: "lat=0 lng=10" in m.text):
|
||||
await context.set_geolocation({"latitude": 0, "longitude": 10})
|
||||
|
||||
async with page.expect_console_message(lambda m: "lat=20 lng=30" in m.text):
|
||||
await context.set_geolocation({"latitude": 20, "longitude": 30})
|
||||
|
||||
async with page.expect_console_message(lambda m: "lat=40 lng=50" in m.text):
|
||||
await context.set_geolocation({"latitude": 40, "longitude": 50})
|
||||
|
||||
all_messages = "|".join(messages)
|
||||
assert "lat=0 lng=10" in all_messages
|
||||
assert "lat=20 lng=30" in all_messages
|
||||
assert "lat=40 lng=50" in all_messages
|
||||
|
||||
|
||||
async def test_should_use_context_options_for_popup(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.grant_permissions(["geolocation"])
|
||||
await context.set_geolocation({"latitude": 10, "longitude": 10})
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"url => window._popup = window.open(url)",
|
||||
server.PREFIX + "/geolocation.html",
|
||||
)
|
||||
popup = await popup_info.value
|
||||
await popup.wait_for_load_state()
|
||||
geolocation = await popup.evaluate("() => window.geolocationPromise")
|
||||
assert geolocation == {"latitude": 10, "longitude": 10}
|
||||
@@ -0,0 +1,806 @@
|
||||
# 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
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Awaitable, Callable, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Error, Page, Route, expect
|
||||
from tests.server import Server, TestServerRequest
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_should_work(browser: Browser, server: Server, tmp_path: Path) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(record_har_path=path)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert "log" in data
|
||||
|
||||
|
||||
async def test_should_omit_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path,
|
||||
record_har_content="omit",
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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
|
||||
|
||||
|
||||
async def test_should_omit_content_legacy(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path, record_har_omit_content=True
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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
|
||||
|
||||
|
||||
async def test_should_attach_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har.zip")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path,
|
||||
record_har_content="attach",
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await page.evaluate("() => fetch('/pptr.png').then(r => r.arrayBuffer())")
|
||||
await 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"]
|
||||
|
||||
|
||||
async def test_should_not_omit_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path, record_har_omit_content=False
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await context.close()
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
content1 = data["log"]["entries"][0]["response"]["content"]
|
||||
assert "text" in content1
|
||||
|
||||
|
||||
async def test_should_include_content(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(record_har_path=path)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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"]
|
||||
|
||||
|
||||
async def test_should_default_to_full_mode(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path,
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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
|
||||
|
||||
|
||||
async def test_should_support_minimal_mode(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
record_har_path=path,
|
||||
record_har_mode="minimal",
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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
|
||||
|
||||
|
||||
async def test_should_filter_by_glob(
|
||||
browser: Browser, server: Server, tmp_path: str
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await browser.new_context(
|
||||
base_url=server.PREFIX,
|
||||
record_har_path=path,
|
||||
record_har_url_filter="/*.css",
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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")
|
||||
|
||||
|
||||
async def test_should_filter_by_regexp(
|
||||
browser: Browser, server: Server, tmp_path: str
|
||||
) -> None:
|
||||
path = os.path.join(tmp_path, "log.har")
|
||||
context = await 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 = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await 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")
|
||||
|
||||
|
||||
async def test_should_context_route_from_har_matching_the_method_and_following_redirects(
|
||||
context: BrowserContext, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
page = await context.new_page()
|
||||
await page.goto("http://no.playwright/")
|
||||
# HAR contains a redirect for the script that should be followed automatically.
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
# HAR contains a POST for the css file that should not be used.
|
||||
await expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
async def test_should_page_route_from_har_matching_the_method_and_following_redirects(
|
||||
page: Page, assetdir: Path
|
||||
) -> None:
|
||||
await page.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
await page.goto("http://no.playwright/")
|
||||
# HAR contains a redirect for the script that should be followed automatically.
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
# HAR contains a POST for the css file that should not be used.
|
||||
await expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
async def test_fallback_continue_should_continue_when_not_found_in_har(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-fulfill.har", not_found="fallback")
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
await expect(page.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_by_default_should_abort_requests_not_found_in_har(
|
||||
context: BrowserContext,
|
||||
server: Server,
|
||||
assetdir: Path,
|
||||
is_chromium: bool,
|
||||
is_webkit: bool,
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-fulfill.har")
|
||||
page = await context.new_page()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await 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
|
||||
|
||||
|
||||
async 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)
|
||||
await context.route_from_har(har=path_to_invalid_har, not_found="fallback")
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
await expect(page.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_only_handle_requests_matching_url_filter(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-fulfill.har", not_found="fallback", url="**/*.js"
|
||||
)
|
||||
page = await context.new_page()
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
await route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
await context.route("http://no.playwright/", handler)
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
await expect(page.locator("body")).to_have_css(
|
||||
"background-color", "rgba(0, 0, 0, 0)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_only_handle_requests_matching_url_filter_no_fallback(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-fulfill.har", url="**/*.js")
|
||||
page = await context.new_page()
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
await route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
await context.route("http://no.playwright/", handler)
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
await expect(page.locator("body")).to_have_css(
|
||||
"background-color", "rgba(0, 0, 0, 0)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_only_handle_requests_matching_url_filter_no_fallback_page(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await page.route_from_har(har=assetdir / "har-fulfill.har", url="**/*.js")
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
assert route.request.url == "http://no.playwright/"
|
||||
await route.fulfill(
|
||||
status=200,
|
||||
content_type="text/html",
|
||||
body='<script src="./script.js"></script><div>hello</div>',
|
||||
)
|
||||
|
||||
await page.route("http://no.playwright/", handler)
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
await expect(page.locator("body")).to_have_css(
|
||||
"background-color", "rgba(0, 0, 0, 0)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_support_regex_filter(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-fulfill.har",
|
||||
url=re.compile(r".*(\.js|.*\.css|no.playwright\/)"),
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.evaluate("window.value") == "foo"
|
||||
await expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
|
||||
|
||||
|
||||
async def test_should_change_document_url_after_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-redirect.har")
|
||||
page = await context.new_page()
|
||||
|
||||
async with page.expect_navigation() as navigation_info:
|
||||
await asyncio.gather(
|
||||
page.wait_for_url("https://www.theverge.com/"),
|
||||
page.goto("https://theverge.com/"),
|
||||
)
|
||||
|
||||
response = await navigation_info.value
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert await page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
async def test_should_change_document_url_after_redirected_navigation_on_click(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content('<a href="https://theverge.com/">click me</a>')
|
||||
async with page.expect_navigation() as navigation_info:
|
||||
await asyncio.gather(
|
||||
page.wait_for_url("https://www.theverge.com/"),
|
||||
page.click("text=click me"),
|
||||
)
|
||||
|
||||
response = await navigation_info.value
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert await page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
async def test_should_go_back_to_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("https://theverge.com/")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
|
||||
response = await page.go_back()
|
||||
assert response
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert await page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
async def test_should_go_forward_to_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("https://theverge.com/")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
await page.goto("https://theverge.com/")
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
await page.go_back()
|
||||
await expect(page).to_have_url(server.EMPTY_PAGE)
|
||||
response = await page.go_forward()
|
||||
assert response
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert await page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
async def test_should_reload_redirected_navigation(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(
|
||||
har=assetdir / "har-redirect.har", url=re.compile(r"/.*theverge.*/")
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto("https://theverge.com/")
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
response = await page.reload()
|
||||
assert response
|
||||
await expect(page).to_have_url("https://www.theverge.com/")
|
||||
assert response.request.url == "https://www.theverge.com/"
|
||||
assert await page.evaluate("window.location.href") == "https://www.theverge.com/"
|
||||
|
||||
|
||||
async def test_should_fulfill_from_har_with_content_in_a_file(
|
||||
context: BrowserContext, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
await context.route_from_har(har=assetdir / "har-sha1.har")
|
||||
page = await context.new_page()
|
||||
await page.goto("http://no.playwright/")
|
||||
assert await page.content() == "<html><head></head><body>Hello, world</body></html>"
|
||||
|
||||
|
||||
async def test_should_round_trip_har_zip(
|
||||
browser: Browser, server: Server, assetdir: Path, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = await browser.new_context(
|
||||
record_har_mode="minimal", record_har_path=har_path
|
||||
)
|
||||
page_1 = await context_1.new_page()
|
||||
await page_1.goto(server.PREFIX + "/one-style.html")
|
||||
await context_1.close()
|
||||
|
||||
context_2 = await browser.new_context()
|
||||
await context_2.route_from_har(har=har_path, not_found="abort")
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page_2.content()
|
||||
await expect(page_2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_round_trip_har_with_post_data(
|
||||
browser: Browser, server: Server, assetdir: Path, tmp_path: Path
|
||||
) -> None:
|
||||
server.set_route("/echo", lambda req: (req.write(req.post_body), req.finish()))
|
||||
fetch_function = """
|
||||
async (body) => {
|
||||
const response = await fetch('/echo', { method: 'POST', body });
|
||||
return await response.text();
|
||||
};
|
||||
"""
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = await browser.new_context(
|
||||
record_har_mode="minimal", record_har_path=har_path
|
||||
)
|
||||
page_1 = await context_1.new_page()
|
||||
await page_1.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert await page_1.evaluate(fetch_function, "1") == "1"
|
||||
assert await page_1.evaluate(fetch_function, "2") == "2"
|
||||
assert await page_1.evaluate(fetch_function, "3") == "3"
|
||||
await context_1.close()
|
||||
|
||||
context_2 = await browser.new_context()
|
||||
await context_2.route_from_har(har=har_path, not_found="abort")
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.EMPTY_PAGE)
|
||||
assert await page_2.evaluate(fetch_function, "1") == "1"
|
||||
assert await page_2.evaluate(fetch_function, "2") == "2"
|
||||
assert await page_2.evaluate(fetch_function, "3") == "3"
|
||||
with pytest.raises(Exception):
|
||||
await page_2.evaluate(fetch_function, "4")
|
||||
|
||||
|
||||
async 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 await response.text();
|
||||
};
|
||||
"""
|
||||
har_path = tmp_path / "har.zip"
|
||||
context_1 = await browser.new_context(
|
||||
record_har_mode="minimal", record_har_path=har_path
|
||||
)
|
||||
page_1 = await context_1.new_page()
|
||||
await page_1.goto(server.EMPTY_PAGE)
|
||||
|
||||
assert await page_1.evaluate(fetch_function, "baz1") == "baz1"
|
||||
assert await page_1.evaluate(fetch_function, "baz2") == "baz2"
|
||||
assert await page_1.evaluate(fetch_function, "baz3") == "baz3"
|
||||
await context_1.close()
|
||||
|
||||
context_2 = await browser.new_context()
|
||||
await context_2.route_from_har(har=har_path)
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.EMPTY_PAGE)
|
||||
assert await page_2.evaluate(fetch_function, "baz1") == "baz1"
|
||||
assert await page_2.evaluate(fetch_function, "baz2") == "baz2"
|
||||
assert await page_2.evaluate(fetch_function, "baz3") == "baz3"
|
||||
assert await page_2.evaluate(fetch_function, "baz4") == "baz1"
|
||||
|
||||
|
||||
async def test_should_produce_extracted_zip(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.har"
|
||||
context = await browser.new_context(
|
||||
record_har_mode="minimal", record_har_path=har_path, record_har_content="attach"
|
||||
)
|
||||
page_1 = await context.new_page()
|
||||
await page_1.goto(server.PREFIX + "/one-style.html")
|
||||
await 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 = await browser.new_context()
|
||||
await context_2.route_from_har(har_path, not_found="abort")
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page_2.content()
|
||||
await expect(page_2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_update_har_zip_for_context(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context = await browser.new_context()
|
||||
await context.route_from_har(har_path, update=True)
|
||||
page_1 = await context.new_page()
|
||||
await page_1.goto(server.PREFIX + "/one-style.html")
|
||||
await context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
|
||||
context_2 = await browser.new_context()
|
||||
await context_2.route_from_har(har_path, not_found="abort")
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page_2.content()
|
||||
await expect(page_2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_page_unroute_all_should_stop_page_route_from_har(
|
||||
context_factory: Callable[[], Awaitable[BrowserContext]],
|
||||
server: Server,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
har_path = assetdir / "har-fulfill.har"
|
||||
context1 = await context_factory()
|
||||
page1 = await context1.new_page()
|
||||
# The har file contains requests for another domain, so the router
|
||||
# is expected to abort all requests.
|
||||
await page1.route_from_har(har_path, not_found="abort")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page1.goto(server.EMPTY_PAGE)
|
||||
assert exc_info.value
|
||||
await page1.unroute_all(behavior="wait")
|
||||
response = must(await page1.goto(server.EMPTY_PAGE))
|
||||
assert response.ok
|
||||
|
||||
|
||||
async def test_context_unroute_call_should_stop_context_route_from_har(
|
||||
context_factory: Callable[[], Awaitable[BrowserContext]],
|
||||
server: Server,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
har_path = assetdir / "har-fulfill.har"
|
||||
context1 = await context_factory()
|
||||
page1 = await context1.new_page()
|
||||
# The har file contains requests for another domain, so the router
|
||||
# is expected to abort all requests.
|
||||
await context1.route_from_har(har_path, not_found="abort")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page1.goto(server.EMPTY_PAGE)
|
||||
assert exc_info.value
|
||||
await context1.unroute_all(behavior="wait")
|
||||
response = must(await page1.goto(server.EMPTY_PAGE))
|
||||
assert must(response).ok
|
||||
|
||||
|
||||
async def test_should_update_har_zip_for_page(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.zip"
|
||||
context = await browser.new_context()
|
||||
page_1 = await context.new_page()
|
||||
await page_1.route_from_har(har_path, update=True)
|
||||
await page_1.goto(server.PREFIX + "/one-style.html")
|
||||
await context.close()
|
||||
|
||||
assert har_path.exists()
|
||||
|
||||
context_2 = await browser.new_context()
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.route_from_har(har_path, not_found="abort")
|
||||
await page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page_2.content()
|
||||
await expect(page_2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async 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 = await browser.new_context()
|
||||
page1 = await context1.new_page()
|
||||
await page1.route_from_har(
|
||||
har_path, update=True, update_content="embed", update_mode="full"
|
||||
)
|
||||
await page1.goto(server.PREFIX + "/one-style.html")
|
||||
await context1.close()
|
||||
|
||||
context2 = await browser.new_context()
|
||||
page2 = await context2.new_page()
|
||||
await page2.route_from_har(har_path, not_found="abort")
|
||||
await page2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page2.content()
|
||||
await expect(page2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
await context2.close()
|
||||
|
||||
|
||||
async def test_should_update_extracted_har_zip_for_page(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
har_path = tmp_path / "har.har"
|
||||
context = await browser.new_context()
|
||||
page_1 = await context.new_page()
|
||||
await page_1.route_from_har(har_path, update=True)
|
||||
await page_1.goto(server.PREFIX + "/one-style.html")
|
||||
await 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 = await browser.new_context()
|
||||
page_2 = await context_2.new_page()
|
||||
await page_2.route_from_har(har_path, not_found="abort")
|
||||
await page_2.goto(server.PREFIX + "/one-style.html")
|
||||
assert "hello, world!" in await page_2.content()
|
||||
await expect(page_2.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_ignore_aborted_requests(
|
||||
context_factory: Callable[[], Awaitable[BrowserContext]],
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
path = tmp_path / "test.har"
|
||||
server.set_route("/x", lambda request: request.loseConnection())
|
||||
context1 = await context_factory()
|
||||
await context1.route_from_har(har=path, update=True)
|
||||
page1 = await context1.new_page()
|
||||
await page1.goto(server.EMPTY_PAGE)
|
||||
req_promise = asyncio.create_task(server.wait_for_request("/x"))
|
||||
eval_task = asyncio.create_task(
|
||||
page1.evaluate(
|
||||
"url => fetch(url).catch(e => 'cancelled')", server.PREFIX + "/x"
|
||||
)
|
||||
)
|
||||
await req_promise
|
||||
req = await eval_task
|
||||
assert req == "cancelled"
|
||||
await context1.close()
|
||||
|
||||
server.reset()
|
||||
|
||||
def _handle_route(req: TestServerRequest) -> None:
|
||||
req.setHeader("Content-Type", "text/plain")
|
||||
req.write(b"test")
|
||||
req.finish()
|
||||
|
||||
server.set_route("/x", _handle_route)
|
||||
context2 = await context_factory()
|
||||
await context2.route_from_har(path)
|
||||
page2 = await context2.new_page()
|
||||
await page2.goto(server.EMPTY_PAGE)
|
||||
eval_task = asyncio.create_task(
|
||||
page2.evaluate(
|
||||
"url => fetch(url).catch(e => 'cancelled')", server.PREFIX + "/x"
|
||||
)
|
||||
)
|
||||
|
||||
async def _timeout() -> str:
|
||||
await asyncio.sleep(1)
|
||||
return "timeout"
|
||||
|
||||
done, _ = await asyncio.wait(
|
||||
[eval_task, asyncio.create_task(_timeout())],
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
assert next(iter(done)).result() == "timeout"
|
||||
eval_task.cancel()
|
||||
@@ -0,0 +1,179 @@
|
||||
# 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 Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserType
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_have_default_url_when_launching_browser(
|
||||
browser_type: BrowserType, launch_arguments: Dict, tmp_path: Path
|
||||
) -> None:
|
||||
browser_context = await browser_type.launch_persistent_context(
|
||||
tmp_path, **{**launch_arguments, "headless": False}
|
||||
)
|
||||
urls = [page.url for page in browser_context.pages]
|
||||
assert urls == ["about:blank"]
|
||||
await browser_context.close()
|
||||
|
||||
|
||||
async def test_should_close_browser_with_beforeunload_page(
|
||||
browser_type: BrowserType, launch_arguments: Dict, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
browser_context = await browser_type.launch_persistent_context(
|
||||
tmp_path, **{**launch_arguments, "headless": False}
|
||||
)
|
||||
page = await browser_context.new_page()
|
||||
await page.goto(server.PREFIX + "/beforeunload.html")
|
||||
# We have to interact with a page so that 'beforeunload' handlers
|
||||
# fire.
|
||||
await page.click("body")
|
||||
await browser_context.close()
|
||||
|
||||
|
||||
async def test_should_not_crash_when_creating_second_context(
|
||||
browser_type: BrowserType, launch_arguments: Dict, server: Server
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
browser_context = await browser.new_context()
|
||||
await browser_context.new_page()
|
||||
await browser_context.close()
|
||||
browser_context = await browser.new_context()
|
||||
await browser_context.new_page()
|
||||
await browser_context.close()
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_should_click_background_tab(
|
||||
browser_type: BrowserType, launch_arguments: Dict, server: Server
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
page = await browser.new_page()
|
||||
await page.set_content(
|
||||
f'<button>Hello</button><a target=_blank href="{server.EMPTY_PAGE}">empty.html</a>'
|
||||
)
|
||||
await page.click("a")
|
||||
await page.click("button")
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_should_close_browser_after_context_menu_was_triggered(
|
||||
browser_type: BrowserType, launch_arguments: Dict, server: Server
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
page = await browser.new_page()
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await page.click("body", button="right")
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_should_not_block_third_party_cookies(
|
||||
browser_type: BrowserType,
|
||||
launch_arguments: Dict,
|
||||
server: Server,
|
||||
is_chromium: bool,
|
||||
is_firefox: bool,
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
page = await browser.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"""src => {
|
||||
let fulfill;
|
||||
const promise = new Promise(x => fulfill = x);
|
||||
const iframe = document.createElement('iframe');
|
||||
document.body.appendChild(iframe);
|
||||
iframe.onload = fulfill;
|
||||
iframe.src = src;
|
||||
return promise;
|
||||
}""",
|
||||
server.CROSS_PROCESS_PREFIX + "/grid.html",
|
||||
)
|
||||
document_cookie = await page.frames[1].evaluate(
|
||||
"""() => {
|
||||
document.cookie = 'username=John Doe';
|
||||
return document.cookie;
|
||||
}"""
|
||||
)
|
||||
|
||||
await page.wait_for_timeout(2000)
|
||||
allows_third_party = is_firefox
|
||||
assert document_cookie == ("username=John Doe" if allows_third_party else "")
|
||||
cookies = await page.context.cookies(server.CROSS_PROCESS_PREFIX + "/grid.html")
|
||||
if allows_third_party:
|
||||
assert cookies == [
|
||||
{
|
||||
"domain": "127.0.0.1",
|
||||
"expires": -1,
|
||||
"httpOnly": False,
|
||||
"name": "username",
|
||||
"path": "/",
|
||||
"sameSite": "Lax" if is_chromium else "None",
|
||||
"secure": False,
|
||||
"value": "John Doe",
|
||||
}
|
||||
]
|
||||
else:
|
||||
assert cookies == []
|
||||
|
||||
await browser.close()
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("webkit")
|
||||
async def test_should_not_override_viewport_size_when_passed_null(
|
||||
browser_type: BrowserType, launch_arguments: Dict, server: Server
|
||||
) -> None:
|
||||
# Our WebKit embedder does not respect window features.
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
context = await browser.new_context(no_viewport=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=300,top=0,left=0');
|
||||
win.resizeTo(500, 450);
|
||||
}"""
|
||||
)
|
||||
popup = await popup_info.value
|
||||
await popup.wait_for_load_state()
|
||||
await popup.wait_for_function(
|
||||
"""() => window.outerWidth === 500 && window.outerHeight === 450"""
|
||||
)
|
||||
await context.close()
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_page_bring_to_front_should_work(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**{**launch_arguments, "headless": False})
|
||||
page1 = await browser.new_page()
|
||||
await page1.set_content("Page1")
|
||||
page2 = await browser.new_page()
|
||||
await page2.set_content("Page2")
|
||||
|
||||
await page1.bring_to_front()
|
||||
assert await page1.evaluate("document.visibilityState") == "visible"
|
||||
assert await page2.evaluate("document.visibilityState") == "visible"
|
||||
|
||||
await page2.bring_to_front()
|
||||
assert await page1.evaluate("document.visibilityState") == "visible"
|
||||
assert await page2.evaluate("document.visibilityState") == "visible"
|
||||
await browser.close()
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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.async_api import Browser, Error
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_ignore_https_error_should_work(
|
||||
browser: Browser, https_server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(ignore_https_errors=True)
|
||||
page = await context.new_page()
|
||||
response = await page.goto(https_server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_ignore_https_error_should_work_negative_case(
|
||||
browser: Browser, https_server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
with pytest.raises(Error):
|
||||
await page.goto(https_server.EMPTY_PAGE)
|
||||
await context.close()
|
||||
@@ -0,0 +1,509 @@
|
||||
# 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
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright._impl._path_utils import get_file_dirname
|
||||
from playwright.async_api import Error, FilePayload, Page
|
||||
from tests.server import Server
|
||||
from tests.utils import chromium_version_less_than, must
|
||||
|
||||
_dirname = get_file_dirname()
|
||||
FILE_TO_UPLOAD = _dirname / ".." / "assets/file-to-upload.txt"
|
||||
|
||||
|
||||
async def test_should_upload_the_file(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/fileupload.html")
|
||||
file_path = os.path.relpath(FILE_TO_UPLOAD, os.getcwd())
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
await input.set_input_files(file_path)
|
||||
assert await page.evaluate("e => e.files[0].name", input) == "file-to-upload.txt"
|
||||
assert (
|
||||
await page.evaluate(
|
||||
"""e => {
|
||||
reader = new FileReader()
|
||||
promise = new Promise(fulfill => reader.onload = fulfill)
|
||||
reader.readAsText(e.files[0])
|
||||
return promise.then(() => reader.result)
|
||||
}""",
|
||||
input,
|
||||
)
|
||||
== "contents of the file\n"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work(page: Page, assetdir: Path) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
await page.set_input_files("input", assetdir / "file-to-upload.txt")
|
||||
assert await page.eval_on_selector("input", "input => input.files.length") == 1
|
||||
assert (
|
||||
await page.eval_on_selector("input", "input => input.files[0].name")
|
||||
== "file-to-upload.txt"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_set_from_memory(page: Page) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
file: FilePayload = {
|
||||
"name": "test.txt",
|
||||
"mimeType": "text/plain",
|
||||
"buffer": b"this is a test",
|
||||
}
|
||||
await page.set_input_files(
|
||||
"input",
|
||||
files=[file],
|
||||
)
|
||||
assert await page.eval_on_selector("input", "input => input.files.length") == 1
|
||||
assert (
|
||||
await page.eval_on_selector("input", "input => input.files[0].name")
|
||||
== "test.txt"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_emit_event(page: Page) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
fc_done: asyncio.Future = asyncio.Future()
|
||||
page.once("filechooser", lambda file_chooser: fc_done.set_result(file_chooser))
|
||||
await page.click("input")
|
||||
file_chooser = await fc_done
|
||||
assert file_chooser
|
||||
assert (
|
||||
repr(file_chooser)
|
||||
== f"<FileChooser page={file_chooser.page} element={file_chooser.element}>"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_when_file_input_is_attached_to_dom(page: Page) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser
|
||||
|
||||
|
||||
async def test_should_work_when_file_input_is_not_attached_to_DOM(page: Page) -> None:
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.click()
|
||||
}"""
|
||||
)
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser
|
||||
|
||||
|
||||
async def test_should_return_the_same_file_chooser_when_there_are_many_watchdogs_simultaneously(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
results = await asyncio.gather(
|
||||
page.wait_for_event("filechooser"),
|
||||
page.wait_for_event("filechooser"),
|
||||
page.eval_on_selector("input", "input => input.click()"),
|
||||
)
|
||||
assert results[0] == results[1]
|
||||
|
||||
|
||||
async def test_should_accept_single_file(page: Page) -> None:
|
||||
await page.set_content('<input type=file oninput="javascript:console.timeStamp()">')
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser.page == page
|
||||
assert file_chooser.element
|
||||
await file_chooser.set_files(FILE_TO_UPLOAD)
|
||||
assert await page.eval_on_selector("input", "input => input.files.length") == 1
|
||||
assert (
|
||||
await page.eval_on_selector("input", "input => input.files[0].name")
|
||||
== "file-to-upload.txt"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_be_able_to_read_selected_file(page: Page) -> None:
|
||||
page.once(
|
||||
"filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)
|
||||
)
|
||||
await page.set_content("<input type=file>")
|
||||
content = await page.eval_on_selector(
|
||||
"input",
|
||||
"""async picker => {
|
||||
picker.click();
|
||||
await new Promise(x => picker.oninput = x);
|
||||
const reader = new FileReader();
|
||||
const promise = new Promise(fulfill => reader.onload = fulfill);
|
||||
reader.readAsText(picker.files[0]);
|
||||
return promise.then(() => reader.result);
|
||||
}""",
|
||||
)
|
||||
assert content == "contents of the file\n"
|
||||
|
||||
|
||||
async def test_should_be_able_to_reset_selected_files_with_empty_file_list(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
page.once(
|
||||
"filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)
|
||||
)
|
||||
file_length = 0
|
||||
async with page.expect_file_chooser():
|
||||
file_length = await page.eval_on_selector(
|
||||
"input",
|
||||
"""async picker => {
|
||||
picker.click();
|
||||
await new Promise(x => picker.oninput = x);
|
||||
return picker.files.length;
|
||||
}""",
|
||||
)
|
||||
assert file_length == 1
|
||||
|
||||
page.once("filechooser", lambda file_chooser: file_chooser.set_files([]))
|
||||
async with page.expect_file_chooser():
|
||||
file_length = await page.eval_on_selector(
|
||||
"input",
|
||||
"""async picker => {
|
||||
picker.click();
|
||||
await new Promise(x => picker.oninput = x);
|
||||
return picker.files.length;
|
||||
}""",
|
||||
)
|
||||
assert file_length == 0
|
||||
|
||||
|
||||
async def test_should_not_accept_multiple_files_for_single_file_input(
|
||||
page: Page, assetdir: Path
|
||||
) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await file_chooser.set_files(
|
||||
[
|
||||
os.path.realpath(assetdir / "file-to-upload.txt"),
|
||||
os.path.realpath(assetdir / "pptr.png"),
|
||||
]
|
||||
)
|
||||
assert exc_info.value
|
||||
|
||||
|
||||
async def test_should_emit_input_and_change_events(page: Page) -> None:
|
||||
events = []
|
||||
await page.expose_function("eventHandled", lambda e: events.append(e))
|
||||
await page.set_content(
|
||||
"""
|
||||
<input id=input type=file></input>
|
||||
<script>
|
||||
input.addEventListener('input', e => eventHandled({ type: e.type }))
|
||||
input.addEventListener('change', e => eventHandled({ type: e.type }))
|
||||
</script>
|
||||
"""
|
||||
)
|
||||
await must(await page.query_selector("input")).set_input_files(FILE_TO_UPLOAD)
|
||||
assert len(events) == 2
|
||||
assert events[0]["type"] == "input"
|
||||
assert events[1]["type"] == "change"
|
||||
|
||||
|
||||
async def test_should_work_for_single_file_pick(page: Page) -> None:
|
||||
await page.set_content("<input type=file>")
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser.is_multiple() is False
|
||||
|
||||
|
||||
async def test_should_work_for_multiple(page: Page) -> None:
|
||||
await page.set_content("<input multiple type=file>")
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser.is_multiple()
|
||||
|
||||
|
||||
async def test_should_work_for_webkitdirectory(page: Page) -> None:
|
||||
await page.set_content("<input multiple webkitdirectory type=file>")
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await page.click("input")
|
||||
file_chooser = await fc_info.value
|
||||
assert file_chooser.is_multiple()
|
||||
|
||||
|
||||
def _assert_wheel_event(expected: Any, received: Any, browser_name: str) -> None:
|
||||
# Chromium reports deltaX/deltaY scaled by host device scale factor.
|
||||
# https://bugs.chromium.org/p/chromium/issues/detail?id=1324819
|
||||
# https://github.com/microsoft/playwright/issues/7362
|
||||
# Different bots have different scale factors (usually 1 or 2), so we just ignore the values
|
||||
# instead of guessing the host scale factor.
|
||||
if sys.platform == "darwin" and browser_name == "chromium":
|
||||
del expected["deltaX"]
|
||||
del expected["deltaY"]
|
||||
del received["deltaX"]
|
||||
del received["deltaY"]
|
||||
assert received == expected
|
||||
|
||||
|
||||
async def test_wheel_should_work(page: Page, browser_name: str) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div style="width: 5000px; height: 5000px;"></div>
|
||||
"""
|
||||
)
|
||||
await page.mouse.move(50, 60)
|
||||
await _listen_for_wheel_events(page, "div")
|
||||
await page.mouse.wheel(0, 100)
|
||||
_assert_wheel_event(
|
||||
await page.evaluate("window.lastEvent"),
|
||||
{
|
||||
"deltaX": 0,
|
||||
"deltaY": 100,
|
||||
"clientX": 50,
|
||||
"clientY": 60,
|
||||
"deltaMode": 0,
|
||||
"ctrlKey": False,
|
||||
"shiftKey": False,
|
||||
"altKey": False,
|
||||
"metaKey": False,
|
||||
},
|
||||
browser_name,
|
||||
)
|
||||
await page.wait_for_function("window.scrollY === 100")
|
||||
|
||||
|
||||
async def _listen_for_wheel_events(page: Page, selector: str) -> None:
|
||||
await page.evaluate(
|
||||
"""
|
||||
selector => {
|
||||
document.querySelector(selector).addEventListener('wheel', (e) => {
|
||||
window['lastEvent'] = {
|
||||
deltaX: e.deltaX,
|
||||
deltaY: e.deltaY,
|
||||
clientX: e.clientX,
|
||||
clientY: e.clientY,
|
||||
deltaMode: e.deltaMode,
|
||||
ctrlKey: e.ctrlKey,
|
||||
shiftKey: e.shiftKey,
|
||||
altKey: e.altKey,
|
||||
metaKey: e.metaKey,
|
||||
};
|
||||
}, { passive: false });
|
||||
}
|
||||
""",
|
||||
selector,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_upload_large_file(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/fileupload.html")
|
||||
large_file_path = tmp_path / "200MB.zip"
|
||||
data = b"A" * 1024
|
||||
with large_file_path.open("wb") as f:
|
||||
for i in range(0, 200 * 1024 * 1024, len(data)):
|
||||
f.write(data)
|
||||
input = page.locator('input[type="file"]')
|
||||
events = await input.evaluate_handle(
|
||||
"""
|
||||
e => {
|
||||
const events = [];
|
||||
e.addEventListener('input', () => events.push('input'));
|
||||
e.addEventListener('change', () => events.push('change'));
|
||||
return events;
|
||||
}
|
||||
"""
|
||||
)
|
||||
|
||||
await input.set_input_files(large_file_path)
|
||||
assert await input.evaluate("e => e.files[0].name") == "200MB.zip"
|
||||
assert await events.evaluate("e => e") == ["input", "change"]
|
||||
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/upload"),
|
||||
page.click("input[type=submit]"),
|
||||
)
|
||||
|
||||
contents = request.args[b"file1"][0]
|
||||
assert len(contents) == 200 * 1024 * 1024
|
||||
assert contents[:1024] == data
|
||||
# flake8: noqa: E203
|
||||
assert contents[len(contents) - 1024 :] == data
|
||||
assert request.post_body
|
||||
match = re.search(
|
||||
rb'^.*Content-Disposition: form-data; name="(?P<name>.*)"; filename="(?P<filename>.*)".*$',
|
||||
request.post_body,
|
||||
re.MULTILINE,
|
||||
)
|
||||
assert match
|
||||
assert match.group("name") == b"file1"
|
||||
assert match.group("filename") == b"200MB.zip"
|
||||
|
||||
|
||||
async def test_set_input_files_should_preserve_last_modified_timestamp(
|
||||
page: Page,
|
||||
assetdir: Path,
|
||||
) -> None:
|
||||
await page.set_content("<input type=file multiple=true/>")
|
||||
input = page.locator("input")
|
||||
files = ["file-to-upload.txt", "file-to-upload-2.txt"]
|
||||
await input.set_input_files([assetdir / file for file in files])
|
||||
assert await input.evaluate("input => [...input.files].map(f => f.name)") == files
|
||||
timestamps = await 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
|
||||
|
||||
|
||||
async def test_should_upload_multiple_large_file(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
files_count = 10
|
||||
await page.goto(server.PREFIX + "/input/fileupload-multi.html")
|
||||
upload_file = tmp_path / "50MB_1.zip"
|
||||
data = b"A" * 1024
|
||||
with upload_file.open("wb") as f:
|
||||
# 49 is close to the actual limit
|
||||
for i in range(0, 49 * 1024):
|
||||
f.write(data)
|
||||
input = page.locator('input[type="file"]')
|
||||
upload_files = [upload_file]
|
||||
for i in range(2, files_count + 1):
|
||||
dst_file = tmp_path / f"50MB_{i}.zip"
|
||||
shutil.copy(upload_file, dst_file)
|
||||
upload_files.append(dst_file)
|
||||
async with page.expect_file_chooser() as fc_info:
|
||||
await input.click()
|
||||
file_chooser = await fc_info.value
|
||||
await file_chooser.set_files(upload_files)
|
||||
files_len = await page.evaluate(
|
||||
'document.getElementsByTagName("input")[0].files.length'
|
||||
)
|
||||
assert file_chooser.is_multiple()
|
||||
assert files_len == files_count
|
||||
for path in upload_files:
|
||||
path.unlink()
|
||||
|
||||
|
||||
async def test_should_upload_a_folder(
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
browser_name: str,
|
||||
browser_version: str,
|
||||
headless: bool,
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/folderupload.html")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
dir = tmp_path / "file-upload-test"
|
||||
dir.mkdir()
|
||||
(dir / "file1.txt").write_text("file1 content")
|
||||
(dir / "file2").write_text("file2 content")
|
||||
(dir / "sub-dir").mkdir()
|
||||
(dir / "sub-dir" / "really.txt").write_text("sub-dir file content")
|
||||
await input.set_input_files(dir)
|
||||
assert set(
|
||||
await input.evaluate("e => [...e.files].map(f => f.webkitRelativePath)")
|
||||
) == set(
|
||||
[
|
||||
"file-upload-test/file1.txt",
|
||||
"file-upload-test/file2",
|
||||
# https://issues.chromium.org/issues/345393164
|
||||
*(
|
||||
[]
|
||||
if browser_name == "chromium"
|
||||
and headless
|
||||
and chromium_version_less_than(browser_version, "127.0.6533.0")
|
||||
else ["file-upload-test/sub-dir/really.txt"]
|
||||
),
|
||||
]
|
||||
)
|
||||
webkit_relative_paths = await input.evaluate(
|
||||
"e => [...e.files].map(f => f.webkitRelativePath)"
|
||||
)
|
||||
for i, webkit_relative_path in enumerate(webkit_relative_paths):
|
||||
content = await input.evaluate(
|
||||
"""(e, i) => {
|
||||
const reader = new FileReader();
|
||||
const promise = new Promise(fulfill => reader.onload = fulfill);
|
||||
reader.readAsText(e.files[i]);
|
||||
return promise.then(() => reader.result);
|
||||
}""",
|
||||
i,
|
||||
)
|
||||
assert content == (dir / ".." / webkit_relative_path).read_text()
|
||||
|
||||
|
||||
async def test_should_upload_a_folder_and_throw_for_multiple_directories(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/folderupload.html")
|
||||
input = page.locator("input")
|
||||
dir = tmp_path / "file-upload-test"
|
||||
dir.mkdir()
|
||||
(dir / "folder1").mkdir()
|
||||
(dir / "folder1" / "file1.txt").write_text("file1 content")
|
||||
(dir / "folder2").mkdir()
|
||||
(dir / "folder2" / "file2.txt").write_text("file2 content")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await input.set_input_files([dir / "folder1", dir / "folder2"])
|
||||
assert "Multiple directories are not supported" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_throw_if_a_directory_and_files_are_passed(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/folderupload.html")
|
||||
input = page.locator("input")
|
||||
dir = tmp_path / "file-upload-test"
|
||||
dir.mkdir()
|
||||
(dir / "file1.txt").write_text("file1 content")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await input.set_input_files([dir, dir / "file1.txt"])
|
||||
assert (
|
||||
"File paths must be all files or a single directory" in exc_info.value.message
|
||||
)
|
||||
|
||||
|
||||
async def test_should_throw_when_upload_a_folder_in_a_normal_file_upload_input(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/fileupload.html")
|
||||
input = await page.query_selector("input")
|
||||
assert input
|
||||
dir = tmp_path / "file-upload-test"
|
||||
dir.mkdir()
|
||||
(dir / "file1.txt").write_text("file1 content")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await input.set_input_files(dir)
|
||||
assert (
|
||||
"File input does not support directories, pass individual files instead"
|
||||
in exc_info.value.message
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
# 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 asyncio import FIRST_COMPLETED, CancelledError, create_task, wait
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserType, Page, Playwright
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_issue_189(browser_type: BrowserType, launch_arguments: Dict) -> None:
|
||||
browser = await browser_type.launch(
|
||||
**launch_arguments, ignore_default_args=["--mute-audio"]
|
||||
)
|
||||
page = await browser.new_page()
|
||||
assert await page.evaluate("1 + 1") == 2
|
||||
await browser.close()
|
||||
|
||||
|
||||
@pytest.mark.only_browser("chromium")
|
||||
async def test_issue_195(playwright: Playwright, browser: Browser) -> None:
|
||||
iphone_11 = playwright.devices["iPhone 11"]
|
||||
context = await browser.new_context(**iphone_11)
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_connection_task_cancel(page: Page) -> None:
|
||||
await page.set_content("<input />")
|
||||
done, pending = await wait(
|
||||
{
|
||||
create_task(page.wait_for_selector("input")),
|
||||
create_task(page.wait_for_selector("#will-never-resolve")),
|
||||
},
|
||||
return_when=FIRST_COMPLETED,
|
||||
)
|
||||
assert len(done) == 1
|
||||
assert len(pending) == 1
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
with pytest.raises(CancelledError):
|
||||
await task
|
||||
assert list(pending)[0].cancelled()
|
||||
@@ -0,0 +1,230 @@
|
||||
# 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 math
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
from playwright.async_api import Page
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_work(page: Page) -> None:
|
||||
window_handle = await page.evaluate_handle("window")
|
||||
assert window_handle
|
||||
assert (
|
||||
repr(window_handle) == f"<JSHandle preview={window_handle._impl_obj._preview}>"
|
||||
)
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_object_handle_as_argument(page: Page) -> None:
|
||||
navigator_handle = await page.evaluate_handle("navigator")
|
||||
text = await page.evaluate("e => e.userAgent", navigator_handle)
|
||||
assert "Mozilla" in text
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_handle_to_primitive_types(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("5")
|
||||
is_five = await page.evaluate("e => Object.is(e, 5)", handle)
|
||||
assert is_five
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_nested_handle(page: Page) -> None:
|
||||
foo = await page.evaluate_handle('({ x: 1, y: "foo" })')
|
||||
result = await page.evaluate("({ foo }) => foo", {"foo": foo})
|
||||
assert result == {"x": 1, "y": "foo"}
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_nested_window_handle(page: Page) -> None:
|
||||
foo = await page.evaluate_handle("window")
|
||||
result = await page.evaluate("({ foo }) => foo === window", {"foo": foo})
|
||||
assert result
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_multiple_nested_handles(page: Page) -> None:
|
||||
foo = await page.evaluate_handle('({ x: 1, y: "foo" })')
|
||||
bar = await page.evaluate_handle("5")
|
||||
baz = await page.evaluate_handle('["baz"]')
|
||||
result = await page.evaluate(
|
||||
"x => JSON.stringify(x)",
|
||||
{"a1": {"foo": foo}, "a2": {"bar": bar, "arr": [{"baz": baz}]}},
|
||||
)
|
||||
assert json.loads(result) == {
|
||||
"a1": {"foo": {"x": 1, "y": "foo"}},
|
||||
"a2": {"bar": 5, "arr": [{"baz": ["baz"]}]},
|
||||
}
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_should_work_for_circular_objects(page: Page) -> None:
|
||||
a: Dict[str, Any] = {"x": 1}
|
||||
a["y"] = a
|
||||
result = await page.evaluate("a => { a.y.x += 1; return a; }", a)
|
||||
assert result["x"] == 2
|
||||
assert result["y"]["x"] == 2
|
||||
assert result == result["y"]
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_same_nested_object_multiple_times(
|
||||
page: Page,
|
||||
) -> None:
|
||||
foo = {"x": 1}
|
||||
assert await page.evaluate(
|
||||
"x => x", {"foo": foo, "bar": [foo], "baz": {"foo": foo}}
|
||||
) == {"foo": {"x": 1}, "bar": [{"x": 1}], "baz": {"foo": {"x": 1}}}
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_accept_object_handle_to_unserializable_value(
|
||||
page: Page,
|
||||
) -> None:
|
||||
handle = await page.evaluate_handle("() => Infinity")
|
||||
assert await page.evaluate("e => Object.is(e, Infinity)", handle)
|
||||
|
||||
|
||||
async def test_jshandle_evaluate_pass_configurable_args(page: Page) -> None:
|
||||
result = await page.evaluate(
|
||||
"""arg => {
|
||||
if (arg.foo !== 42)
|
||||
throw new Error('Not a 42');
|
||||
arg.foo = 17;
|
||||
if (arg.foo !== 17)
|
||||
throw new Error('Not 17');
|
||||
delete arg.foo;
|
||||
if (arg.foo === 17)
|
||||
throw new Error('Still 17');
|
||||
return arg;
|
||||
}""",
|
||||
{"foo": 42},
|
||||
)
|
||||
assert result == {}
|
||||
|
||||
|
||||
async def test_jshandle_properties_get_property(page: Page) -> None:
|
||||
handle1 = await page.evaluate_handle(
|
||||
"""() => ({
|
||||
one: 1,
|
||||
two: 2,
|
||||
three: 3
|
||||
})"""
|
||||
)
|
||||
handle2 = await handle1.get_property("two")
|
||||
assert await handle2.json_value() == 2
|
||||
|
||||
|
||||
async def test_jshandle_properties_work_with_undefined_null_and_empty(
|
||||
page: Page,
|
||||
) -> None:
|
||||
handle = await page.evaluate_handle(
|
||||
"""() => ({
|
||||
undefined: undefined,
|
||||
null: null,
|
||||
})"""
|
||||
)
|
||||
undefined_handle = await handle.get_property("undefined")
|
||||
assert await undefined_handle.json_value() is None
|
||||
null_handle = await handle.get_property("null")
|
||||
assert await null_handle.json_value() is None
|
||||
empty_handle = await handle.get_property("empty")
|
||||
assert await empty_handle.json_value() is None
|
||||
|
||||
|
||||
async def test_jshandle_properties_work_with_unserializable_values(page: Page) -> None:
|
||||
handle = await page.evaluate_handle(
|
||||
"""() => ({
|
||||
infinity: Infinity,
|
||||
negInfinity: -Infinity,
|
||||
nan: NaN,
|
||||
negZero: -0
|
||||
})"""
|
||||
)
|
||||
infinity_handle = await handle.get_property("infinity")
|
||||
assert await infinity_handle.json_value() == float("inf")
|
||||
neg_infinity_handle = await handle.get_property("negInfinity")
|
||||
assert await neg_infinity_handle.json_value() == float("-inf")
|
||||
nan_handle = await handle.get_property("nan")
|
||||
assert math.isnan(await nan_handle.json_value()) is True
|
||||
neg_zero_handle = await handle.get_property("negZero")
|
||||
assert await neg_zero_handle.json_value() == float("-0")
|
||||
|
||||
|
||||
async def test_jshandle_properties_get_properties(page: Page) -> None:
|
||||
handle = await page.evaluate_handle('() => ({ foo: "bar" })')
|
||||
properties = await handle.get_properties()
|
||||
assert "foo" in properties
|
||||
foo = properties["foo"]
|
||||
assert await foo.json_value() == "bar"
|
||||
|
||||
|
||||
async def test_jshandle_properties_return_empty_map_for_non_objects(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("123")
|
||||
properties = await handle.get_properties()
|
||||
assert properties == {}
|
||||
|
||||
|
||||
async def test_jshandle_json_value_work(page: Page) -> None:
|
||||
handle = await page.evaluate_handle('() => ({foo: "bar"})')
|
||||
json = await handle.json_value()
|
||||
assert json == {"foo": "bar"}
|
||||
|
||||
|
||||
async def test_jshandle_json_value_work_with_dates(page: Page) -> None:
|
||||
handle = await page.evaluate_handle('() => new Date("2020-05-27T01:31:38.506Z")')
|
||||
json = await handle.json_value()
|
||||
assert json == datetime.fromisoformat("2020-05-27T01:31:38.506").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
|
||||
|
||||
async def test_jshandle_json_value_should_work_for_circular_object(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("const a = {}; a.b = a; a")
|
||||
a: Dict[str, Any] = {}
|
||||
a["b"] = a
|
||||
result = await handle.json_value()
|
||||
# Node test looks like the below, but assert isn't smart enough to handle this:
|
||||
# assert await handle.json_value() == a
|
||||
assert result["b"] == result
|
||||
|
||||
|
||||
async def test_jshandle_as_element_work(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("document.body")
|
||||
element = handle.as_element()
|
||||
assert element is not None
|
||||
|
||||
|
||||
async def test_jshandle_as_element_return_none_for_non_elements(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("2")
|
||||
element = handle.as_element()
|
||||
assert element is None
|
||||
|
||||
|
||||
async def test_jshandle_to_string_work_for_primitives(page: Page) -> None:
|
||||
number_handle = await page.evaluate_handle("2")
|
||||
assert str(number_handle) == "2"
|
||||
string_handle = await page.evaluate_handle('"a"')
|
||||
assert str(string_handle) == "a"
|
||||
|
||||
|
||||
async def test_jshandle_to_string_work_for_complicated_objects(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
handle = await page.evaluate_handle("window")
|
||||
if browser_name != "firefox":
|
||||
assert str(handle) == "Window"
|
||||
else:
|
||||
assert str(handle) == "JSHandle@object"
|
||||
|
||||
|
||||
async def test_jshandle_to_string_work_for_promises(page: Page) -> None:
|
||||
handle = await page.evaluate_handle("({b: Promise.resolve(123)})")
|
||||
b_handle = await handle.get_property("b")
|
||||
assert str(b_handle) == "Promise"
|
||||
@@ -0,0 +1,569 @@
|
||||
# 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.async_api import Error, JSHandle, Page
|
||||
from tests.server import Server
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async def captureLastKeydown(page: Page) -> JSHandle:
|
||||
lastEvent = await page.evaluate_handle(
|
||||
"""() => {
|
||||
const lastEvent = {
|
||||
repeat: false,
|
||||
location: -1,
|
||||
code: '',
|
||||
key: '',
|
||||
metaKey: false,
|
||||
keyIdentifier: 'unsupported'
|
||||
};
|
||||
document.addEventListener('keydown', e => {
|
||||
lastEvent.repeat = e.repeat;
|
||||
lastEvent.location = e.location;
|
||||
lastEvent.key = e.key;
|
||||
lastEvent.code = e.code;
|
||||
lastEvent.metaKey = e.metaKey;
|
||||
// keyIdentifier only exists in WebKit, and isn't in TypeScript's lib.
|
||||
lastEvent.keyIdentifier = 'keyIdentifier' in e && e.keyIdentifier;
|
||||
}, true);
|
||||
return lastEvent;
|
||||
}"""
|
||||
)
|
||||
return lastEvent
|
||||
|
||||
|
||||
async def test_keyboard_type_into_a_textarea(page: Page) -> None:
|
||||
await page.evaluate(
|
||||
"""
|
||||
const textarea = document.createElement('textarea');
|
||||
document.body.appendChild(textarea);
|
||||
textarea.focus();
|
||||
"""
|
||||
)
|
||||
text = "Hello world. I am the text that was typed!"
|
||||
await page.keyboard.type(text)
|
||||
assert await page.evaluate('document.querySelector("textarea").value') == text
|
||||
|
||||
|
||||
async def test_keyboard_move_with_the_arrow_keys(page: Page, server: Server) -> None:
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
await page.type("textarea", "Hello World!")
|
||||
assert (
|
||||
await page.evaluate("document.querySelector('textarea').value")
|
||||
== "Hello World!"
|
||||
)
|
||||
for _ in "World!":
|
||||
await page.keyboard.press("ArrowLeft")
|
||||
await page.keyboard.type("inserted ")
|
||||
assert (
|
||||
await page.evaluate("document.querySelector('textarea').value")
|
||||
== "Hello inserted World!"
|
||||
)
|
||||
await page.keyboard.down("Shift")
|
||||
for _ in "inserted ":
|
||||
await page.keyboard.press("ArrowLeft")
|
||||
await page.keyboard.up("Shift")
|
||||
await page.keyboard.press("Backspace")
|
||||
assert (
|
||||
await page.evaluate("document.querySelector('textarea').value")
|
||||
== "Hello World!"
|
||||
)
|
||||
|
||||
|
||||
async def test_keyboard_send_a_character_with_elementhandle_press(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.press("a")
|
||||
assert await page.evaluate("document.querySelector('textarea').value") == "a"
|
||||
await page.evaluate(
|
||||
"() => window.addEventListener('keydown', e => e.preventDefault(), true)"
|
||||
)
|
||||
await textarea.press("b")
|
||||
assert await page.evaluate("document.querySelector('textarea').value") == "a"
|
||||
|
||||
|
||||
async def test_should_send_a_character_with_send_character(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.focus("textarea")
|
||||
await page.keyboard.insert_text("嗨")
|
||||
assert await page.evaluate('() => document.querySelector("textarea").value') == "嗨"
|
||||
await page.evaluate(
|
||||
'() => window.addEventListener("keydown", e => e.preventDefault(), true)'
|
||||
)
|
||||
await page.keyboard.insert_text("a")
|
||||
assert (
|
||||
await page.evaluate('() => document.querySelector("textarea").value') == "嗨a"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_only_emit_input_event(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.focus("textarea")
|
||||
events = await page.evaluate_handle(
|
||||
"""() => {
|
||||
const events = [];
|
||||
document.addEventListener('keydown', e => events.push(e.type));
|
||||
document.addEventListener('keyup', e => events.push(e.type));
|
||||
document.addEventListener('keypress', e => events.push(e.type));
|
||||
document.addEventListener('input', e => events.push(e.type));
|
||||
return events;
|
||||
}"""
|
||||
)
|
||||
|
||||
await page.keyboard.insert_text("hello world")
|
||||
assert await events.json_value() == ["input"]
|
||||
|
||||
|
||||
async def test_should_report_shiftkey(
|
||||
page: Page, server: Server, is_mac: bool, is_firefox: bool
|
||||
) -> None:
|
||||
if is_firefox and is_mac:
|
||||
pytest.skip()
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
keyboard = page.keyboard
|
||||
codeForKey = {"Shift": 16, "Alt": 18, "Control": 17}
|
||||
for modifierKey in codeForKey.keys():
|
||||
await keyboard.down(modifierKey)
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: "
|
||||
+ modifierKey
|
||||
+ " "
|
||||
+ modifierKey
|
||||
+ "Left "
|
||||
+ str(codeForKey[modifierKey])
|
||||
+ " ["
|
||||
+ modifierKey
|
||||
+ "]"
|
||||
)
|
||||
await keyboard.down("!")
|
||||
# Shift+! will generate a keypress
|
||||
if modifierKey == "Shift":
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: ! Digit1 49 ["
|
||||
+ modifierKey
|
||||
+ "]\nKeypress: ! Digit1 33 33 ["
|
||||
+ modifierKey
|
||||
+ "]"
|
||||
)
|
||||
else:
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: ! Digit1 49 [" + modifierKey + "]"
|
||||
)
|
||||
|
||||
await keyboard.up("!")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keyup: ! Digit1 49 [" + modifierKey + "]"
|
||||
)
|
||||
await keyboard.up(modifierKey)
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keyup: "
|
||||
+ modifierKey
|
||||
+ " "
|
||||
+ modifierKey
|
||||
+ "Left "
|
||||
+ str(codeForKey[modifierKey])
|
||||
+ " []"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_report_multiple_modifiers(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
keyboard = page.keyboard
|
||||
await keyboard.down("Control")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: Control ControlLeft 17 [Control]"
|
||||
)
|
||||
await keyboard.down("Alt")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: Alt AltLeft 18 [Alt Control]"
|
||||
)
|
||||
await keyboard.down(";")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keydown: ; Semicolon 186 [Alt Control]"
|
||||
)
|
||||
await keyboard.up(";")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keyup: ; Semicolon 186 [Alt Control]"
|
||||
)
|
||||
await keyboard.up("Control")
|
||||
assert (
|
||||
await page.evaluate("() => getResult()")
|
||||
== "Keyup: Control ControlLeft 17 [Alt]"
|
||||
)
|
||||
await keyboard.up("Alt")
|
||||
assert await page.evaluate("() => getResult()") == "Keyup: Alt AltLeft 18 []"
|
||||
|
||||
|
||||
async def test_should_send_proper_codes_while_typing(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.type("!")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: ! Digit1 49 []",
|
||||
"Keypress: ! Digit1 33 33 []",
|
||||
"Keyup: ! Digit1 49 []",
|
||||
]
|
||||
)
|
||||
await page.keyboard.type("^")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: ^ Digit6 54 []",
|
||||
"Keypress: ^ Digit6 94 94 []",
|
||||
"Keyup: ^ Digit6 54 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_send_proper_codes_while_typing_with_shift(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
keyboard = page.keyboard
|
||||
await keyboard.down("Shift")
|
||||
await page.keyboard.type("~")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: Shift ShiftLeft 16 [Shift]",
|
||||
"Keydown: ~ Backquote 192 [Shift]", # 192 is ` keyCode
|
||||
"Keypress: ~ Backquote 126 126 [Shift]", # 126 is ~ charCode
|
||||
"Keyup: ~ Backquote 192 [Shift]",
|
||||
]
|
||||
)
|
||||
await keyboard.up("Shift")
|
||||
|
||||
|
||||
async def test_should_not_type_canceled_events(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.focus("textarea")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.addEventListener('keydown', event => {
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
if (event.key === 'l')
|
||||
event.preventDefault();
|
||||
if (event.key === 'o')
|
||||
event.preventDefault();
|
||||
}, false);
|
||||
}"""
|
||||
)
|
||||
|
||||
await page.keyboard.type("Hello World!")
|
||||
assert (
|
||||
await page.eval_on_selector("textarea", "textarea => textarea.value")
|
||||
== "He Wrd!"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_press_plus(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.press("+")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: + Equal 187 []", # 192 is ` keyCode
|
||||
"Keypress: + Equal 43 43 []", # 126 is ~ charCode
|
||||
"Keyup: + Equal 187 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_press_shift_plus(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.press("Shift++")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: Shift ShiftLeft 16 [Shift]",
|
||||
"Keydown: + Equal 187 [Shift]", # 192 is ` keyCode
|
||||
"Keypress: + Equal 43 43 [Shift]", # 126 is ~ charCode
|
||||
"Keyup: + Equal 187 [Shift]",
|
||||
"Keyup: Shift ShiftLeft 16 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_support_plus_separated_modifiers(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.press("Shift+~")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: Shift ShiftLeft 16 [Shift]",
|
||||
"Keydown: ~ Backquote 192 [Shift]", # 192 is ` keyCode
|
||||
"Keypress: ~ Backquote 126 126 [Shift]", # 126 is ~ charCode
|
||||
"Keyup: ~ Backquote 192 [Shift]",
|
||||
"Keyup: Shift ShiftLeft 16 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_suport_multiple_plus_separated_modifiers(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.press("Control+Shift+~")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: Control ControlLeft 17 [Control]",
|
||||
"Keydown: Shift ShiftLeft 16 [Control Shift]",
|
||||
"Keydown: ~ Backquote 192 [Control Shift]", # 192 is ` keyCode
|
||||
"Keyup: ~ Backquote 192 [Control Shift]",
|
||||
"Keyup: Shift ShiftLeft 16 [Control]",
|
||||
"Keyup: Control ControlLeft 17 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_shift_raw_codes(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/keyboard.html")
|
||||
await page.keyboard.press("Shift+Digit3")
|
||||
assert await page.evaluate("() => getResult()") == "\n".join(
|
||||
[
|
||||
"Keydown: Shift ShiftLeft 16 [Shift]",
|
||||
"Keydown: # Digit3 51 [Shift]", # 51 is # keyCode
|
||||
"Keypress: # Digit3 35 35 [Shift]", # 35 is # charCode
|
||||
"Keyup: # Digit3 51 [Shift]",
|
||||
"Keyup: Shift ShiftLeft 16 []",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_specify_repeat_property(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.focus("textarea")
|
||||
lastEvent = await captureLastKeydown(page)
|
||||
await page.keyboard.down("a")
|
||||
assert await lastEvent.evaluate("e => e.repeat") is False
|
||||
await page.keyboard.press("a")
|
||||
assert await lastEvent.evaluate("e => e.repeat")
|
||||
|
||||
await page.keyboard.down("b")
|
||||
assert await lastEvent.evaluate("e => e.repeat") is False
|
||||
await page.keyboard.down("b")
|
||||
assert await lastEvent.evaluate("e => e.repeat")
|
||||
|
||||
await page.keyboard.up("a")
|
||||
await page.keyboard.down("a")
|
||||
assert await lastEvent.evaluate("e => e.repeat") is False
|
||||
|
||||
|
||||
async def test_should_type_all_kinds_of_characters(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.focus("textarea")
|
||||
text = "This text goes onto two lines.\nThis character is 嗨."
|
||||
await page.keyboard.type(text)
|
||||
assert await page.eval_on_selector("textarea", "t => t.value") == text
|
||||
|
||||
|
||||
async def test_should_specify_location(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
lastEvent = await captureLastKeydown(page)
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
|
||||
await textarea.press("Digit5")
|
||||
assert await lastEvent.evaluate("e => e.location") == 0
|
||||
|
||||
await textarea.press("ControlLeft")
|
||||
assert await lastEvent.evaluate("e => e.location") == 1
|
||||
|
||||
await textarea.press("ControlRight")
|
||||
assert await lastEvent.evaluate("e => e.location") == 2
|
||||
|
||||
await textarea.press("NumpadSubtract")
|
||||
assert await lastEvent.evaluate("e => e.location") == 3
|
||||
|
||||
|
||||
async def test_should_press_enter(page: Page) -> None:
|
||||
await page.set_content("<textarea></textarea>")
|
||||
await page.focus("textarea")
|
||||
lastEventHandle = await captureLastKeydown(page)
|
||||
|
||||
async def testEnterKey(key: str, expectedKey: str, expectedCode: str) -> None:
|
||||
await page.keyboard.press(key)
|
||||
lastEvent = await lastEventHandle.json_value()
|
||||
assert lastEvent["key"] == expectedKey
|
||||
assert lastEvent["code"] == expectedCode
|
||||
value = await page.eval_on_selector("textarea", "t => t.value")
|
||||
assert value == "\n"
|
||||
await page.eval_on_selector("textarea", "t => t.value = ''")
|
||||
|
||||
await testEnterKey("Enter", "Enter", "Enter")
|
||||
await testEnterKey("NumpadEnter", "Enter", "NumpadEnter")
|
||||
await testEnterKey("\n", "Enter", "Enter")
|
||||
await testEnterKey("\r", "Enter", "Enter")
|
||||
|
||||
|
||||
async def test_should_throw_unknown_keys(page: Page, server: Server) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.keyboard.press("NotARealKey")
|
||||
assert exc.value.message == 'Keyboard.press: Unknown key: "NotARealKey"'
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.keyboard.press("ё")
|
||||
assert exc.value.message == 'Keyboard.press: Unknown key: "ё"'
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.keyboard.press("😊")
|
||||
assert exc.value.message == 'Keyboard.press: Unknown key: "😊"'
|
||||
|
||||
|
||||
async def test_should_type_emoji(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
await page.type("textarea", "👹 Tokyo street Japan 🇯🇵")
|
||||
assert (
|
||||
await page.eval_on_selector("textarea", "textarea => textarea.value")
|
||||
== "👹 Tokyo street Japan 🇯🇵"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_type_emoji_into_an_iframe(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "emoji-test", server.PREFIX + "/input/textarea.html")
|
||||
frame = page.frames[1]
|
||||
textarea = await frame.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.type("👹 Tokyo street Japan 🇯🇵")
|
||||
assert (
|
||||
await frame.eval_on_selector("textarea", "textarea => textarea.value")
|
||||
== "👹 Tokyo street Japan 🇯🇵"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_handle_select_all(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.type("some text")
|
||||
await page.keyboard.down("ControlOrMeta")
|
||||
await page.keyboard.press("a")
|
||||
await page.keyboard.up("ControlOrMeta")
|
||||
await page.keyboard.press("Backspace")
|
||||
assert await page.eval_on_selector("textarea", "textarea => textarea.value") == ""
|
||||
|
||||
|
||||
async def test_should_be_able_to_prevent_select_all(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.type("some text")
|
||||
await page.eval_on_selector(
|
||||
"textarea",
|
||||
"""textarea => {
|
||||
textarea.addEventListener('keydown', event => {
|
||||
if (event.key === 'a' && (event.metaKey || event.ctrlKey))
|
||||
event.preventDefault();
|
||||
}, false);
|
||||
}""",
|
||||
)
|
||||
|
||||
await page.keyboard.down("ControlOrMeta")
|
||||
await page.keyboard.press("a")
|
||||
await page.keyboard.up("ControlOrMeta")
|
||||
await page.keyboard.press("Backspace")
|
||||
assert (
|
||||
await page.eval_on_selector("textarea", "textarea => textarea.value")
|
||||
== "some tex"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.only_platform("darwin")
|
||||
@pytest.mark.skip_browser("firefox") # Upstream issue
|
||||
async def test_should_support_macos_shortcuts(
|
||||
page: Page, server: Server, is_firefox: bool, is_mac: bool
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/textarea.html")
|
||||
textarea = await page.query_selector("textarea")
|
||||
assert textarea
|
||||
await textarea.type("some text")
|
||||
# select one word backwards
|
||||
await page.keyboard.press("Shift+Control+Alt+KeyB")
|
||||
await page.keyboard.press("Backspace")
|
||||
assert (
|
||||
await page.eval_on_selector("textarea", "textarea => textarea.value") == "some "
|
||||
)
|
||||
|
||||
|
||||
async def test_should_press_the_meta_key(page: Page) -> None:
|
||||
lastEvent = await captureLastKeydown(page)
|
||||
await page.keyboard.press("Meta")
|
||||
v = await lastEvent.json_value()
|
||||
metaKey = v["metaKey"]
|
||||
key = v["key"]
|
||||
code = v["code"]
|
||||
assert key == "Meta"
|
||||
assert code == "MetaLeft"
|
||||
assert metaKey
|
||||
|
||||
|
||||
async def test_should_work_after_a_cross_origin_navigation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/empty.html")
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
|
||||
lastEvent = await captureLastKeydown(page)
|
||||
await page.keyboard.press("a")
|
||||
assert await lastEvent.evaluate("l => l.key") == "a"
|
||||
|
||||
|
||||
# event.keyIdentifier has been removed from all browsers except WebKit
|
||||
@pytest.mark.only_browser("webkit")
|
||||
async def test_should_expose_keyIdentifier_in_webkit(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
lastEvent = await captureLastKeydown(page)
|
||||
keyMap = {
|
||||
"ArrowUp": "Up",
|
||||
"ArrowDown": "Down",
|
||||
"ArrowLeft": "Left",
|
||||
"ArrowRight": "Right",
|
||||
"Backspace": "U+0008",
|
||||
"Tab": "U+0009",
|
||||
"Delete": "U+007F",
|
||||
"a": "U+0041",
|
||||
"b": "U+0042",
|
||||
"F12": "F12",
|
||||
}
|
||||
for key, keyIdentifier in keyMap.items():
|
||||
await page.keyboard.press(key)
|
||||
assert await lastEvent.evaluate("e => e.keyIdentifier") == keyIdentifier
|
||||
|
||||
|
||||
async def test_should_scroll_with_pagedown(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/scrollable.html")
|
||||
# A click is required for WebKit to send the event into the body.
|
||||
await page.click("body")
|
||||
await page.keyboard.press("PageDown")
|
||||
# We can't wait for the scroll to finish, so just wait for it to start.
|
||||
await page.wait_for_function("() => scrollY > 0")
|
||||
@@ -0,0 +1,118 @@
|
||||
# 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
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import BrowserType, Error
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
async def test_browser_type_launch_should_reject_all_promises_when_browser_is_closed(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**launch_arguments)
|
||||
page = await (await browser.new_context()).new_page()
|
||||
never_resolves = asyncio.create_task(page.evaluate("() => new Promise(r => {})"))
|
||||
await page.close()
|
||||
with pytest.raises(Error) as exc:
|
||||
await never_resolves
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc.value.message
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async 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:
|
||||
await browser_type.launch(**launch_arguments, args=["http://example.com"])
|
||||
assert "can not specify page" in exc.value.message
|
||||
|
||||
|
||||
async 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):
|
||||
await browser_type.launch(
|
||||
**launch_arguments,
|
||||
executable_path=assetdir / "dummy_bad_browser_executable.js",
|
||||
)
|
||||
|
||||
|
||||
async 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:
|
||||
await browser_type.launch(
|
||||
**launch_arguments, executable_path="random-invalid-path"
|
||||
)
|
||||
assert "executable doesn't exist" in exc.value.message
|
||||
|
||||
|
||||
async 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)
|
||||
|
||||
|
||||
async 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")
|
||||
|
||||
|
||||
async def test_browser_close_should_fire_close_event_for_all_contexts(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**launch_arguments)
|
||||
context = await browser.new_context()
|
||||
closed = []
|
||||
context.on("close", lambda _: closed.append(True))
|
||||
await browser.close()
|
||||
assert closed == [True]
|
||||
|
||||
|
||||
async def test_browser_close_should_be_callable_twice(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
browser = await browser_type.launch(**launch_arguments)
|
||||
await asyncio.gather(
|
||||
browser.close(),
|
||||
browser.close(),
|
||||
)
|
||||
await browser.close()
|
||||
|
||||
|
||||
async def test_browser_type_launch_should_accept_ignore_default_args_false(
|
||||
browser_type: BrowserType, launch_arguments: Dict
|
||||
) -> None:
|
||||
# Regression for https://github.com/microsoft/playwright-python/issues/3005:
|
||||
# passing False used to crash with "expected array, got boolean".
|
||||
browser = await browser_type.launch(**launch_arguments, ignore_default_args=False)
|
||||
await browser.close()
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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.async_api import Page, Response
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_listeners(page: Page, server: Server) -> None:
|
||||
log = []
|
||||
|
||||
def print_response(response: Response) -> None:
|
||||
log.append(response)
|
||||
|
||||
page.on("response", print_response)
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
assert len(log) > 0
|
||||
page.remove_listener("response", print_response)
|
||||
|
||||
log = []
|
||||
await page.goto(f"{server.PREFIX}/input/textarea.html")
|
||||
assert len(log) == 0
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,922 @@
|
||||
# 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
|
||||
import json
|
||||
from asyncio import Future
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
import pytest
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.async_api import Browser, Error, Page, Request, Response, Route
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
def adjust_server_headers(headers: Dict[str, str], browser_name: str) -> Dict[str, str]:
|
||||
if browser_name != "firefox":
|
||||
return headers
|
||||
headers = headers.copy()
|
||||
headers.pop("priority", None)
|
||||
return headers
|
||||
|
||||
|
||||
async def test_request_fulfill(page: Page, server: Server) -> None:
|
||||
async def handle_request(route: Route, request: Request) -> None:
|
||||
headers = await route.request.all_headers()
|
||||
assert headers["accept"]
|
||||
assert route.request == request
|
||||
assert repr(route) == f"<Route request={route.request}>"
|
||||
assert "empty.html" in request.url
|
||||
assert request.headers["user-agent"]
|
||||
assert request.method == "GET"
|
||||
assert request.post_data is None
|
||||
assert request.is_navigation_request()
|
||||
assert request.resource_type == "document"
|
||||
assert request.frame == page.main_frame
|
||||
assert request.frame.url == "about:blank"
|
||||
assert (
|
||||
repr(request) == f"<Request url={request.url!r} method={request.method!r}>"
|
||||
)
|
||||
await route.fulfill(body="Text")
|
||||
|
||||
await page.route(
|
||||
"**/empty.html",
|
||||
lambda route, request: asyncio.create_task(handle_request(route, request)),
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
|
||||
assert response.ok
|
||||
assert (
|
||||
repr(response) == f"<Response url={response.url!r} request={response.request}>"
|
||||
)
|
||||
assert await response.text() == "Text"
|
||||
|
||||
|
||||
async def test_request_continue(page: Page, server: Server) -> None:
|
||||
async def handle_request(
|
||||
route: Route, request: Request, intercepted: List[bool]
|
||||
) -> None:
|
||||
intercepted.append(True)
|
||||
await route.continue_()
|
||||
|
||||
intercepted: List[bool] = []
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route, request: asyncio.create_task(
|
||||
handle_request(route, request, intercepted)
|
||||
),
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.ok
|
||||
assert intercepted == [True]
|
||||
assert await page.title() == ""
|
||||
|
||||
|
||||
async def test_page_events_request_should_fire_for_navigation_requests(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
async def test_page_events_request_should_accept_method(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
class Log:
|
||||
def __init__(self) -> None:
|
||||
self.requests: List[Request] = []
|
||||
|
||||
def handle(self, request: Request) -> None:
|
||||
self.requests.append(request)
|
||||
|
||||
log = Log()
|
||||
page.on("request", log.handle)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(log.requests) == 1
|
||||
|
||||
|
||||
async def test_page_events_request_should_fire_for_iframes(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
async def test_page_events_request_should_fire_for_fetches(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate('() => fetch("/empty.html")')
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
async def test_page_events_request_should_report_requests_and_responses_handled_by_service_worker(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
|
||||
await page.evaluate("() => window.activationPromise")
|
||||
sw_response = None
|
||||
async with page.expect_request("**/*") as request_info:
|
||||
sw_response = await page.evaluate('() => fetchDummy("foo")')
|
||||
request = await request_info.value
|
||||
assert sw_response == "responseFromServiceWorker:foo"
|
||||
assert request.url == server.PREFIX + "/serviceworkers/fetchdummy/foo"
|
||||
response = await request.response()
|
||||
assert response
|
||||
assert response.url == server.PREFIX + "/serviceworkers/fetchdummy/foo"
|
||||
assert await response.text() == "responseFromServiceWorker:foo"
|
||||
|
||||
|
||||
async def test_request_frame_should_work_for_main_frame_navigation_request(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(requests) == 1
|
||||
assert requests[0].frame == page.main_frame
|
||||
|
||||
|
||||
async def test_request_frame_should_work_for_subframe_navigation_request(
|
||||
page: Page, server: Server, utils: Utils
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
|
||||
assert len(requests) == 1
|
||||
assert requests[0].frame == page.frames[1]
|
||||
|
||||
|
||||
async def test_request_frame_should_work_for_fetch_requests(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
requests: List[Request] = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.evaluate('() => fetch("/digits/1.png")')
|
||||
requests = [r for r in requests if "favicon" not in r.url]
|
||||
assert len(requests) == 1
|
||||
assert requests[0].frame == page.main_frame
|
||||
|
||||
|
||||
async def test_request_headers_should_work(
|
||||
page: Page, server: Server, is_chromium: bool, is_firefox: bool, is_webkit: bool
|
||||
) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
if is_chromium:
|
||||
assert "Chrome" in response.request.headers["user-agent"]
|
||||
elif is_firefox:
|
||||
assert "Firefox" in response.request.headers["user-agent"]
|
||||
elif is_webkit:
|
||||
assert "WebKit" in response.request.headers["user-agent"]
|
||||
|
||||
|
||||
async def test_request_headers_should_get_the_same_headers_as_the_server(
|
||||
page: Page,
|
||||
server: Server,
|
||||
is_webkit: bool,
|
||||
is_win: bool,
|
||||
browser_name: str,
|
||||
) -> None:
|
||||
if is_webkit and is_win:
|
||||
pytest.xfail("Curl does not show accept-encoding and accept-language")
|
||||
server_request_headers_future: Future[Dict[str, str]] = asyncio.Future()
|
||||
|
||||
def handle(request: http.Request) -> None:
|
||||
normalized_headers = {
|
||||
key.decode().lower(): value[0].decode()
|
||||
for key, value in request.requestHeaders.getAllRawHeaders()
|
||||
}
|
||||
server_request_headers_future.set_result(normalized_headers)
|
||||
request.write(b"done")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/empty.html", handle)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
server_headers = adjust_server_headers(
|
||||
await server_request_headers_future, browser_name
|
||||
)
|
||||
assert await response.request.all_headers() == server_headers
|
||||
|
||||
|
||||
async def test_request_headers_should_get_the_same_headers_as_the_server_cors(
|
||||
page: Page, server: Server, is_webkit: bool, is_win: bool, browser_name: str
|
||||
) -> None:
|
||||
if is_webkit and is_win:
|
||||
pytest.xfail("Curl does not show accept-encoding and accept-language")
|
||||
await page.goto(server.PREFIX + "/empty.html")
|
||||
server_request_headers_future: Future[Dict[str, str]] = asyncio.Future()
|
||||
|
||||
def handle_something(request: http.Request) -> None:
|
||||
normalized_headers = {
|
||||
key.decode().lower(): value[0].decode()
|
||||
for key, value in request.requestHeaders.getAllRawHeaders()
|
||||
}
|
||||
server_request_headers_future.set_result(normalized_headers)
|
||||
request.setHeader("Access-Control-Allow-Origin", "*")
|
||||
request.write(b"done")
|
||||
request.finish()
|
||||
|
||||
server.set_route("/something", handle_something)
|
||||
|
||||
text = None
|
||||
async with page.expect_request("**/*") as request_info:
|
||||
text = await page.evaluate(
|
||||
"""async url => {
|
||||
const data = await fetch(url);
|
||||
return data.text();
|
||||
}""",
|
||||
server.CROSS_PROCESS_PREFIX + "/something",
|
||||
)
|
||||
request = await request_info.value
|
||||
assert text == "done"
|
||||
server_headers = adjust_server_headers(
|
||||
await server_request_headers_future, browser_name
|
||||
)
|
||||
assert await request.all_headers() == server_headers
|
||||
|
||||
|
||||
async def test_should_report_request_headers_array(
|
||||
page: Page, server: Server, is_win: bool, browser_name: str
|
||||
) -> None:
|
||||
if is_win and browser_name == "webkit":
|
||||
pytest.skip("libcurl does not support non-set-cookie multivalue headers")
|
||||
expected_headers = []
|
||||
|
||||
def handle(request: http.Request) -> None:
|
||||
for name, values in request.requestHeaders.getAllRawHeaders():
|
||||
for value in values:
|
||||
if browser_name == "firefox" and name.decode().lower() == "priority":
|
||||
continue
|
||||
expected_headers.append(
|
||||
{"name": name.decode().lower(), "value": value.decode()}
|
||||
)
|
||||
request.finish()
|
||||
|
||||
server.set_route("/headers", handle)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_request("*/**") as request_info:
|
||||
await page.evaluate(
|
||||
"""() => fetch('/headers', {
|
||||
headers: [
|
||||
['header-a', 'value-a'],
|
||||
['header-b', 'value-b'],
|
||||
['header-a', 'value-a-1'],
|
||||
['header-a', 'value-a-2'],
|
||||
]
|
||||
})
|
||||
"""
|
||||
)
|
||||
request = await request_info.value
|
||||
sorted_pw_request_headers = sorted(
|
||||
list(
|
||||
map(
|
||||
lambda header: {
|
||||
"name": header["name"].lower(),
|
||||
"value": header["value"],
|
||||
},
|
||||
await request.headers_array(),
|
||||
)
|
||||
),
|
||||
key=lambda header: header["name"],
|
||||
)
|
||||
sorted_expected_headers = sorted(
|
||||
expected_headers, key=lambda header: header["name"]
|
||||
)
|
||||
assert sorted_pw_request_headers == sorted_expected_headers
|
||||
assert await request.header_value("Header-A") == "value-a, value-a-1, value-a-2"
|
||||
assert await request.header_value("not-there") is None
|
||||
|
||||
|
||||
async def test_should_report_response_headers_array(
|
||||
page: Page, server: Server, is_win: bool, browser_name: str
|
||||
) -> None:
|
||||
if is_win and browser_name == "webkit":
|
||||
pytest.skip("libcurl does not support non-set-cookie multivalue headers")
|
||||
expected_headers = {
|
||||
"header-a": ["value-a", "value-a-1", "value-a-2"],
|
||||
"header-b": ["value-b"],
|
||||
"set-cookie": ["a=b", "c=d"],
|
||||
}
|
||||
|
||||
def handle(request: http.Request) -> None:
|
||||
for key in expected_headers:
|
||||
for value in expected_headers[key]:
|
||||
request.responseHeaders.addRawHeader(key, value)
|
||||
request.finish()
|
||||
|
||||
server.set_route("/headers", handle)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_response("*/**") as response_info:
|
||||
await page.evaluate(
|
||||
"""() => fetch('/headers')
|
||||
"""
|
||||
)
|
||||
response = await response_info.value
|
||||
actual_headers: Dict[str, List[str]] = {}
|
||||
for header in await response.headers_array():
|
||||
name = header["name"].lower()
|
||||
value = header["value"]
|
||||
if not actual_headers.get(name):
|
||||
actual_headers[name] = []
|
||||
actual_headers[name].append(value)
|
||||
|
||||
for key in ["Keep-Alive", "Connection", "Date", "Transfer-Encoding"]:
|
||||
if key in actual_headers:
|
||||
actual_headers.pop(key)
|
||||
if key.lower() in actual_headers:
|
||||
actual_headers.pop(key.lower())
|
||||
assert actual_headers == expected_headers
|
||||
assert await response.header_value("not-there") is None
|
||||
assert await response.header_value("set-cookie") == "a=b\nc=d"
|
||||
assert await response.header_value("header-a") == "value-a, value-a-1, value-a-2"
|
||||
assert await response.header_values("set-cookie") == ["a=b", "c=d"]
|
||||
|
||||
|
||||
async def test_response_headers_should_work(page: Page, server: Server) -> None:
|
||||
server.set_route("/empty.html", lambda r: (r.setHeader("foo", "bar"), r.finish()))
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.headers["foo"] == "bar"
|
||||
assert (await response.all_headers())["foo"] == "bar"
|
||||
|
||||
|
||||
async def test_request_post_data_should_work(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route("/post", lambda r: r.finish())
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.evaluate(
|
||||
'() => fetch("./post", { method: "POST", body: JSON.stringify({foo: "bar"})})'
|
||||
)
|
||||
assert len(requests) == 1
|
||||
assert requests[0].post_data == '{"foo":"bar"}'
|
||||
|
||||
|
||||
async def test_request_post_data__should_be_undefined_when_there_is_no_post_data(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.request.post_data is None
|
||||
|
||||
|
||||
async def test_should_parse_the_json_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route("/post", lambda req: req.finish())
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.evaluate(
|
||||
"""() => fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar' }) })"""
|
||||
)
|
||||
assert len(requests) == 1
|
||||
assert requests[0].post_data_json == {"foo": "bar"}
|
||||
|
||||
|
||||
async def test_should_parse_the_data_if_content_type_is_form_urlencoded(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route("/post", lambda req: req.finish())
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.set_content(
|
||||
"""<form method='POST' action='/post'><input type='text' name='foo' value='bar'><input type='number' name='baz' value='123'><input type='submit'></form>"""
|
||||
)
|
||||
await page.click("input[type=submit]")
|
||||
assert len(requests) == 1
|
||||
assert requests[0].post_data_json == {"foo": "bar", "baz": "123"}
|
||||
|
||||
|
||||
async def test_should_be_undefined_when_there_is_no_post_data(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.request.post_data_json is None
|
||||
|
||||
|
||||
async def test_should_return_post_data_without_content_type(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_request("**/*") as request_info:
|
||||
await page.evaluate(
|
||||
"""({url}) => {
|
||||
const request = new Request(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ value: 42 }),
|
||||
});
|
||||
request.headers.set('content-type', '');
|
||||
return fetch(request);
|
||||
}""",
|
||||
{"url": server.PREFIX + "/title.html"},
|
||||
)
|
||||
request = await request_info.value
|
||||
assert request.post_data_json == {"value": 42}
|
||||
|
||||
|
||||
async def test_should_throw_on_invalid_json_in_post_data(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_request("**/*") as request_info:
|
||||
await page.evaluate(
|
||||
"""({url}) => {
|
||||
const request = new Request(url, {
|
||||
method: 'POST',
|
||||
body: '<not a json>',
|
||||
});
|
||||
request.headers.set('content-type', '');
|
||||
return fetch(request);
|
||||
}""",
|
||||
{"url": server.PREFIX + "/title.html"},
|
||||
)
|
||||
request = await request_info.value
|
||||
with pytest.raises(Error) as exc_info:
|
||||
print(request.post_data_json)
|
||||
assert "POST data is not a valid JSON object: <not a json>" in str(exc_info.value)
|
||||
|
||||
|
||||
async def test_should_work_with_binary_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route("/post", lambda req: req.finish())
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.evaluate(
|
||||
"""async () => {
|
||||
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })
|
||||
}"""
|
||||
)
|
||||
assert len(requests) == 1
|
||||
buffer = requests[0].post_data_buffer
|
||||
assert len(buffer) == 256
|
||||
for i in range(256):
|
||||
assert buffer[i] == i
|
||||
|
||||
|
||||
async def test_should_work_with_binary_post_data_and_interception(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route("/post", lambda req: req.finish())
|
||||
requests = []
|
||||
await page.route("/post", lambda route: asyncio.ensure_future(route.continue_()))
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.evaluate(
|
||||
"""async () => {
|
||||
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })
|
||||
}"""
|
||||
)
|
||||
assert len(requests) == 1
|
||||
buffer = requests[0].post_data_buffer
|
||||
assert len(buffer) == 256
|
||||
for i in range(256):
|
||||
assert buffer[i] == i
|
||||
|
||||
|
||||
async def test_response_text_should_work(page: Page, server: Server) -> None:
|
||||
response = await page.goto(server.PREFIX + "/simple.json")
|
||||
assert response
|
||||
assert await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
async def test_response_text_should_return_uncompressed_text(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
server.enable_gzip("/simple.json")
|
||||
response = await page.goto(server.PREFIX + "/simple.json")
|
||||
assert response
|
||||
assert response.headers["content-encoding"] == "gzip"
|
||||
assert await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
|
||||
async def test_response_text_should_throw_when_requesting_body_of_redirected_response(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
server.set_redirect("/foo.html", "/empty.html")
|
||||
response = await page.goto(server.PREFIX + "/foo.html")
|
||||
assert response
|
||||
redirected_from = response.request.redirected_from
|
||||
assert redirected_from
|
||||
redirected = await redirected_from.response()
|
||||
assert redirected
|
||||
assert redirected.status == 302
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await redirected.text()
|
||||
except Error as exc:
|
||||
error = exc
|
||||
assert error
|
||||
assert "Response body is unavailable for redirect responses" in error.message
|
||||
|
||||
|
||||
async def test_response_json_should_work(page: Page, server: Server) -> None:
|
||||
response = await page.goto(server.PREFIX + "/simple.json")
|
||||
assert response
|
||||
assert await response.json() == {"foo": "bar"}
|
||||
|
||||
|
||||
async def test_response_body_should_work(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
response = await page.goto(server.PREFIX + "/pptr.png")
|
||||
assert response
|
||||
with open(
|
||||
assetdir / "pptr.png",
|
||||
"rb",
|
||||
) as fd:
|
||||
assert fd.read() == await response.body()
|
||||
|
||||
|
||||
async def test_response_body_should_work_with_compression(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
server.enable_gzip("/pptr.png")
|
||||
response = await page.goto(server.PREFIX + "/pptr.png")
|
||||
assert response
|
||||
with open(
|
||||
assetdir / "pptr.png",
|
||||
"rb",
|
||||
) as fd:
|
||||
assert fd.read() == await response.body()
|
||||
|
||||
|
||||
async def test_response_status_text_should_work(page: Page, server: Server) -> None:
|
||||
server.set_route("/cool", lambda r: (r.setResponseCode(200, b"cool!"), r.finish()))
|
||||
|
||||
response = await page.goto(server.PREFIX + "/cool")
|
||||
assert response
|
||||
assert response.status_text == "cool!"
|
||||
|
||||
|
||||
async def test_request_resource_type_should_return_event_source(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
SSE_MESSAGE = {"foo": "bar"}
|
||||
# 1. Setup server-sent events on server that immediately sends a message to the client.
|
||||
server.set_route(
|
||||
"/sse",
|
||||
lambda r: (
|
||||
r.setHeader("Content-Type", "text/event-stream"),
|
||||
r.setHeader("Connection", "keep-alive"),
|
||||
r.setHeader("Cache-Control", "no-cache"),
|
||||
r.setResponseCode(200),
|
||||
r.write(f"data: {json.dumps(SSE_MESSAGE)}\n\n".encode()),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
# 2. Subscribe to page request events.
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
# 3. Connect to EventSource in browser and return first message.
|
||||
assert (
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const eventSource = new EventSource('/sse');
|
||||
return new Promise(resolve => {
|
||||
eventSource.onmessage = e => resolve(JSON.parse(e.data));
|
||||
});
|
||||
}"""
|
||||
)
|
||||
== SSE_MESSAGE
|
||||
)
|
||||
assert requests[0].resource_type == "eventsource"
|
||||
|
||||
|
||||
async def test_network_events_request(page: Page, server: Server) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(requests) == 1
|
||||
assert requests[0].url == server.EMPTY_PAGE
|
||||
assert requests[0].resource_type == "document"
|
||||
assert requests[0].method == "GET"
|
||||
assert await requests[0].response()
|
||||
assert requests[0].frame == page.main_frame
|
||||
assert requests[0].frame.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_network_events_response(page: Page, server: Server) -> None:
|
||||
responses = []
|
||||
page.on("response", lambda r: responses.append(r))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(responses) == 1
|
||||
assert responses[0].url == server.EMPTY_PAGE
|
||||
assert responses[0].status == 200
|
||||
assert responses[0].ok
|
||||
assert responses[0].request
|
||||
|
||||
|
||||
async def test_network_events_request_failed(
|
||||
page: Page,
|
||||
server: Server,
|
||||
is_chromium: bool,
|
||||
is_webkit: bool,
|
||||
is_mac: bool,
|
||||
is_win: bool,
|
||||
) -> None:
|
||||
def handle_request(request: TestServerRequest) -> None:
|
||||
request.setHeader("Content-Type", "text/css")
|
||||
request.loseConnection()
|
||||
|
||||
server.set_route("/one-style.css", handle_request)
|
||||
|
||||
failed_requests = []
|
||||
page.on("requestfailed", lambda request: failed_requests.append(request))
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
# TODO: https://github.com/microsoft/playwright/issues/12789
|
||||
assert len(failed_requests) >= 1
|
||||
assert "one-style.css" in failed_requests[0].url
|
||||
assert await failed_requests[0].response() is None
|
||||
assert failed_requests[0].resource_type == "stylesheet"
|
||||
if is_chromium:
|
||||
assert failed_requests[0].failure == "net::ERR_EMPTY_RESPONSE"
|
||||
elif is_webkit:
|
||||
if is_mac:
|
||||
assert failed_requests[0].failure == "The network connection was lost."
|
||||
elif is_win:
|
||||
assert (
|
||||
failed_requests[0].failure
|
||||
== "Server returned nothing (no headers, no data)"
|
||||
)
|
||||
else:
|
||||
assert failed_requests[0].failure in [
|
||||
"Message Corrupt",
|
||||
"Connection terminated unexpectedly",
|
||||
]
|
||||
else:
|
||||
assert failed_requests[0].failure == "NS_ERROR_NET_RESET"
|
||||
assert failed_requests[0].frame
|
||||
|
||||
|
||||
async def test_network_events_request_finished(page: Page, server: Server) -> None:
|
||||
async with page.expect_event("requestfinished") as event_info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
request = await event_info.value
|
||||
assert request.url == server.EMPTY_PAGE
|
||||
assert await request.response()
|
||||
assert request.frame == page.main_frame
|
||||
assert request.frame.url == server.EMPTY_PAGE
|
||||
|
||||
|
||||
async def test_network_events_should_fire_events_in_proper_order(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
events = []
|
||||
page.on("request", lambda request: events.append("request"))
|
||||
page.on("response", lambda response: events.append("response"))
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
await response.finished()
|
||||
events.append("requestfinished")
|
||||
assert events == ["request", "response", "requestfinished"]
|
||||
|
||||
|
||||
async def test_network_events_should_support_redirects(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
FOO_URL = server.PREFIX + "/foo.html"
|
||||
events: Dict[str, List[Union[str, int]]] = {}
|
||||
events[FOO_URL] = []
|
||||
events[server.EMPTY_PAGE] = []
|
||||
|
||||
def _handle_on_request(request: Request) -> None:
|
||||
events[request.url].append(request.method)
|
||||
|
||||
page.on("request", _handle_on_request)
|
||||
|
||||
def _handle_on_response(response: Response) -> None:
|
||||
events[response.url].append(response.status)
|
||||
|
||||
page.on("response", _handle_on_response)
|
||||
|
||||
def _handle_on_requestfinished(request: Request) -> None:
|
||||
events[request.url].append("DONE")
|
||||
|
||||
page.on("requestfinished", _handle_on_requestfinished)
|
||||
|
||||
def _handle_on_requestfailed(request: Request) -> None:
|
||||
events[request.url].append("FAIL")
|
||||
|
||||
page.on("requestfailed", _handle_on_requestfailed)
|
||||
server.set_redirect("/foo.html", "/empty.html")
|
||||
response = await page.goto(FOO_URL)
|
||||
assert response
|
||||
await response.finished()
|
||||
expected = {}
|
||||
expected[FOO_URL] = ["GET", 302, "DONE"]
|
||||
expected[server.EMPTY_PAGE] = ["GET", 200, "DONE"]
|
||||
assert events == expected
|
||||
redirected_from = response.request.redirected_from
|
||||
assert redirected_from
|
||||
assert "/foo.html" in redirected_from.url
|
||||
assert redirected_from.redirected_from is None
|
||||
assert redirected_from.redirected_to == response.request
|
||||
|
||||
|
||||
async def test_request_is_navigation_request_should_work(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
requests: Dict[str, Request] = {}
|
||||
|
||||
def handle_request(request: Request) -> None:
|
||||
requests[request.url.split("/").pop()] = request
|
||||
|
||||
page.on("request", handle_request)
|
||||
server.set_redirect("/rrredirect", "/frames/one-frame.html")
|
||||
await page.goto(server.PREFIX + "/rrredirect")
|
||||
assert requests["rrredirect"].is_navigation_request()
|
||||
assert requests["one-frame.html"].is_navigation_request()
|
||||
assert requests["frame.html"].is_navigation_request()
|
||||
assert requests["script.js"].is_navigation_request() is False
|
||||
assert requests["style.css"].is_navigation_request() is False
|
||||
|
||||
|
||||
async def test_request_is_navigation_request_should_work_when_navigating_to_image(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
requests = []
|
||||
page.on("request", lambda r: requests.append(r))
|
||||
await page.goto(server.PREFIX + "/pptr.png")
|
||||
assert requests[0].is_navigation_request()
|
||||
|
||||
|
||||
async def test_set_extra_http_headers_should_work(page: Page, server: Server) -> None:
|
||||
await page.set_extra_http_headers({"foo": "bar"})
|
||||
|
||||
request = (
|
||||
await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
)[0]
|
||||
assert request.getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_set_extra_http_headers_should_work_with_redirects(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
server.set_redirect("/foo.html", "/empty.html")
|
||||
await page.set_extra_http_headers({"foo": "bar"})
|
||||
|
||||
request = (
|
||||
await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.PREFIX + "/foo.html"),
|
||||
)
|
||||
)[0]
|
||||
assert request.getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_set_extra_http_headers_should_work_with_extra_headers_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
await context.set_extra_http_headers({"foo": "bar"})
|
||||
|
||||
page = await context.new_page()
|
||||
request = (
|
||||
await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
)[0]
|
||||
await context.close()
|
||||
assert request.getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_set_extra_http_headers_should_override_extra_headers_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(extra_http_headers={"fOo": "bAr", "baR": "foO"})
|
||||
|
||||
page = await context.new_page()
|
||||
await page.set_extra_http_headers({"Foo": "Bar"})
|
||||
|
||||
request = (
|
||||
await asyncio.gather(
|
||||
server.wait_for_request("/empty.html"),
|
||||
page.goto(server.EMPTY_PAGE),
|
||||
)
|
||||
)[0]
|
||||
await context.close()
|
||||
assert request.getHeader("foo") == "Bar"
|
||||
assert request.getHeader("bar") == "foO"
|
||||
|
||||
|
||||
async def test_set_extra_http_headers_should_throw_for_non_string_header_values(
|
||||
page: Page,
|
||||
) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.set_extra_http_headers({"foo": 1}) # type: ignore
|
||||
except Error as exc:
|
||||
error = exc
|
||||
assert error
|
||||
assert (
|
||||
error.message
|
||||
== "Page.set_extra_http_headers: headers[0].value: expected string, got number"
|
||||
)
|
||||
|
||||
|
||||
async def test_response_server_addr(page: Page, server: Server) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
server_addr = await response.server_addr()
|
||||
assert server_addr
|
||||
assert server_addr["port"] == server.PORT
|
||||
assert server_addr["ipAddress"] in ["127.0.0.1", "[::1]"]
|
||||
|
||||
|
||||
async 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 = await browser.new_page(ignore_https_errors=True)
|
||||
response = await page.goto(https_server.EMPTY_PAGE)
|
||||
assert response
|
||||
await response.finished()
|
||||
security_details = await 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,
|
||||
}
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_response_security_details_none_without_https(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
security_details = await response.security_details()
|
||||
assert security_details is None
|
||||
|
||||
|
||||
async def test_should_report_if_request_was_from_service_worker(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
response = await page.goto(server.PREFIX + "/serviceworkers/fetch/sw.html")
|
||||
assert response
|
||||
assert not response.from_service_worker
|
||||
await page.evaluate("() => window.activationPromise")
|
||||
async with page.expect_response("**/example.txt") as response_info:
|
||||
await page.evaluate("() => fetch('/example.txt')")
|
||||
response = await response_info.value
|
||||
assert response.from_service_worker
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,388 @@
|
||||
# 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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Locator, Page, expect
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server) -> None:
|
||||
await 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")
|
||||
|
||||
async def handler(locator: Locator) -> None:
|
||||
assert locator == original_locator
|
||||
nonlocal before_count
|
||||
nonlocal after_count
|
||||
before_count += 1
|
||||
await page.locator("#close").click()
|
||||
after_count += 1
|
||||
|
||||
await 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],
|
||||
]:
|
||||
await page.locator("#aside").hover()
|
||||
before_count = 0
|
||||
after_count = 0
|
||||
await page.evaluate(
|
||||
"(args) => { window.clicked = 0; window.setupAnnoyingInterstitial(...args); }",
|
||||
args,
|
||||
)
|
||||
assert before_count == 0
|
||||
assert after_count == 0
|
||||
await page.locator("#target").click()
|
||||
assert before_count == args[1]
|
||||
assert after_count == args[1]
|
||||
assert await page.evaluate("window.clicked") == 1
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
|
||||
|
||||
async def test_should_work_with_a_custom_check(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
async def handler() -> None:
|
||||
if await page.get_by_text("This interstitial covers the button").is_visible():
|
||||
await page.locator("#close").click()
|
||||
|
||||
await page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
|
||||
|
||||
for args in [
|
||||
["mouseover", 2],
|
||||
["none", 1],
|
||||
["remove", 1],
|
||||
["hide", 1],
|
||||
]:
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
"(args) => { window.clicked = 0; window.setupAnnoyingInterstitial(...args); }",
|
||||
args,
|
||||
)
|
||||
await page.locator("#target").click()
|
||||
assert await page.evaluate("window.clicked") == 1
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
|
||||
|
||||
async def test_should_work_with_locator_hover(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
'() => { window.setupAnnoyingInterstitial("pointerover", 1, "capture"); }'
|
||||
)
|
||||
await page.locator("#target").hover()
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert (
|
||||
await page.eval_on_selector(
|
||||
"#target", "e => window.getComputedStyle(e).backgroundColor"
|
||||
)
|
||||
== "rgb(255, 255, 0)"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_not_work_with_force_true(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate('() => { window.setupAnnoyingInterstitial("none", 1); }')
|
||||
await page.locator("#target").click(force=True, timeout=2000)
|
||||
assert await page.locator("#interstitial").is_visible()
|
||||
assert await page.evaluate("window.clicked") is None
|
||||
|
||||
|
||||
async def test_should_throw_when_page_closes(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), lambda: page.close()
|
||||
)
|
||||
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("mouseover", 1); }'
|
||||
)
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.locator("#target").click()
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc.value.message
|
||||
|
||||
|
||||
async def test_should_throw_when_handler_times_out(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
called = 0
|
||||
stall_future: asyncio.Future[None] = asyncio.Future()
|
||||
|
||||
async def handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
# Deliberately timeout.
|
||||
await stall_future
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), handler
|
||||
)
|
||||
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("mouseover", 1); }'
|
||||
)
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.locator("#target").click(timeout=3000)
|
||||
assert "Timeout 3000ms exceeded" in exc.value.message
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
await 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
|
||||
stall_future.cancel()
|
||||
|
||||
|
||||
async def test_should_work_with_to_be_visible(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
|
||||
called = 0
|
||||
|
||||
async def handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
await page.locator("#close").click()
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_text("This interstitial covers the button"), handler
|
||||
)
|
||||
|
||||
await page.evaluate(
|
||||
'() => { window.clicked = 0; window.setupAnnoyingInterstitial("remove", 1); }'
|
||||
)
|
||||
await expect(page.locator("#target")).to_be_visible()
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 1
|
||||
|
||||
|
||||
async def test_should_work_when_owner_frame_detaches(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await 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);
|
||||
}
|
||||
"""
|
||||
)
|
||||
await page.add_locator_handler(
|
||||
page.frame_locator("iframe").locator("body"),
|
||||
lambda: page.locator("#close").click(),
|
||||
)
|
||||
await page.locator("#target").click()
|
||||
assert await page.query_selector("iframe") is None
|
||||
assert await page.evaluate("window._clicked") is True
|
||||
|
||||
|
||||
async def test_should_work_with_times_option(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.locator("body"), _handler, no_wait_after=True, times=2
|
||||
)
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('mouseover', 4);
|
||||
}
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.locator("#target").click(timeout=3000)
|
||||
assert called == 2
|
||||
assert await page.evaluate("window.clicked") == 0
|
||||
await 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
|
||||
)
|
||||
|
||||
|
||||
async def test_should_wait_for_hidden_by_default(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
async def _handler(button: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
await button.click()
|
||||
|
||||
await page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('timeout', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
await page.locator("#target").click()
|
||||
assert await page.evaluate("window.clicked") == 1
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 1
|
||||
|
||||
|
||||
async def test_should_wait_for_hidden_by_default_2(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
def _handler() -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
|
||||
await page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.locator("#target").click(timeout=3000)
|
||||
assert await page.evaluate("window.clicked") == 0
|
||||
assert await 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
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_with_noWaitAfter(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
async def _handler(button: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
if called == 1:
|
||||
await button.click()
|
||||
else:
|
||||
await page.locator("#interstitial").wait_for(state="hidden")
|
||||
|
||||
await page.add_locator_handler(
|
||||
page.get_by_role("button", name="close"), _handler, no_wait_after=True
|
||||
)
|
||||
await page.locator("#aside").hover()
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('timeout', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
await page.locator("#target").click()
|
||||
assert await page.evaluate("window.clicked") == 1
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
assert called == 2
|
||||
|
||||
|
||||
async def test_should_removeLocatorHandler(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/input/handle-locator.html")
|
||||
called = 0
|
||||
|
||||
async def _handler(locator: Locator) -> None:
|
||||
nonlocal called
|
||||
called += 1
|
||||
await locator.click()
|
||||
|
||||
await page.add_locator_handler(page.get_by_role("button", name="close"), _handler)
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
await page.locator("#target").click()
|
||||
assert called == 1
|
||||
assert await page.evaluate("window.clicked") == 1
|
||||
await expect(page.locator("#interstitial")).not_to_be_visible()
|
||||
await page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
window.clicked = 0;
|
||||
window.setupAnnoyingInterstitial('hide', 1);
|
||||
}
|
||||
"""
|
||||
)
|
||||
await page.remove_locator_handler(page.get_by_role("button", name="close"))
|
||||
with pytest.raises(Error) as error:
|
||||
await page.locator("#target").click(timeout=3000)
|
||||
assert called == 1
|
||||
assert await page.evaluate("window.clicked") == 0
|
||||
await expect(page.locator("#interstitial")).to_be_visible()
|
||||
assert "Timeout 3000ms exceeded" in error.value.message
|
||||
@@ -0,0 +1,277 @@
|
||||
# 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.async_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()]
|
||||
)
|
||||
|
||||
|
||||
async def check_and_match_snapshot(locator: Locator, snapshot: str) -> None:
|
||||
assert await locator.aria_snapshot() == _unshift(snapshot)
|
||||
await expect(locator).to_match_aria_snapshot(snapshot, timeout=1000)
|
||||
|
||||
|
||||
async def test_should_snapshot(page: Page) -> None:
|
||||
await page.set_content("<h1>title</h1>")
|
||||
await check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_list(page: Page) -> None:
|
||||
await page.set_content("<h1>title</h1><h1>title 2</h1>")
|
||||
await check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
- heading "title 2" [level=1]
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_list_with_list(page: Page) -> None:
|
||||
await page.set_content("<ul><li>one</li><li>two</li></ul>")
|
||||
await check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list:
|
||||
- listitem: one
|
||||
- listitem: two
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_list_with_accessible_name(page: Page) -> None:
|
||||
await page.set_content('<ul aria-label="my list"><li>one</li><li>two</li></ul>')
|
||||
await check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list "my list":
|
||||
- listitem: one
|
||||
- listitem: two
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_complex(page: Page) -> None:
|
||||
await page.set_content('<ul><li><a href="about:blank">link</a></li></ul>')
|
||||
await check_and_match_snapshot(
|
||||
page.locator("body"),
|
||||
"""
|
||||
- list:
|
||||
- listitem:
|
||||
- link "link":
|
||||
- /url: about:blank
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_with_unexpected_children_equal(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>One</li>
|
||||
<li>Two</li>
|
||||
<li>Three</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- listitem: One
|
||||
- listitem: Three
|
||||
""",
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: equal
|
||||
- listitem: One
|
||||
- listitem: Three
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_with_unexpected_children_deep_equal(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>
|
||||
<ul>
|
||||
<li>1.1</li>
|
||||
<li>1.2</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_with_restored_contain_mode_inside_deep_equal(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<ul>
|
||||
<li>
|
||||
<ul>
|
||||
<li>1.1</li>
|
||||
<li>1.2</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- listitem: 1.1
|
||||
""",
|
||||
timeout=1000,
|
||||
)
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- list:
|
||||
- /children: deep-equal
|
||||
- listitem:
|
||||
- list:
|
||||
- /children: contain
|
||||
- listitem: 1.1
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_match_values_both_against_regex_and_string(page: Page) -> None:
|
||||
await page.set_content('<a href="/auth?r=/">Log in</a>')
|
||||
await expect(page.locator("body")).to_match_aria_snapshot(
|
||||
"""
|
||||
- link "Log in":
|
||||
- /url: /auth?r=/
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_snapshot_with_depth(page: Page) -> None:
|
||||
await page.set_content("<ul><li><a href=about:blank>link</a></li></ul>")
|
||||
snapshot = await page.locator("body").aria_snapshot(depth=1)
|
||||
assert "listitem" in snapshot
|
||||
assert "/url" not in snapshot
|
||||
|
||||
|
||||
async def test_page_aria_snapshot_should_work(page: Page) -> None:
|
||||
await page.set_content("<h1>title</h1>")
|
||||
snapshot = await page.aria_snapshot()
|
||||
assert _unshift(snapshot) == _unshift(
|
||||
"""
|
||||
- heading "title" [level=1]
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def test_to_match_aria_snapshot_should_match_page(page: Page) -> None:
|
||||
# Ported from upstream tests/page/to-match-aria-snapshot.spec.ts.
|
||||
await page.set_content("<h1>title</h1>")
|
||||
await expect(page).to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "title"
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def test_to_match_aria_snapshot_should_match_page_complex(page: Page) -> None:
|
||||
# Ported from upstream tests/page/to-match-aria-snapshot.spec.ts.
|
||||
await 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>
|
||||
"""
|
||||
)
|
||||
await expect(page).to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "Microsoft"
|
||||
- text: Open source projects and samples from Microsoft
|
||||
- list:
|
||||
- listitem:
|
||||
- link "Playwright"
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def test_to_match_aria_snapshot_should_match_page_with_not(page: Page) -> None:
|
||||
# Ported from upstream tests/page/to-match-aria-snapshot.spec.ts.
|
||||
await page.set_content("<h1>title</h1>")
|
||||
await expect(page).not_to_match_aria_snapshot(
|
||||
"""
|
||||
- heading "wrong"
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,118 @@
|
||||
# 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 Dict
|
||||
|
||||
from playwright.async_api import Browser, BrowserType
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_should_construct_a_new_url_when_a_base_url_in_browser_new_context_is_passed(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(base_url=server.PREFIX)
|
||||
page = await context.new_page()
|
||||
assert (must(await page.goto("/empty.html"))).url == server.EMPTY_PAGE
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_construct_a_new_url_when_a_base_url_in_browser_new_page_is_passed(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(base_url=server.PREFIX)
|
||||
assert (must(await page.goto("/empty.html"))).url == server.EMPTY_PAGE
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_construct_a_new_url_when_a_base_url_in_browser_new_persistent_context_is_passed(
|
||||
browser_type: BrowserType, tmp_path: Path, server: Server, launch_arguments: Dict
|
||||
) -> None:
|
||||
context = await browser_type.launch_persistent_context(
|
||||
tmp_path, **launch_arguments, base_url=server.PREFIX
|
||||
)
|
||||
page = await context.new_page()
|
||||
assert (must(await page.goto("/empty.html"))).url == server.EMPTY_PAGE
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_construct_correctly_when_a_baseurl_without_a_trailing_slash_is_passed(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(base_url=server.PREFIX + "/url-construction")
|
||||
assert (must(await page.goto("mypage.html"))).url == server.PREFIX + "/mypage.html"
|
||||
assert (
|
||||
must(await page.goto("./mypage.html"))
|
||||
).url == server.PREFIX + "/mypage.html"
|
||||
assert (must(await page.goto("/mypage.html"))).url == server.PREFIX + "/mypage.html"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_construct_correctly_when_a_baseurl_with_a_trailing_slash_is_passed(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(base_url=server.PREFIX + "/url-construction/")
|
||||
assert (
|
||||
must(await page.goto("mypage.html"))
|
||||
).url == server.PREFIX + "/url-construction/mypage.html"
|
||||
assert (
|
||||
must(await page.goto("./mypage.html"))
|
||||
).url == server.PREFIX + "/url-construction/mypage.html"
|
||||
assert (must(await page.goto("/mypage.html"))).url == server.PREFIX + "/mypage.html"
|
||||
assert (must(await page.goto("."))).url == server.PREFIX + "/url-construction/"
|
||||
assert (must(await page.goto("/"))).url == server.PREFIX + "/"
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_not_construct_a_new_url_when_valid_urls_are_passed(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(base_url="http://microsoft.com")
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.url == server.EMPTY_PAGE
|
||||
|
||||
await page.goto("data:text/html,Hello world")
|
||||
assert page.url == "data:text/html,Hello world"
|
||||
|
||||
await page.goto("about:blank")
|
||||
assert page.url == "about:blank"
|
||||
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_should_be_able_to_match_a_url_relative_to_its_given_url_with_urlmatcher(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(base_url=server.PREFIX + "/foobar/")
|
||||
|
||||
await page.goto("/kek/index.html")
|
||||
await page.wait_for_url("/kek/index.html")
|
||||
assert page.url == server.PREFIX + "/kek/index.html"
|
||||
|
||||
await page.route(
|
||||
"./kek/index.html", lambda route: route.fulfill(body="base-url-matched-route")
|
||||
)
|
||||
|
||||
async with page.expect_request("./kek/index.html") as request_info:
|
||||
async with page.expect_response("./kek/index.html") as response_info:
|
||||
await page.goto("./kek/index.html")
|
||||
request = await request_info.value
|
||||
response = await response_info.value
|
||||
assert request.url == server.PREFIX + "/foobar/kek/index.html"
|
||||
assert response.url == server.PREFIX + "/foobar/kek/index.html"
|
||||
assert await response.body() == b"base-url-matched-route"
|
||||
|
||||
await page.close()
|
||||
@@ -0,0 +1,487 @@
|
||||
# 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
|
||||
import datetime
|
||||
from typing import Any, AsyncGenerator, List
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def calls(page: Page) -> List[Any]:
|
||||
calls: List[Any] = []
|
||||
await page.expose_function("stub", lambda *args: calls.append(list(args)))
|
||||
return calls
|
||||
|
||||
|
||||
class TestRunFor:
|
||||
@pytest.fixture(autouse=True)
|
||||
async def before_each(self, page: Page) -> AsyncGenerator[None, None]:
|
||||
await page.clock.install(time=0)
|
||||
await page.clock.pause_at(1000)
|
||||
yield
|
||||
|
||||
async def test_run_for_triggers_immediately_without_specified_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(window.stub)")
|
||||
await page.clock.run_for(0)
|
||||
assert len(calls) == 1
|
||||
|
||||
async def test_run_for_does_not_trigger_without_sufficient_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(window.stub, 100)")
|
||||
await page.clock.run_for(10)
|
||||
assert len(calls) == 0
|
||||
|
||||
async def test_run_for_triggers_after_sufficient_delay(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(window.stub, 100)")
|
||||
await page.clock.run_for(100)
|
||||
assert len(calls) == 1
|
||||
|
||||
async def test_run_for_triggers_simultaneous_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"setTimeout(window.stub, 100); setTimeout(window.stub, 100)"
|
||||
)
|
||||
await page.clock.run_for(100)
|
||||
assert len(calls) == 2
|
||||
|
||||
async def test_run_for_triggers_multiple_simultaneous_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"setTimeout(window.stub, 100); setTimeout(window.stub, 100); setTimeout(window.stub, 99); setTimeout(window.stub, 100)"
|
||||
)
|
||||
await page.clock.run_for(100)
|
||||
assert len(calls) == 4
|
||||
|
||||
async def test_run_for_waits_after_setTimeout_was_called(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(window.stub, 150)")
|
||||
await page.clock.run_for(50)
|
||||
assert len(calls) == 0
|
||||
await page.clock.run_for(100)
|
||||
assert len(calls) == 1
|
||||
|
||||
async def test_run_for_triggers_event_when_some_throw(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"setTimeout(() => { throw new Error(); }, 100); setTimeout(window.stub, 120)"
|
||||
)
|
||||
with pytest.raises(Error):
|
||||
await page.clock.run_for(120)
|
||||
assert len(calls) == 1
|
||||
|
||||
async def test_run_for_creates_updated_Date_while_ticking(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.clock.set_system_time(0)
|
||||
await page.evaluate(
|
||||
"setInterval(() => { window.stub(new Date().getTime()); }, 10)"
|
||||
)
|
||||
await page.clock.run_for(100)
|
||||
assert calls == [
|
||||
[10],
|
||||
[20],
|
||||
[30],
|
||||
[40],
|
||||
[50],
|
||||
[60],
|
||||
[70],
|
||||
[80],
|
||||
[90],
|
||||
[100],
|
||||
]
|
||||
|
||||
async def test_run_for_passes_8_seconds(self, page: Page, calls: List[Any]) -> None:
|
||||
await page.evaluate("setInterval(window.stub, 4000)")
|
||||
await page.clock.run_for("08")
|
||||
assert len(calls) == 2
|
||||
|
||||
async def test_run_for_passes_1_minute(self, page: Page, calls: List[Any]) -> None:
|
||||
await page.evaluate("setInterval(window.stub, 6000)")
|
||||
await page.clock.run_for("01:00")
|
||||
assert len(calls) == 10
|
||||
|
||||
async def test_run_for_passes_2_hours_34_minutes_and_10_seconds(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setInterval(window.stub, 10000)")
|
||||
await page.clock.run_for("02:34:10")
|
||||
assert len(calls) == 925
|
||||
|
||||
async def test_run_for_throws_for_invalid_format(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setInterval(window.stub, 10000)")
|
||||
with pytest.raises(Error):
|
||||
await page.clock.run_for("12:02:34:10")
|
||||
assert len(calls) == 0
|
||||
|
||||
async def test_run_for_returns_the_current_now_value(self, page: Page) -> None:
|
||||
await page.clock.set_system_time(0)
|
||||
value = 200
|
||||
await page.clock.run_for(value)
|
||||
assert await page.evaluate("Date.now()") == value
|
||||
|
||||
|
||||
class TestFastForward:
|
||||
@pytest.fixture(autouse=True)
|
||||
async def before_each(self, page: Page) -> AsyncGenerator[None, None]:
|
||||
await page.clock.install(time=0)
|
||||
await page.clock.pause_at(1)
|
||||
yield
|
||||
|
||||
async def test_ignores_timers_which_wouldnt_be_run(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"setTimeout(() => { window.stub('should not be logged'); }, 1000)"
|
||||
)
|
||||
await page.clock.fast_forward(500)
|
||||
assert len(calls) == 0
|
||||
|
||||
async def test_pushes_back_execution_time_for_skipped_timers(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(() => { window.stub(Date.now()); }, 1000)")
|
||||
await page.clock.fast_forward(2000)
|
||||
assert calls == [[1000 + 2000]]
|
||||
|
||||
async def test_supports_string_time_arguments(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"setTimeout(() => { window.stub(Date.now()); }, 100000)"
|
||||
) # 100000 = 1:40
|
||||
await page.clock.fast_forward("01:50")
|
||||
assert calls == [[1000 + 110000]]
|
||||
|
||||
|
||||
class TestStubTimers:
|
||||
@pytest.fixture(autouse=True)
|
||||
async def before_each(self, page: Page) -> AsyncGenerator[None, None]:
|
||||
await page.clock.install(time=0)
|
||||
await page.clock.pause_at(1)
|
||||
yield
|
||||
|
||||
async def test_sets_initial_timestamp(self, page: Page) -> None:
|
||||
await page.clock.set_system_time(1.4)
|
||||
assert await page.evaluate("Date.now()") == 1400
|
||||
|
||||
async def test_replaces_global_setTimeout(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setTimeout(window.stub, 1000)")
|
||||
await page.clock.run_for(1000)
|
||||
assert len(calls) == 1
|
||||
|
||||
async def test_global_fake_setTimeout_should_return_id(self, page: Page) -> None:
|
||||
to = await page.evaluate("setTimeout(window.stub, 1000)")
|
||||
assert isinstance(to, int)
|
||||
|
||||
async def test_replaces_global_clearTimeout(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"""
|
||||
const to = setTimeout(window.stub, 1000);
|
||||
clearTimeout(to);
|
||||
"""
|
||||
)
|
||||
await page.clock.run_for(1000)
|
||||
assert len(calls) == 0
|
||||
|
||||
async def test_replaces_global_setInterval(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate("setInterval(window.stub, 500)")
|
||||
await page.clock.run_for(1000)
|
||||
assert len(calls) == 2
|
||||
|
||||
async def test_replaces_global_clearInterval(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.evaluate(
|
||||
"""
|
||||
const to = setInterval(window.stub, 500);
|
||||
clearInterval(to);
|
||||
"""
|
||||
)
|
||||
await page.clock.run_for(1000)
|
||||
assert len(calls) == 0
|
||||
|
||||
async def test_replaces_global_performance_now(self, page: Page) -> None:
|
||||
promise = asyncio.create_task(
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
const prev = performance.now();
|
||||
await new Promise(f => setTimeout(f, 1000));
|
||||
const next = performance.now();
|
||||
return { prev, next };
|
||||
}"""
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0) # Make sure the promise is scheduled.
|
||||
await page.clock.run_for(1000)
|
||||
assert await promise == {"prev": 1000, "next": 2000}
|
||||
|
||||
async def test_fakes_Date_constructor(self, page: Page) -> None:
|
||||
now = await page.evaluate("new Date().getTime()")
|
||||
assert now == 1000
|
||||
|
||||
|
||||
class TestStubTimersPerformance:
|
||||
async def test_replaces_global_performance_time_origin(self, page: Page) -> None:
|
||||
await page.clock.install(time=1)
|
||||
await page.clock.pause_at(2)
|
||||
promise = asyncio.create_task(
|
||||
page.evaluate(
|
||||
"""async () => {
|
||||
const prev = performance.now();
|
||||
await new Promise(f => setTimeout(f, 1000));
|
||||
const next = performance.now();
|
||||
return { prev, next };
|
||||
}"""
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0) # Make sure the promise is scheduled.
|
||||
await page.clock.run_for(1000)
|
||||
assert await page.evaluate("performance.timeOrigin") == 1000
|
||||
assert await promise == {"prev": 1000, "next": 2000}
|
||||
|
||||
|
||||
class TestPopup:
|
||||
async def test_should_tick_after_popup(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
now = datetime.datetime.fromisoformat("2015-09-25")
|
||||
await page.clock.pause_at(now)
|
||||
popup, _ = await asyncio.gather(
|
||||
page.wait_for_event("popup"), page.evaluate("window.open('about:blank')")
|
||||
)
|
||||
popup_time = await popup.evaluate("Date.now()")
|
||||
assert popup_time == now.timestamp() * 1000
|
||||
await page.clock.run_for(1000)
|
||||
popup_time_after = await popup.evaluate("Date.now()")
|
||||
assert popup_time_after == now.timestamp() * 1000 + 1000
|
||||
|
||||
async def test_should_tick_before_popup(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
now = datetime.datetime.fromisoformat("2015-09-25")
|
||||
await page.clock.pause_at(now)
|
||||
await page.clock.run_for(1000)
|
||||
popup, _ = await asyncio.gather(
|
||||
page.wait_for_event("popup"), page.evaluate("window.open('about:blank')")
|
||||
)
|
||||
popup_time = await popup.evaluate("Date.now()")
|
||||
assert popup_time == int(now.timestamp() * 1000 + 1000)
|
||||
assert datetime.datetime.fromtimestamp(popup_time / 1_000).year == 2015
|
||||
|
||||
async 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(),
|
||||
),
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
# Wait for 2 second in real life to check that it is past in popup.
|
||||
await page.wait_for_timeout(2000)
|
||||
popup, _ = await asyncio.gather(
|
||||
page.wait_for_event("popup"),
|
||||
page.evaluate("window.open('{}')".format(server.PREFIX + "/popup.html")),
|
||||
)
|
||||
popup_time = await popup.evaluate("window.time")
|
||||
assert popup_time >= 2000
|
||||
|
||||
async 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(),
|
||||
),
|
||||
)
|
||||
await page.clock.install(time=0)
|
||||
await page.clock.pause_at(1)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
# Wait for 2 second in real life to check that it is past in popup.
|
||||
await page.wait_for_timeout(2000)
|
||||
popup, _ = await asyncio.gather(
|
||||
page.wait_for_event("popup"),
|
||||
page.evaluate("window.open('{}')".format(server.PREFIX + "/popup.html")),
|
||||
)
|
||||
popup_time = await popup.evaluate("window.time")
|
||||
assert popup_time == 1000
|
||||
|
||||
|
||||
class TestSetFixedTime:
|
||||
async def test_does_not_fake_methods(self, page: Page) -> None:
|
||||
await page.clock.set_fixed_time(0)
|
||||
# Should not stall.
|
||||
await page.evaluate("new Promise(f => setTimeout(f, 1))")
|
||||
|
||||
async def test_allows_setting_time_multiple_times(self, page: Page) -> None:
|
||||
await page.clock.set_fixed_time(0.1)
|
||||
assert await page.evaluate("Date.now()") == 100
|
||||
await page.clock.set_fixed_time(0.2)
|
||||
assert await page.evaluate("Date.now()") == 200
|
||||
|
||||
async def test_fixed_time_is_not_affected_by_clock_manipulation(
|
||||
self, page: Page
|
||||
) -> None:
|
||||
await page.clock.set_fixed_time(0.1)
|
||||
assert await page.evaluate("Date.now()") == 100
|
||||
await page.clock.fast_forward(20)
|
||||
assert await page.evaluate("Date.now()") == 100
|
||||
|
||||
async def test_allows_installing_fake_timers_after_setting_time(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.clock.set_fixed_time(0.1)
|
||||
assert await page.evaluate("Date.now()") == 100
|
||||
await page.clock.set_fixed_time(0.2)
|
||||
await page.evaluate("setTimeout(() => window.stub(Date.now()))")
|
||||
await page.clock.run_for(0)
|
||||
assert calls == [[200]]
|
||||
|
||||
|
||||
class TestWhileRunning:
|
||||
async def test_should_progress_time(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.wait_for_timeout(1000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert 1000 <= now <= 2000
|
||||
|
||||
async def test_should_run_for(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.run_for(10000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
async def test_should_fast_forward(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.fast_forward(10000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
async def test_should_fast_forward_to(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.fast_forward(10000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert 10000 <= now <= 11000
|
||||
|
||||
async def test_should_pause(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1)
|
||||
await page.wait_for_timeout(1000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert 0 <= now <= 1000
|
||||
|
||||
async def test_should_pause_and_fast_forward(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1)
|
||||
await page.clock.fast_forward(1000)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert now == 2000
|
||||
|
||||
async def test_should_set_system_time_on_pause(self, page: Page) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1)
|
||||
now = await page.evaluate("Date.now()")
|
||||
assert now == 1000
|
||||
|
||||
|
||||
class TestWhileOnPause:
|
||||
async def test_fast_forward_should_not_run_nested_immediate(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1000)
|
||||
await page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
setTimeout(() => window.stub('inner'), 0);
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
await page.clock.fast_forward(1000)
|
||||
assert calls == [["outer"]]
|
||||
await page.clock.fast_forward(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
|
||||
async def test_run_for_should_not_run_nested_immediate(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1000)
|
||||
await page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
setTimeout(() => window.stub('inner'), 0);
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
await page.clock.run_for(1000)
|
||||
assert calls == [["outer"]]
|
||||
await page.clock.run_for(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
|
||||
async def test_run_for_should_not_run_nested_immediate_from_microtask(
|
||||
self, page: Page, calls: List[Any]
|
||||
) -> None:
|
||||
await page.clock.install(time=0)
|
||||
await page.goto("data:text/html,")
|
||||
await page.clock.pause_at(1000)
|
||||
await page.evaluate(
|
||||
"""
|
||||
setTimeout(() => {
|
||||
window.stub('outer');
|
||||
void Promise.resolve().then(() => setTimeout(() => window.stub('inner'), 0));
|
||||
}, 1000);
|
||||
"""
|
||||
)
|
||||
await page.clock.run_for(1000)
|
||||
assert calls == [["outer"]]
|
||||
await page.clock.run_for(1)
|
||||
assert calls == [["outer"], ["inner"]]
|
||||
@@ -0,0 +1,355 @@
|
||||
# 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 math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from urllib.parse import ParseResult, urlparse
|
||||
|
||||
from playwright.async_api import Error, Page
|
||||
|
||||
|
||||
async def test_evaluate_work(page: Page) -> None:
|
||||
result = await page.evaluate("7 * 3")
|
||||
assert result == 21
|
||||
|
||||
|
||||
async def test_evaluate_return_none_for_null(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", None)
|
||||
assert result is None
|
||||
|
||||
|
||||
async def test_evaluate_transfer_nan(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", float("nan"))
|
||||
assert math.isnan(result)
|
||||
|
||||
|
||||
async def test_evaluate_transfer_neg_zero(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", -0)
|
||||
assert result == float("-0")
|
||||
|
||||
|
||||
async def test_evaluate_transfer_infinity(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", float("Infinity"))
|
||||
assert result == float("Infinity")
|
||||
|
||||
|
||||
async def test_evaluate_transfer_neg_infinity(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", float("-Infinity"))
|
||||
assert result == float("-Infinity")
|
||||
|
||||
|
||||
async def test_evaluate_roundtrip_unserializable_values(page: Page) -> None:
|
||||
value = {
|
||||
"infinity": float("Infinity"),
|
||||
"nInfinity": float("-Infinity"),
|
||||
"nZero": float("-0"),
|
||||
}
|
||||
result = await page.evaluate("a => a", value)
|
||||
assert result == value
|
||||
|
||||
|
||||
async def test_evaluate_transfer_arrays(page: Page) -> None:
|
||||
result = await page.evaluate("a => a", [1, 2, 3])
|
||||
assert result == [1, 2, 3]
|
||||
|
||||
|
||||
async def test_evaluate_transfer_typed_arrays(page: Page) -> None:
|
||||
async def test_typed_array(
|
||||
typed_array: str, expected: list[float], value_suffix: Optional[str]
|
||||
) -> None:
|
||||
value_suffix = "" if value_suffix is None else value_suffix
|
||||
result = await page.evaluate(
|
||||
f"() => new {typed_array}([1{value_suffix}, 2{value_suffix}, 3{value_suffix}])"
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
await test_typed_array("Int8Array", [1, 2, 3], None)
|
||||
await test_typed_array("Uint8Array", [1, 2, 3], None)
|
||||
await test_typed_array("Uint8ClampedArray", [1, 2, 3], None)
|
||||
await test_typed_array("Int16Array", [1, 2, 3], None)
|
||||
await test_typed_array("Uint16Array", [1, 2, 3], None)
|
||||
await test_typed_array("Int32Array", [1, 2, 3], None)
|
||||
await test_typed_array("Uint32Array", [1, 2, 3], None)
|
||||
await test_typed_array("Float32Array", [1.5, 2.5, 3.5], ".5")
|
||||
await test_typed_array("Float64Array", [1.5, 2.5, 3.5], ".5")
|
||||
await test_typed_array("BigInt64Array", [1, 2, 3], "n")
|
||||
await test_typed_array("BigUint64Array", [1, 2, 3], "n")
|
||||
|
||||
|
||||
async def test_evaluate_transfer_bigint(page: Page) -> None:
|
||||
assert await page.evaluate("() => 42n") == 42
|
||||
assert await page.evaluate("a => a", 17) == 17
|
||||
|
||||
|
||||
async def test_evaluate_return_undefined_for_objects_with_symbols(page: Page) -> None:
|
||||
assert await page.evaluate('[Symbol("foo4")]') == [None]
|
||||
assert (
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
const a = { };
|
||||
a[Symbol('foo4')] = 42;
|
||||
return a;
|
||||
}"""
|
||||
)
|
||||
== {}
|
||||
)
|
||||
assert (
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
return { foo: [{ a: Symbol('foo4') }] };
|
||||
}"""
|
||||
)
|
||||
== {"foo": [{"a": None}]}
|
||||
)
|
||||
|
||||
|
||||
async def test_evaluate_work_with_unicode_chars(page: Page) -> None:
|
||||
result = await page.evaluate('a => a["中文字符"]', {"中文字符": 42})
|
||||
assert result == 42
|
||||
|
||||
|
||||
async def test_evaluate_throw_when_evaluation_triggers_reload(page: Page) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.evaluate(
|
||||
"() => { location.reload(); return new Promise(() => {}); }"
|
||||
)
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "navigation" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_work_with_exposed_function(page: Page) -> None:
|
||||
await page.expose_function("callController", lambda a, b: a * b)
|
||||
result = await page.evaluate("callController(9, 3)")
|
||||
assert result == 27
|
||||
|
||||
|
||||
async def test_evaluate_reject_promise_with_exception(page: Page) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.evaluate("not_existing_object.property")
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "not_existing_object" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_support_thrown_strings(page: Page) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.evaluate('throw "qwerty"')
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "qwerty" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_support_thrown_numbers(page: Page) -> None:
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.evaluate("throw 100500")
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "100500" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_return_complex_objects(page: Page) -> None:
|
||||
obj = {"foo": "bar!"}
|
||||
result = await page.evaluate("a => a", obj)
|
||||
assert result == obj
|
||||
|
||||
|
||||
async def test_evaluate_accept_none_as_one_of_multiple_parameters(page: Page) -> None:
|
||||
result = await page.evaluate(
|
||||
'({ a, b }) => Object.is(a, null) && Object.is(b, "foo")',
|
||||
{"a": None, "b": "foo"},
|
||||
)
|
||||
assert result
|
||||
|
||||
|
||||
async def test_evaluate_properly_serialize_none_arguments(page: Page) -> None:
|
||||
assert await page.evaluate("x => ({a: x})", None) == {"a": None}
|
||||
|
||||
|
||||
async def test_should_alias_window_document_and_node(page: Page) -> None:
|
||||
object = await page.evaluate("[window, document, document.body]")
|
||||
assert object == ["ref: <Window>", "ref: <Document>", "ref: <Node>"]
|
||||
|
||||
|
||||
async def test_evaluate_should_work_for_circular_object(page: Page) -> None:
|
||||
a = await page.evaluate(
|
||||
"""() => {
|
||||
const a = {x: 47};
|
||||
const b = {a};
|
||||
a.b = b;
|
||||
return a;
|
||||
}"""
|
||||
)
|
||||
|
||||
assert a["b"]["a"]["b"]["a"]["x"] == 47
|
||||
assert a["b"]["a"] == a
|
||||
|
||||
|
||||
async def test_evaluate_accept_string(page: Page) -> None:
|
||||
assert await page.evaluate("1 + 2") == 3
|
||||
|
||||
|
||||
async def test_evaluate_accept_element_handle_as_an_argument(page: Page) -> None:
|
||||
await page.set_content("<section>42</section>")
|
||||
element = await page.query_selector("section")
|
||||
text = await page.evaluate("e => e.textContent", element)
|
||||
assert text == "42"
|
||||
|
||||
|
||||
async def test_evaluate_throw_if_underlying_element_was_disposed(page: Page) -> None:
|
||||
await page.set_content("<section>39</section>")
|
||||
element = await page.query_selector("section")
|
||||
assert element
|
||||
await element.dispose()
|
||||
error: Optional[Error] = None
|
||||
try:
|
||||
await page.evaluate("e => e.textContent", element)
|
||||
except Error as e:
|
||||
error = e
|
||||
assert error
|
||||
assert "no object with guid" in error.message
|
||||
|
||||
|
||||
async def test_evaluate_evaluate_exception(page: Page) -> None:
|
||||
error = await page.evaluate(
|
||||
"""() => {
|
||||
function innerFunction() {
|
||||
const e = new Error('error message');
|
||||
e.name = 'foobar';
|
||||
return e;
|
||||
}
|
||||
return innerFunction();
|
||||
}"""
|
||||
)
|
||||
assert isinstance(error, Error)
|
||||
assert error.message == "error message"
|
||||
assert error.name == "foobar"
|
||||
assert error.stack
|
||||
assert "innerFunction" in error.stack
|
||||
|
||||
|
||||
async def test_should_pass_exception_argument(page: Page) -> None:
|
||||
def _raise_and_get_exception(exception: Exception) -> Exception:
|
||||
try:
|
||||
raise exception
|
||||
except Exception as e:
|
||||
return e
|
||||
|
||||
error_for_roundtrip = Error("error message")
|
||||
error_for_roundtrip._name = "foobar"
|
||||
error_for_roundtrip._stack = "test stack"
|
||||
error = await page.evaluate(
|
||||
"""e => {
|
||||
return { message: e.message, name: e.name, stack: e.stack };
|
||||
}""",
|
||||
error_for_roundtrip,
|
||||
)
|
||||
assert error["message"] == "error message"
|
||||
assert error["name"] == "foobar"
|
||||
assert "test stack" in error["stack"]
|
||||
|
||||
error = await page.evaluate(
|
||||
"""e => {
|
||||
return { message: e.message, name: e.name, stack: e.stack };
|
||||
}""",
|
||||
_raise_and_get_exception(Exception("error message")),
|
||||
)
|
||||
assert error["message"] == "error message"
|
||||
assert error["name"] == "Exception"
|
||||
assert "error message" in error["stack"]
|
||||
|
||||
|
||||
async def test_evaluate_evaluate_date(page: Page) -> None:
|
||||
result = await page.evaluate(
|
||||
'() => ({ date: new Date("2020-05-27T01:31:38.506Z") })'
|
||||
)
|
||||
assert result == {
|
||||
"date": datetime.fromisoformat("2020-05-27T01:31:38.506").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
async def test_evaluate_roundtrip_date_without_tzinfo(page: Page) -> None:
|
||||
date = datetime.fromisoformat("2020-05-27T01:31:38.506")
|
||||
result = await page.evaluate("date => date", date)
|
||||
assert result.timestamp() == date.timestamp()
|
||||
|
||||
|
||||
async def test_evaluate_roundtrip_date(page: Page) -> None:
|
||||
date = datetime.fromisoformat("2020-05-27T01:31:38.506").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
result = await page.evaluate("date => date", date)
|
||||
assert result == date
|
||||
|
||||
|
||||
async def test_evaluate_roundtrip_date_with_tzinfo(page: Page) -> None:
|
||||
date = datetime.fromisoformat("2020-05-27T01:31:38.506")
|
||||
date = date.astimezone(timezone(timedelta(hours=4)))
|
||||
result = await page.evaluate("date => date", date)
|
||||
assert result == date
|
||||
|
||||
|
||||
async def test_evaluate_jsonvalue_date(page: Page) -> None:
|
||||
date = datetime.fromisoformat("2020-05-27T01:31:38.506").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
result = await page.evaluate(
|
||||
'() => ({ date: new Date("2020-05-27T01:31:38.506Z") })'
|
||||
)
|
||||
assert result == {"date": date}
|
||||
|
||||
|
||||
async def test_should_evaluate_url(page: Page) -> None:
|
||||
out = await page.evaluate(
|
||||
"() => ({ someKey: new URL('https://user:pass@example.com/?foo=bar#hi') })"
|
||||
)
|
||||
assert out["someKey"] == ParseResult(
|
||||
scheme="https",
|
||||
netloc="user:pass@example.com",
|
||||
path="/",
|
||||
query="foo=bar",
|
||||
params="",
|
||||
fragment="hi",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_roundtrip_url(page: Page) -> None:
|
||||
in_ = urlparse("https://user:pass@example.com/?foo=bar#hi")
|
||||
out = await page.evaluate("url => url", in_)
|
||||
assert in_ == out
|
||||
|
||||
|
||||
async def test_should_roundtrip_complex_url(page: Page) -> None:
|
||||
in_ = urlparse(
|
||||
"https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName"
|
||||
)
|
||||
out = await page.evaluate("url => url", in_)
|
||||
assert in_ == out
|
||||
|
||||
|
||||
async def test_evaluate_jsonvalue_url(page: Page) -> None:
|
||||
url = urlparse("https://example.com/")
|
||||
result = await page.evaluate('() => ({ someKey: new URL("https://example.com/") })')
|
||||
assert result == {"someKey": url}
|
||||
@@ -0,0 +1,65 @@
|
||||
# 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.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_console_messages_should_work(page: Page) -> None:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
for (let i = 0; i < 301; i++)
|
||||
console.log('message' + i);
|
||||
}"""
|
||||
)
|
||||
|
||||
messages = await 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"
|
||||
|
||||
|
||||
async def test_should_have_a_timestamp(page: Page) -> None:
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate("() => console.log('hello')")
|
||||
message = await message_info.value
|
||||
assert message.timestamp > 0
|
||||
|
||||
|
||||
async def test_clear_console_messages_should_drop_buffered_messages(page: Page) -> None:
|
||||
await page.evaluate("() => console.log('first')")
|
||||
assert any(m.text == "first" for m in await page.console_messages())
|
||||
await page.clear_console_messages()
|
||||
assert not any(m.text == "first" for m in await page.console_messages())
|
||||
await page.evaluate("() => console.log('second')")
|
||||
assert any(m.text == "second" for m in await page.console_messages())
|
||||
|
||||
|
||||
async def test_console_messages_filter_since_navigation_drops_pre_nav_messages(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate("() => console.log('before-nav')")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate("() => console.log('after-nav')")
|
||||
after = await page.console_messages(filter="since-navigation")
|
||||
texts = [m.text for m in after]
|
||||
assert "after-nav" in texts
|
||||
assert "before-nav" not in texts
|
||||
@@ -0,0 +1,60 @@
|
||||
# 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.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_page_errors_should_work(page: Page) -> None:
|
||||
await 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 = await 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"
|
||||
|
||||
|
||||
async def test_clear_page_errors_should_drop_buffered_errors(page: Page) -> None:
|
||||
await page.evaluate("() => setTimeout(() => { throw new Error('first'); }, 0)")
|
||||
await page.evaluate("() => new Promise(r => setTimeout(r, 50))")
|
||||
assert any(e.message == "first" for e in await page.page_errors())
|
||||
await page.clear_page_errors()
|
||||
assert not any(e.message == "first" for e in await page.page_errors())
|
||||
|
||||
|
||||
async def test_page_errors_filter_since_navigation_drops_pre_nav_errors(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate("() => setTimeout(() => { throw new Error('before-nav'); }, 0)")
|
||||
await page.evaluate("() => new Promise(r => setTimeout(r, 50))")
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate("() => setTimeout(() => { throw new Error('after-nav'); }, 0)")
|
||||
await page.evaluate("() => new Promise(r => setTimeout(r, 50))")
|
||||
after = await page.page_errors(filter="since-navigation")
|
||||
messages = [e.message for e in after]
|
||||
assert "after-nav" in messages
|
||||
assert "before-nav" not in messages
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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 playwright._impl._network import Request, Route
|
||||
from playwright._impl._page import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_return_last_requests(page: Page, server: Server) -> None:
|
||||
await page.goto(server.PREFIX + "/title.html")
|
||||
for i in range(200):
|
||||
|
||||
def _handle_route(route: Route) -> None:
|
||||
asyncio.ensure_future(
|
||||
route.fulfill(
|
||||
status=200,
|
||||
body=f"url:{route.request.url}",
|
||||
)
|
||||
)
|
||||
|
||||
await page.route(f"**/fetch?{i}", _handle_route)
|
||||
|
||||
# #0 is the navigation request, so start with #1.
|
||||
for i in range(1, 100):
|
||||
await page.evaluate("url => fetch(url)", server.PREFIX + f"/fetch?{i}")
|
||||
first_100_requests_with_goto = await page.requests()
|
||||
first_100_requests = first_100_requests_with_goto[1:]
|
||||
|
||||
for i in range(100, 200):
|
||||
await page.evaluate("url => fetch(url)", server.PREFIX + f"/fetch?{i}")
|
||||
last_100_requests = await page.requests()
|
||||
|
||||
all_requests = first_100_requests + last_100_requests
|
||||
|
||||
async def gather_response(request: Request) -> dict:
|
||||
response = await request.response()
|
||||
assert response
|
||||
return {"text": await response.text(), "url": request.url}
|
||||
|
||||
# All 199 requests are fully functional.
|
||||
received = await asyncio.gather(
|
||||
*[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,84 @@
|
||||
# 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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page, Request
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_not_allow_to_access_frame_on_popup_main_request(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content(f'<a target=_blank href="{server.EMPTY_PAGE}">click me</a>')
|
||||
request_promise = asyncio.ensure_future(page.context.wait_for_event("request"))
|
||||
popup_promise = asyncio.ensure_future(page.context.wait_for_event("page"))
|
||||
clicked = asyncio.ensure_future(page.get_by_text("click me").click())
|
||||
request: Request = await request_promise
|
||||
|
||||
assert request.is_navigation_request()
|
||||
|
||||
with pytest.raises(Error) as exc_info:
|
||||
request.frame
|
||||
assert (
|
||||
"Frame for this navigation request is not available" in exc_info.value.message
|
||||
)
|
||||
|
||||
response = await request.response()
|
||||
assert response
|
||||
await response.finished()
|
||||
await popup_promise
|
||||
await clicked
|
||||
|
||||
|
||||
async def test_should_parse_the_data_if_content_type_is_application_x_www_form_urlencoded_charset_UTF_8(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_event("request") as request_info:
|
||||
await page.evaluate(
|
||||
"""() => fetch('./post', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
},
|
||||
body: 'foo=bar&baz=123'
|
||||
})"""
|
||||
)
|
||||
request = await request_info.value
|
||||
assert request
|
||||
assert request.post_data_json == {"foo": "bar", "baz": "123"}
|
||||
|
||||
|
||||
async def test_existing_response_should_return_response_after_it_is_received(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
async with page.expect_event("requestfinished") as request_finished_info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
request = await request_finished_info.value
|
||||
assert request.existing_response is not None
|
||||
assert request.existing_response.status == 200
|
||||
|
||||
|
||||
async def test_existing_response_should_return_none_before_response_arrives(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
captured = []
|
||||
page.on("request", lambda req: captured.append(req.existing_response))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert captured
|
||||
# When the "request" event fires, the response has not been received yet.
|
||||
assert captured[0] is None
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
async def test_should_reject_response_finished_if_page_closes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
def handle_get(request: TestServerRequest) -> 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
|
||||
[page_response, _] = await asyncio.gather(
|
||||
page.wait_for_event("response"),
|
||||
page.evaluate("() => fetch('./get', { method: 'GET' })"),
|
||||
)
|
||||
|
||||
finish_coroutine = page_response.finished()
|
||||
await page.close()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await finish_coroutine
|
||||
error = exc_info.value
|
||||
assert "closed" in error.message
|
||||
|
||||
|
||||
async def test_should_reject_response_finished_if_context_closes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
def handle_get(request: TestServerRequest) -> 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
|
||||
[page_response, _] = await asyncio.gather(
|
||||
page.wait_for_event("response"),
|
||||
page.evaluate("() => fetch('./get', { method: 'GET' })"),
|
||||
)
|
||||
|
||||
finish_coroutine = page_response.finished()
|
||||
await page.context.close()
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await finish_coroutine
|
||||
error = exc_info.value
|
||||
assert "closed" in error.message
|
||||
|
||||
|
||||
async def test_should_return_http_version(page: Page, server: Server) -> None:
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
http_version = await response.http_version()
|
||||
assert http_version in ("HTTP/1.0", "HTTP/1.1", "HTTP/2.0")
|
||||
@@ -0,0 +1,368 @@
|
||||
# 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 typing import Any, Callable, Coroutine, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page, Request, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server) -> None:
|
||||
await page.route("**/*", lambda route: asyncio.create_task(route.fallback()))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_fall_back(page: Page, server: Server) -> None:
|
||||
intercepted = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler1)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
intercepted.append(2)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler2)
|
||||
|
||||
def _handler3(route: Route) -> None:
|
||||
intercepted.append(3)
|
||||
asyncio.create_task(route.fallback())
|
||||
|
||||
await page.route("**/empty.html", _handler3)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_fall_back_async_delayed(page: Page, server: Server) -> None:
|
||||
intercepted = []
|
||||
|
||||
def create_handler(i: int) -> Callable[[Route], Coroutine]:
|
||||
async def handler(route: Route) -> None:
|
||||
intercepted.append(i)
|
||||
await asyncio.sleep(0.1)
|
||||
await route.fallback()
|
||||
|
||||
return handler
|
||||
|
||||
await page.route("**/empty.html", create_handler(1))
|
||||
await page.route("**/empty.html", create_handler(2))
|
||||
await page.route("**/empty.html", create_handler(3))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_chain_once(page: Page, server: Server) -> None:
|
||||
await page.route(
|
||||
"**/madeup.txt",
|
||||
lambda route: asyncio.create_task(
|
||||
route.fulfill(status=200, body="fulfilled one")
|
||||
),
|
||||
times=1,
|
||||
)
|
||||
await page.route(
|
||||
"**/madeup.txt", lambda route: asyncio.create_task(route.fallback()), times=1
|
||||
)
|
||||
|
||||
resp = await page.goto(server.PREFIX + "/madeup.txt")
|
||||
assert resp
|
||||
body = await resp.body()
|
||||
assert body == b"fulfilled one"
|
||||
|
||||
|
||||
async def test_should_not_chain_fulfill(page: Page, server: Server) -> None:
|
||||
failed = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
await page.route("**/empty.html", handler)
|
||||
await page.route(
|
||||
"**/empty.html",
|
||||
lambda route: asyncio.create_task(route.fulfill(status=200, body="fulfilled")),
|
||||
)
|
||||
await page.route(
|
||||
"**/empty.html", lambda route: asyncio.create_task(route.fallback())
|
||||
)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
body = await response.body()
|
||||
assert body == b"fulfilled"
|
||||
assert not failed[0]
|
||||
|
||||
|
||||
async def test_should_not_chain_abort(
|
||||
page: Page, server: Server, is_webkit: bool, is_firefox: bool
|
||||
) -> None:
|
||||
failed = [False]
|
||||
|
||||
def handler(route: Route) -> None:
|
||||
failed[0] = True
|
||||
|
||||
await page.route("**/empty.html", handler)
|
||||
await page.route("**/empty.html", lambda route: asyncio.create_task(route.abort()))
|
||||
await page.route(
|
||||
"**/empty.html", lambda route: asyncio.create_task(route.fallback())
|
||||
)
|
||||
|
||||
with pytest.raises(Error) as excinfo:
|
||||
await 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]
|
||||
|
||||
|
||||
async def test_should_fall_back_after_exception(page: Page, server: Server) -> None:
|
||||
await page.route("**/empty.html", lambda route: route.continue_())
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
try:
|
||||
await route.fulfill(response=cast(Any, {}))
|
||||
except Exception:
|
||||
await route.fallback()
|
||||
|
||||
await page.route("**/empty.html", handler)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_should_amend_http_headers(page: Page, server: Server) -> None:
|
||||
values = []
|
||||
|
||||
async def handler(route: Route) -> None:
|
||||
values.append(route.request.headers.get("foo"))
|
||||
values.append(await route.request.header_value("FOO"))
|
||||
await route.continue_()
|
||||
|
||||
await page.route("**/sleep.zzz", handler)
|
||||
|
||||
async def handler_with_header_mods(route: Route) -> None:
|
||||
await route.fallback(headers={**route.request.headers, "FOO": "bar"})
|
||||
|
||||
await page.route("**/*", handler_with_header_mods)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
with server.expect_request("/sleep.zzz") as server_request_info:
|
||||
await page.evaluate("() => fetch('/sleep.zzz')")
|
||||
values.append(server_request_info.value.getHeader("foo"))
|
||||
assert values == ["bar", "bar", "bar"]
|
||||
|
||||
|
||||
async def test_should_delete_header_with_undefined_value(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await 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 = []
|
||||
|
||||
async def capture_and_continue(route: Route, request: Request) -> None:
|
||||
intercepted_request.append(request)
|
||||
await route.continue_()
|
||||
|
||||
await page.route("**/*", capture_and_continue)
|
||||
|
||||
async def delete_foo_header(route: Route, request: Request) -> None:
|
||||
headers = await request.all_headers()
|
||||
del headers["foo"]
|
||||
await route.fallback(headers=headers)
|
||||
|
||||
await page.route(server.PREFIX + "/something", delete_foo_header)
|
||||
|
||||
[server_req, text] = await asyncio.gather(
|
||||
server.wait_for_request("/something"),
|
||||
page.evaluate(
|
||||
"""
|
||||
async url => {
|
||||
const data = await fetch(url, {
|
||||
headers: {
|
||||
foo: 'a',
|
||||
bar: 'b',
|
||||
}
|
||||
});
|
||||
return data.text();
|
||||
}
|
||||
""",
|
||||
server.PREFIX + "/something",
|
||||
),
|
||||
)
|
||||
|
||||
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"
|
||||
|
||||
|
||||
async def test_should_amend_method(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
method = []
|
||||
|
||||
def _handler(route: Route) -> None:
|
||||
method.append(route.request.method)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await page.route("**/*", _handler)
|
||||
await page.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fallback(method="POST"))
|
||||
)
|
||||
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("() => fetch('/sleep.zzz')"),
|
||||
)
|
||||
|
||||
assert method == ["POST"]
|
||||
assert request.method == b"POST"
|
||||
|
||||
|
||||
async def test_should_override_request_url(page: Page, server: Server) -> None:
|
||||
url = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
url.append(route.request.url)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await page.route("**/global-var.html", _handler1)
|
||||
|
||||
def _handler2(route: Route) -> None:
|
||||
asyncio.create_task(route.fallback(url=server.PREFIX + "/global-var.html"))
|
||||
|
||||
await page.route("**/foo", _handler2)
|
||||
|
||||
[server_request, response, _] = await asyncio.gather(
|
||||
server.wait_for_request("/global-var.html"),
|
||||
page.wait_for_event("response"),
|
||||
page.goto(server.PREFIX + "/foo"),
|
||||
)
|
||||
|
||||
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 await page.evaluate("() => window['globalVar']") == 123
|
||||
assert server_request.uri == b"/global-var.html"
|
||||
assert server_request.method == b"GET"
|
||||
|
||||
|
||||
async def test_should_amend_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
post_data = []
|
||||
|
||||
def _handler(route: Route) -> None:
|
||||
post_data.append(route.request.post_data)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await page.route("**/*", _handler)
|
||||
await page.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.fallback(post_data="doggo"))
|
||||
)
|
||||
[server_request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
assert post_data == ["doggo"]
|
||||
assert server_request.post_body == b"doggo"
|
||||
|
||||
|
||||
async def test_should_amend_binary_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
post_data_buffer = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
post_data_buffer.append(route.request.post_data)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await page.route("**/*", _handler1)
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
await route.fallback(post_data=b"\x00\x01\x02\x03\x04")
|
||||
|
||||
await page.route("**/*", _handler2)
|
||||
|
||||
[server_request, result] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
# 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"
|
||||
|
||||
|
||||
async def test_should_chain_fallback_with_dynamic_url(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
intercepted = []
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
intercepted.append(1)
|
||||
asyncio.create_task(route.fallback(url=server.EMPTY_PAGE))
|
||||
|
||||
await page.route("**/bar", _handler1)
|
||||
|
||||
def _handler2(route: Route, request: Request) -> None:
|
||||
intercepted.append(2)
|
||||
asyncio.create_task(route.fallback(url="http://localhost/bar"))
|
||||
|
||||
await page.route("**/foo", _handler2)
|
||||
|
||||
def _handler3(route: Route, request: Request) -> None:
|
||||
intercepted.append(3)
|
||||
asyncio.create_task(route.fallback(url="http://localhost/foo"))
|
||||
|
||||
await page.route("**/empty.html", _handler3)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert intercepted == [3, 2, 1]
|
||||
|
||||
|
||||
async def test_should_amend_json_post_data(server: Server, page: Page) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
post_data = []
|
||||
|
||||
def _handle1(route: Route, request: Request) -> None:
|
||||
post_data.append(route.request.post_data)
|
||||
asyncio.create_task(route.continue_())
|
||||
|
||||
await page.route("**/*", _handle1)
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.fallback(post_data={"foo": "bar"})),
|
||||
)
|
||||
|
||||
[server_request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
assert post_data == ['{"foo": "bar"}']
|
||||
assert server_request.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.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server) -> None:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
globalThis.objectToDestroy = { hello: 'world' };
|
||||
globalThis.weakRef = new WeakRef(globalThis.objectToDestroy);
|
||||
}"""
|
||||
)
|
||||
await page.request_gc()
|
||||
assert await page.evaluate("() => globalThis.weakRef.deref()") == {"hello": "world"}
|
||||
|
||||
await page.request_gc()
|
||||
assert await page.evaluate("() => globalThis.weakRef.deref()") == {"hello": "world"}
|
||||
|
||||
await page.evaluate("() => globalThis.objectToDestroy = null")
|
||||
await page.request_gc()
|
||||
assert await page.evaluate("() => globalThis.weakRef.deref()") is None
|
||||
@@ -0,0 +1,100 @@
|
||||
# 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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page, Route, expect
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
async def test_should_support_timeout_option_in_route_fetch(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
def _handler(request: TestServerRequest) -> None:
|
||||
request.responseHeaders.addRawHeader("Content-Length", "4096")
|
||||
request.responseHeaders.addRawHeader("Content-Type", "text/html")
|
||||
request.write(b"")
|
||||
|
||||
server.set_route("/slow", _handler)
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
with pytest.raises(Error) as error:
|
||||
await route.fetch(timeout=1000)
|
||||
assert "Route.fetch: Timeout 1000ms exceeded." in error.value.message
|
||||
|
||||
await page.route("**/*", lambda route: handle(route))
|
||||
with pytest.raises(Error) as error:
|
||||
await page.goto(server.PREFIX + "/slow", timeout=2000)
|
||||
assert "Timeout 2000ms exceeded" in error.value.message
|
||||
|
||||
|
||||
async 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")
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
response = await route.fetch(max_redirects=0)
|
||||
assert response.headers["location"] == "/empty.html"
|
||||
assert response.status == 302
|
||||
await route.fulfill(body="hello")
|
||||
|
||||
await page.route("**/*", lambda route: handle(route))
|
||||
await page.goto(server.PREFIX + "/foo")
|
||||
assert "hello" in await page.content()
|
||||
|
||||
|
||||
async def test_should_intercept_with_url_override(server: Server, page: Page) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await route.fetch(url=server.PREFIX + "/one-style.html")
|
||||
await route.fulfill(response=response)
|
||||
|
||||
await page.route("**/*.html", lambda route: handle(route))
|
||||
response = await page.goto(server.PREFIX + "/empty.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert "one-style.css" in (await response.body()).decode("utf-8")
|
||||
|
||||
|
||||
async def test_should_intercept_with_post_data_override(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
request_promise = asyncio.create_task(server.wait_for_request("/empty.html"))
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
response = await route.fetch(post_data={"foo": "bar"})
|
||||
await route.fulfill(response=response)
|
||||
|
||||
await page.route("**/*.html", lambda route: handle(route))
|
||||
await page.goto(server.PREFIX + "/empty.html")
|
||||
request = await request_promise
|
||||
assert request.post_body
|
||||
assert request.post_body.decode("utf-8") == '{"foo": "bar"}'
|
||||
|
||||
|
||||
async def test_should_fulfill_popup_main_request_using_alias(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
async def route_handler(route: Route) -> None:
|
||||
response = await route.fetch()
|
||||
await route.fulfill(response=response, body="hello")
|
||||
|
||||
await page.context.route("**/*", route_handler)
|
||||
await page.set_content(f'<a target=_blank href="{server.EMPTY_PAGE}">click me</a>')
|
||||
[popup, _] = await asyncio.gather(
|
||||
page.wait_for_event("popup"), page.get_by_text("click me").click()
|
||||
)
|
||||
await expect(popup.locator("body")).to_have_text("hello")
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,273 @@
|
||||
# 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.async_api import Error, Page, TimeoutError
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", "blue")
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_value(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", "blue")
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_label(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", label="Indigo")
|
||||
assert await page.evaluate("result.onInput") == ["indigo"]
|
||||
assert await page.evaluate("result.onChange") == ["indigo"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_empty_label(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<select>
|
||||
<option value="indigo">Indigo</option>
|
||||
<option value="violet"></option>
|
||||
</select>
|
||||
"""
|
||||
)
|
||||
assert await page.locator("select").input_value() == "indigo"
|
||||
await page.select_option("select", label="")
|
||||
assert await page.locator("select").input_value() == "violet"
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_handle(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option(
|
||||
"select", element=await page.query_selector("[id=whiteOption]")
|
||||
)
|
||||
assert await page.evaluate("result.onInput") == ["white"]
|
||||
assert await page.evaluate("result.onChange") == ["white"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_index(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", index=2)
|
||||
assert await page.evaluate("result.onInput") == ["brown"]
|
||||
assert await page.evaluate("result.onChange") == ["brown"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_single_option_by_index_0(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", index=0)
|
||||
assert await page.evaluate("result.onInput") == ["black"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_only_first_option(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", ["blue", "green", "red"])
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_select_option_should_not_throw_when_select_causes_navigation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.eval_on_selector(
|
||||
"select",
|
||||
"select => select.addEventListener('input', () => window.location = '/empty.html')",
|
||||
)
|
||||
async with page.expect_navigation():
|
||||
await page.select_option("select", "blue")
|
||||
assert "empty.html" in page.url
|
||||
|
||||
|
||||
async def test_select_option_should_select_multiple_options(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
await page.select_option("select", ["blue", "green", "red"])
|
||||
assert await page.evaluate("result.onInput") == ["blue", "green", "red"]
|
||||
assert await page.evaluate("result.onChange") == ["blue", "green", "red"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_multiple_options_with_attributes(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
await page.select_option(
|
||||
"select",
|
||||
value="blue",
|
||||
label="Green",
|
||||
index=4,
|
||||
)
|
||||
assert await page.evaluate("result.onInput") == ["blue", "gray", "green"]
|
||||
assert await page.evaluate("result.onChange") == ["blue", "gray", "green"]
|
||||
|
||||
|
||||
async def test_select_option_should_select_option_with_empty_value(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<select>
|
||||
<option value="first">First</option>
|
||||
<option value="">Second</option>
|
||||
</select>
|
||||
"""
|
||||
)
|
||||
assert await page.locator("select").input_value() == "first"
|
||||
await page.select_option("select", value="")
|
||||
assert await page.locator("select").input_value() == ""
|
||||
|
||||
|
||||
async def test_select_option_should_respect_event_bubbling(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", "blue")
|
||||
assert await page.evaluate("result.onBubblingInput") == ["blue"]
|
||||
assert await page.evaluate("result.onBubblingChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_select_option_should_throw_when_element_is_not_a__select_(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.select_option("body", "")
|
||||
assert "Element is not a <select> element" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_select_option_should_return_on_no_matched_values(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
with pytest.raises(TimeoutError) as exc_info:
|
||||
await page.select_option("select", ["42", "abc"], timeout=1000)
|
||||
assert "Timeout 1000" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_select_option_should_return_an_array_of_matched_values(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
result = await page.select_option("select", ["blue", "black", "magenta"])
|
||||
assert result == ["black", "blue", "magenta"]
|
||||
|
||||
|
||||
async def test_select_option_should_return_an_array_of_one_element_when_multiple_is_not_set(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
result = await page.select_option("select", ["42", "blue", "black", "magenta"])
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
async def test_select_option_should_return_on_no_values(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
result = await page.select_option("select", [])
|
||||
assert result == []
|
||||
|
||||
|
||||
async def test_select_option_should_not_allow_null_items(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.select_option("select", ["blue", None, "black", "magenta"]) # type: ignore
|
||||
assert "expected string, got object" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_select_option_should_unselect_with_null(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
result = await page.select_option("select", ["blue", "black", "magenta"])
|
||||
assert result == ["black", "blue", "magenta"]
|
||||
await page.select_option("select", None)
|
||||
assert await page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
async def test_select_option_should_deselect_all_options_when_passed_no_values_for_a_multiple_select(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("makeMultiple()")
|
||||
await page.select_option("select", ["blue", "black", "magenta"])
|
||||
await page.select_option("select", [])
|
||||
assert await page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
async def test_select_option_should_deselect_all_options_when_passed_no_values_for_a_select_without_multiple(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", ["blue", "black", "magenta"])
|
||||
await page.select_option("select", [])
|
||||
assert await page.eval_on_selector(
|
||||
"select",
|
||||
"select => Array.from(select.options).every(option => !option.selected)",
|
||||
)
|
||||
|
||||
|
||||
async def test_select_option_should_work_when_re_defining_top_level_event_class(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.evaluate("window.Event = null")
|
||||
await page.select_option("select", "blue")
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
|
||||
|
||||
async def test_select_options_should_fall_back_to_selecting_by_label(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/input/select.html")
|
||||
await page.select_option("select", "Blue")
|
||||
assert await page.evaluate("result.onInput") == ["blue"]
|
||||
assert await page.evaluate("result.onChange") == ["blue"]
|
||||
@@ -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
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Page
|
||||
from tests.server import Server
|
||||
|
||||
pytestmark = pytest.mark.only_browser("chromium")
|
||||
|
||||
|
||||
async def test_should_be_able_to_save_pdf_file(page: Page, tmp_path: Path) -> None:
|
||||
output_file = tmp_path / "foo.png"
|
||||
await page.pdf(path=str(output_file))
|
||||
assert os.path.getsize(output_file) > 0
|
||||
|
||||
|
||||
async def test_should_be_able_capture_pdf_without_path(page: Page) -> None:
|
||||
buffer = await page.pdf()
|
||||
assert buffer
|
||||
|
||||
|
||||
async def test_should_be_able_to_generate_outline(
|
||||
page: Page, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
await page.goto(server.PREFIX + "/headings.html")
|
||||
output_file_no_outline = tmp_path / "outputNoOutline.pdf"
|
||||
output_file_outline = tmp_path / "outputOutline.pdf"
|
||||
await page.pdf(path=output_file_no_outline)
|
||||
await page.pdf(path=output_file_outline, tagged=True, outline=True)
|
||||
assert os.path.getsize(output_file_outline) > os.path.getsize(
|
||||
output_file_no_outline
|
||||
)
|
||||
@@ -0,0 +1,480 @@
|
||||
# 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 typing import List, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, Request, Route
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_link_navigation_inherit_user_agent_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(user_agent="hey")
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
'<a target=_blank rel=noopener href="/popup/popup.html">link</a>'
|
||||
)
|
||||
request_waitable = asyncio.create_task(server.wait_for_request("/popup/popup.html"))
|
||||
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
|
||||
async with context.expect_page() as page_info:
|
||||
await page.click("a")
|
||||
popup = await page_info.value
|
||||
await popup.wait_for_load_state("domcontentloaded")
|
||||
user_agent = await popup.evaluate("window.initialUserAgent")
|
||||
request = await request_waitable
|
||||
assert user_agent == "hey"
|
||||
assert request.requestHeaders.getRawHeaders("user-agent") == ["hey"]
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_link_navigation_respect_routes_from_browser_context(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content('<a target=_blank rel=noopener href="empty.html">link</a>')
|
||||
|
||||
intercepted: List[bool] = []
|
||||
|
||||
async def handle_request(route: Route) -> None:
|
||||
intercepted.append(True)
|
||||
await route.continue_()
|
||||
|
||||
await context.route("**/empty.html", handle_request)
|
||||
async with context.expect_page():
|
||||
await page.click("a")
|
||||
assert intercepted == [True]
|
||||
|
||||
|
||||
async def test_window_open_inherit_user_agent_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(user_agent="hey")
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
request_promise = asyncio.create_task(server.wait_for_request("/dummy.html"))
|
||||
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
|
||||
user_agent = await page.evaluate(
|
||||
"""url => {
|
||||
win = window.open(url)
|
||||
return win.navigator.userAgent
|
||||
}""",
|
||||
server.PREFIX + "/dummy.html",
|
||||
)
|
||||
request = await request_promise
|
||||
assert user_agent == "hey"
|
||||
assert request.requestHeaders.getRawHeaders("user-agent") == ["hey"]
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_inherit_extra_headers_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(extra_http_headers={"foo": "bar"})
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
request_promise = asyncio.create_task(server.wait_for_request("/dummy.html"))
|
||||
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
|
||||
await page.evaluate(
|
||||
"url => window._popup = window.open(url)", server.PREFIX + "/dummy.html"
|
||||
)
|
||||
request = await request_promise
|
||||
assert request.requestHeaders.getRawHeaders("foo") == ["bar"]
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_inherit_offline_from_browser_context(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await context.set_offline(True)
|
||||
online = await page.evaluate(
|
||||
"""url => {
|
||||
win = window.open(url)
|
||||
return win.navigator.onLine
|
||||
}""",
|
||||
server.PREFIX + "/dummy.html",
|
||||
)
|
||||
assert online is False
|
||||
|
||||
|
||||
async def test_should_inherit_http_credentials_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
server.set_auth("/title.html", "user", "pass")
|
||||
context = await browser.new_context(
|
||||
http_credentials={"username": "user", "password": "pass"}
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"url => window._popup = window.open(url)", server.PREFIX + "/title.html"
|
||||
)
|
||||
popup = await popup_info.value
|
||||
await popup.wait_for_load_state("domcontentloaded")
|
||||
assert await popup.title() == "Woof-Woof"
|
||||
await context.close()
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("firefox")
|
||||
async def test_should_inherit_touch_support_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
# Firefox 148+ does not expose `ontouchstart` on freshly window.open()'d
|
||||
# popups (https://bugzilla.mozilla.org/show_bug.cgi?id=2014330);
|
||||
# upstream marks this as fixme for the same reason.
|
||||
context = await browser.new_context(
|
||||
viewport={"width": 400, "height": 500}, has_touch=True
|
||||
)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
has_touch = await page.evaluate(
|
||||
"""() => {
|
||||
win = window.open('')
|
||||
return 'ontouchstart' in win
|
||||
}"""
|
||||
)
|
||||
|
||||
assert has_touch
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_inherit_viewport_size_from_browser_context(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(viewport={"width": 400, "height": 500})
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
size = await page.evaluate(
|
||||
"""() => {
|
||||
win = window.open('about:blank')
|
||||
return { width: win.innerWidth, height: win.innerHeight }
|
||||
}"""
|
||||
)
|
||||
|
||||
assert size == {"width": 400, "height": 500}
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_use_viewport_size_from_window_features(
|
||||
browser: Browser, server: Server
|
||||
) -> None:
|
||||
context = await browser.new_context(viewport={"width": 700, "height": 700})
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
size = None
|
||||
async with page.expect_popup() as popup_info:
|
||||
size = await page.evaluate(
|
||||
"""async () => {
|
||||
const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=300,top=0,left=0');
|
||||
await new Promise(resolve => {
|
||||
const interval = setInterval(() => {
|
||||
if (win.innerWidth === 600 && win.innerHeight === 300) {
|
||||
clearInterval(interval);
|
||||
resolve();
|
||||
}
|
||||
}, 10);
|
||||
});
|
||||
return { width: win.innerWidth, height: win.innerHeight }
|
||||
}"""
|
||||
)
|
||||
popup = await popup_info.value
|
||||
await popup.set_viewport_size({"width": 500, "height": 400})
|
||||
await popup.wait_for_load_state()
|
||||
resized = await popup.evaluate(
|
||||
"() => ({ width: window.innerWidth, height: window.innerHeight })"
|
||||
)
|
||||
await context.close()
|
||||
assert size == {"width": 600, "height": 300}
|
||||
assert resized == {"width": 500, "height": 400}
|
||||
|
||||
|
||||
async def test_should_respect_routes_from_browser_context(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
def handle_request(route: Route, request: Request, intercepted: List[bool]) -> None:
|
||||
asyncio.create_task(route.continue_())
|
||||
intercepted.append(True)
|
||||
|
||||
intercepted: List[bool] = []
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route, request: handle_request(route, request, intercepted),
|
||||
)
|
||||
|
||||
async with page.expect_popup():
|
||||
await page.evaluate(
|
||||
"url => window.__popup = window.open(url)", server.EMPTY_PAGE
|
||||
)
|
||||
assert len(intercepted) == 1
|
||||
|
||||
|
||||
async def test_browser_context_add_init_script_should_apply_to_an_in_process_popup(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.add_init_script("window.injected = 123")
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
injected = await page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open('about:blank');
|
||||
return win.injected;
|
||||
}"""
|
||||
)
|
||||
|
||||
assert injected == 123
|
||||
|
||||
|
||||
async def test_browser_context_add_init_script_should_apply_to_a_cross_process_popup(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.add_init_script("window.injected = 123")
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"url => window.open(url)", server.CROSS_PROCESS_PREFIX + "/title.html"
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert await popup.evaluate("injected") == 123
|
||||
await popup.reload()
|
||||
assert await popup.evaluate("injected") == 123
|
||||
|
||||
|
||||
async def test_should_expose_function_from_browser_context(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.expose_function("add", lambda a, b: a + b)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
added = await page.evaluate(
|
||||
"""async () => {
|
||||
win = window.open('about:blank')
|
||||
return win.add(9, 4)
|
||||
}"""
|
||||
)
|
||||
|
||||
assert added == 13
|
||||
|
||||
|
||||
async def test_should_work(context: BrowserContext) -> None:
|
||||
page = await context.new_page()
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate('window.__popup = window.open("about:blank")')
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener")
|
||||
|
||||
|
||||
async def test_should_work_with_window_features(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
'window.__popup = window.open(window.location.href, "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0")'
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener")
|
||||
|
||||
|
||||
async def test_window_open_emit_for_immediately_closed_popups(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
win = window.open('about:blank')
|
||||
win.close()
|
||||
}"""
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert popup
|
||||
|
||||
|
||||
async def test_should_emit_for_immediately_closed_popups(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
win = window.open(window.location.href)
|
||||
win.close()
|
||||
}"""
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert popup
|
||||
|
||||
|
||||
async def test_should_be_able_to_capture_alert(context: BrowserContext) -> None:
|
||||
page = await context.new_page()
|
||||
evaluate_task: Optional[asyncio.Future] = None
|
||||
|
||||
async def evaluate() -> None:
|
||||
nonlocal evaluate_task
|
||||
evaluate_task = asyncio.create_task(
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
const win = window.open('')
|
||||
win.alert('hello')
|
||||
}"""
|
||||
)
|
||||
)
|
||||
|
||||
[popup, dialog, _] = await asyncio.gather(
|
||||
page.wait_for_event("popup"), context.wait_for_event("dialog"), evaluate()
|
||||
)
|
||||
|
||||
assert dialog.message == "hello"
|
||||
assert dialog.page == popup
|
||||
await dialog.dismiss()
|
||||
await must(evaluate_task)
|
||||
|
||||
|
||||
async def test_should_work_with_empty_url(context: BrowserContext) -> None:
|
||||
page = await context.new_page()
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate("() => window.__popup = window.open('')")
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener")
|
||||
|
||||
|
||||
async def test_should_work_with_noopener_and_no_url(context: BrowserContext) -> None:
|
||||
page = await context.new_page()
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
'() => window.__popup = window.open(undefined, null, "noopener")'
|
||||
)
|
||||
popup = await popup_info.value
|
||||
# Chromium reports 'about:blank#blocked' here.
|
||||
assert popup.url.split("#")[0] == "about:blank"
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener") is False
|
||||
|
||||
|
||||
async def test_should_work_with_noopener_and_about_blank(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
'() => window.__popup = window.open("about:blank", null, "noopener")'
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener") is False
|
||||
|
||||
|
||||
async def test_should_work_with_noopener_and_url(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.evaluate(
|
||||
'url => window.__popup = window.open(url, null, "noopener")',
|
||||
server.EMPTY_PAGE,
|
||||
)
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener") is False
|
||||
|
||||
|
||||
async def test_should_work_with_clicking_target__blank(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
'<a target=_blank rel="opener" href="/one-style.html">yo</a>'
|
||||
)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.click("a")
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener")
|
||||
assert popup.main_frame.page == popup
|
||||
|
||||
|
||||
async def test_should_work_with_fake_clicking_target__blank_and_rel_noopener(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
|
||||
)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.eval_on_selector("a", "a => a.click()")
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener") is False
|
||||
|
||||
|
||||
async def test_should_work_with_clicking_target__blank_and_rel_noopener(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
|
||||
)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.click("a")
|
||||
popup = await popup_info.value
|
||||
assert await page.evaluate("!!window.opener") is False
|
||||
assert await popup.evaluate("!!window.opener") is False
|
||||
|
||||
|
||||
async def test_should_not_treat_navigations_as_new_popups(
|
||||
context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
|
||||
)
|
||||
async with page.expect_popup() as popup_info:
|
||||
await page.click("a")
|
||||
popup = await popup_info.value
|
||||
handled_popups = []
|
||||
page.on(
|
||||
"popup",
|
||||
lambda popup: handled_popups.append(True),
|
||||
)
|
||||
|
||||
await popup.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
|
||||
assert len(handled_popups) == 0
|
||||
@@ -0,0 +1,160 @@
|
||||
# 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
|
||||
import base64
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, Error
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
async def test_should_throw_for_bad_server_value(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]",
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await browser_factory(proxy={"server": 123})
|
||||
assert "proxy.server: expected string, got number" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_should_use_proxy(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
browser = await browser_factory(proxy={"server": f"localhost:{server.PORT}"})
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_proxy_should_allow_none_for_optional_settings(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
browser = await browser_factory(
|
||||
proxy={
|
||||
"server": f"localhost:{server.PORT}",
|
||||
"username": None,
|
||||
"password": None,
|
||||
"bypass": None,
|
||||
}
|
||||
)
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_use_proxy_for_second_page(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
browser = await browser_factory(proxy={"server": f"localhost:{server.PORT}"})
|
||||
|
||||
page1 = await browser.new_page()
|
||||
await page1.goto("http://non-existent.com/target.html")
|
||||
assert await page1.title() == "Served by the proxy"
|
||||
|
||||
page2 = await browser.new_page()
|
||||
await page2.goto("http://non-existent.com/target.html")
|
||||
assert await page2.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_work_with_ip_port_notion(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
server.set_route(
|
||||
"/target.html",
|
||||
lambda r: (
|
||||
r.write(b"<html><title>Served by the proxy</title></html>"),
|
||||
r.finish(),
|
||||
),
|
||||
)
|
||||
browser = await browser_factory(proxy={"server": f"127.0.0.1:{server.PORT}"})
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Served by the proxy"
|
||||
|
||||
|
||||
async def test_should_authenticate(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
def handler(req: TestServerRequest) -> None:
|
||||
auth = req.getHeader("proxy-authorization")
|
||||
if not auth:
|
||||
req.setHeader(
|
||||
b"Proxy-Authenticate", b'Basic realm="Access to internal site"'
|
||||
)
|
||||
req.setResponseCode(407)
|
||||
else:
|
||||
req.write(f"<html><title>{auth}</title></html>".encode("utf-8"))
|
||||
req.finish()
|
||||
|
||||
server.set_route("/target.html", handler)
|
||||
|
||||
browser = await browser_factory(
|
||||
proxy={
|
||||
"server": f"localhost:{server.PORT}",
|
||||
"username": "user",
|
||||
"password": "secret",
|
||||
}
|
||||
)
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Basic " + base64.b64encode(b"user:secret").decode(
|
||||
"utf-8"
|
||||
)
|
||||
|
||||
|
||||
async def test_should_authenticate_with_empty_password(
|
||||
browser_factory: "Callable[..., asyncio.Future[Browser]]", server: Server
|
||||
) -> None:
|
||||
def handler(req: TestServerRequest) -> None:
|
||||
auth = req.getHeader("proxy-authorization")
|
||||
if not auth:
|
||||
req.setHeader(
|
||||
b"Proxy-Authenticate", b'Basic realm="Access to internal site"'
|
||||
)
|
||||
req.setResponseCode(407)
|
||||
else:
|
||||
req.write(f"<html><title>{auth}</title></html>".encode("utf-8"))
|
||||
req.finish()
|
||||
|
||||
server.set_route("/target.html", handler)
|
||||
|
||||
browser = await browser_factory(
|
||||
proxy={"server": f"localhost:{server.PORT}", "username": "user", "password": ""}
|
||||
)
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://non-existent.com/target.html")
|
||||
assert await page.title() == "Basic " + base64.b64encode(b"user:").decode("utf-8")
|
||||
@@ -0,0 +1,410 @@
|
||||
# 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.async_api import Browser, Error, Page, Selectors
|
||||
|
||||
from .utils import Utils
|
||||
|
||||
|
||||
async 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.
|
||||
await selectors.register(selector_name, tag_selector)
|
||||
|
||||
context = await browser.new_context()
|
||||
# Register another engine after creating context.
|
||||
await selectors.register(selector2_name, tag_selector)
|
||||
|
||||
page = await context.new_page()
|
||||
await page.set_content("<div><span></span></div><div></div>")
|
||||
|
||||
assert (
|
||||
await page.eval_on_selector(f"{selector_name}=DIV", "e => e.nodeName") == "DIV"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector(f"{selector_name}=SPAN", "e => e.nodeName")
|
||||
== "SPAN"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(f"{selector_name}=DIV", "es => es.length") == 2
|
||||
)
|
||||
|
||||
assert (
|
||||
await page.eval_on_selector(f"{selector2_name}=DIV", "e => e.nodeName") == "DIV"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector(f"{selector2_name}=SPAN", "e => e.nodeName")
|
||||
== "SPAN"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(f"{selector2_name}=DIV", "es => es.length") == 2
|
||||
)
|
||||
|
||||
# Selector names are case-sensitive.
|
||||
with pytest.raises(Error) as exc:
|
||||
await page.query_selector("tAG=DIV")
|
||||
assert 'Unknown engine "tAG" while parsing selector tAG=DIV' in exc.value.message
|
||||
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_selectors_register_should_work_with_path(
|
||||
selectors: Selectors, page: Page, utils: Utils, assetdir: Path
|
||||
) -> None:
|
||||
await utils.register_selector_engine(
|
||||
selectors, "foo", path=assetdir / "sectionselectorengine.js"
|
||||
)
|
||||
await page.set_content("<section></section>")
|
||||
assert await page.eval_on_selector("foo=whatever", "e => e.nodeName") == "SECTION"
|
||||
|
||||
|
||||
async 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] : [];
|
||||
}
|
||||
}"""
|
||||
|
||||
await utils.register_selector_engine(selectors, "main", dummy_selector_script)
|
||||
await utils.register_selector_engine(
|
||||
selectors, "isolated", dummy_selector_script, content_script=True
|
||||
)
|
||||
await page.set_content("<div><span><section></section></span></div>")
|
||||
await page.evaluate('() => window.__answer = document.querySelector("span")')
|
||||
# Works in main if asked.
|
||||
assert await page.eval_on_selector("main=ignored", "e => e.nodeName") == "SPAN"
|
||||
assert (
|
||||
await page.eval_on_selector("css=div >> main=ignored", "e => e.nodeName")
|
||||
== "SPAN"
|
||||
)
|
||||
assert await page.eval_on_selector_all(
|
||||
"main=ignored", "es => window.__answer !== undefined"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"main=ignored", "es => es.filter(e => e).length"
|
||||
)
|
||||
== 3
|
||||
)
|
||||
# Works in isolated by default.
|
||||
assert await page.query_selector("isolated=ignored") is None
|
||||
assert await page.query_selector("css=div >> isolated=ignored") is None
|
||||
# $$eval always works in main, to avoid adopting nodes one by one.
|
||||
assert await page.eval_on_selector_all(
|
||||
"isolated=ignored", "es => window.__answer !== undefined"
|
||||
)
|
||||
assert (
|
||||
await 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 (
|
||||
await page.eval_on_selector(
|
||||
"main=ignored >> isolated=ignored", "e => e.nodeName"
|
||||
)
|
||||
== "SPAN"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector(
|
||||
"isolated=ignored >> main=ignored", "e => e.nodeName"
|
||||
)
|
||||
== "SPAN"
|
||||
)
|
||||
# Can be chained to css.
|
||||
assert (
|
||||
await page.eval_on_selector("main=ignored >> css=section", "e => e.nodeName")
|
||||
== "SECTION"
|
||||
)
|
||||
|
||||
|
||||
async def test_selectors_register_should_handle_errors(
|
||||
selectors: Selectors, page: Page, utils: Utils
|
||||
) -> None:
|
||||
with pytest.raises(Error) as exc:
|
||||
await 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:
|
||||
await 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.
|
||||
await utils.register_selector_engine(
|
||||
selectors, "dummy", dummy_selector_engine_script
|
||||
)
|
||||
await utils.register_selector_engine(
|
||||
selectors, "duMMy", dummy_selector_engine_script
|
||||
)
|
||||
|
||||
with pytest.raises(Error) as exc:
|
||||
await 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:
|
||||
await selectors.register("css", dummy_selector_engine_script)
|
||||
assert (
|
||||
exc.value.message == 'Selectors.register: "css" is a predefined selector engine'
|
||||
)
|
||||
|
||||
|
||||
async 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],
|
||||
]
|
||||
await page.set_content(
|
||||
'<container style="width: 500px; height: 500px; position: relative;"></container>'
|
||||
)
|
||||
await 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 await page.eval_on_selector("div:right-of(#id6)", "e => e.id") == "id7"
|
||||
assert await page.eval_on_selector("div:right-of(#id1)", "e => e.id") == "id2"
|
||||
assert await page.eval_on_selector("div:right-of(#id3)", "e => e.id") == "id4"
|
||||
assert await page.query_selector("div:right-of(#id4)") is None
|
||||
assert await page.eval_on_selector("div:right-of(#id0)", "e => e.id") == "id7"
|
||||
assert await page.eval_on_selector("div:right-of(#id8)", "e => e.id") == "id9"
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:right-of(#id3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id2,id5,id7,id8,id9"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:right-of(#id3, 50)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id2,id5,id7,id8"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:right-of(#id3, 49)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id8"
|
||||
)
|
||||
|
||||
assert await page.eval_on_selector("div:left-of(#id2)", "e => e.id") == "id1"
|
||||
assert await page.query_selector("div:left-of(#id0)") is None
|
||||
assert await page.eval_on_selector("div:left-of(#id5)", "e => e.id") == "id0"
|
||||
assert await page.eval_on_selector("div:left-of(#id9)", "e => e.id") == "id8"
|
||||
assert await page.eval_on_selector("div:left-of(#id4)", "e => e.id") == "id3"
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:left-of(#id5)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id7,id3,id1,id6,id8"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:left-of(#id5, 3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id8"
|
||||
)
|
||||
|
||||
assert await page.eval_on_selector("div:above(#id0)", "e => e.id") == "id3"
|
||||
assert await page.eval_on_selector("div:above(#id5)", "e => e.id") == "id4"
|
||||
assert await page.eval_on_selector("div:above(#id7)", "e => e.id") == "id5"
|
||||
assert await page.eval_on_selector("div:above(#id8)", "e => e.id") == "id0"
|
||||
assert await page.eval_on_selector("div:above(#id9)", "e => e.id") == "id8"
|
||||
assert await page.query_selector("div:above(#id2)") is None
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:above(#id5)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id2,id3,id1"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:above(#id5, 20)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id4,id3"
|
||||
)
|
||||
|
||||
assert await page.eval_on_selector("div:below(#id4)", "e => e.id") == "id5"
|
||||
assert await page.eval_on_selector("div:below(#id3)", "e => e.id") == "id0"
|
||||
assert await page.eval_on_selector("div:below(#id2)", "e => e.id") == "id4"
|
||||
assert await page.eval_on_selector("div:below(#id6)", "e => e.id") == "id8"
|
||||
assert await page.eval_on_selector("div:below(#id7)", "e => e.id") == "id8"
|
||||
assert await page.eval_on_selector("div:below(#id8)", "e => e.id") == "id9"
|
||||
assert await page.query_selector("div:below(#id9)") is None
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:below(#id3)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id6,id7,id8,id9"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:below(#id3, 105)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id6,id7"
|
||||
)
|
||||
|
||||
assert await page.eval_on_selector("div:near(#id0)", "e => e.id") == "id3"
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:near(#id7)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id5,id3,id6"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:near(#id0)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id3,id6,id7,id8,id1,id5"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:near(#id6)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0,id3,id7"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"div:near(#id6, 10)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id0"
|
||||
)
|
||||
assert (
|
||||
await 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 (
|
||||
await page.eval_on_selector_all(
|
||||
"div:below(#id5):above(#id8)", "els => els.map(e => e.id).join(',')"
|
||||
)
|
||||
== "id7,id6"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("div:below(#id5):above(#id8)", "e => e.id") == "id7"
|
||||
)
|
||||
|
||||
assert (
|
||||
await 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:
|
||||
await 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:
|
||||
await page.query_selector('left-of="div"')
|
||||
assert '"left-of" selector cannot be first' in exc_info.value.message
|
||||
@@ -0,0 +1,196 @@
|
||||
# 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 typing import Optional
|
||||
|
||||
from playwright.async_api import Page, Route
|
||||
from tests.server import Server, TestServerRequest
|
||||
|
||||
|
||||
async def test_request_continue_should_work(page: Page, server: Server) -> None:
|
||||
await page.route("**/*", lambda route: asyncio.create_task(route.continue_()))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_request_continue_should_amend_http_headers(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(
|
||||
route.continue_(headers={**route.request.headers, "FOO": "bar"})
|
||||
),
|
||||
)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate('() => fetch("/sleep.zzz")'),
|
||||
)
|
||||
assert request.getHeader("foo") == "bar"
|
||||
|
||||
|
||||
async def test_request_continue_should_amend_method(page: Page, server: Server) -> None:
|
||||
server_request = asyncio.create_task(server.wait_for_request("/sleep.zzz"))
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.continue_(method="POST"))
|
||||
)
|
||||
[request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate('() => fetch("/sleep.zzz")'),
|
||||
)
|
||||
assert request.method.decode() == "POST"
|
||||
assert (await server_request).method.decode() == "POST"
|
||||
|
||||
|
||||
async def test_request_continue_should_amend_method_on_main_request(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
request = asyncio.create_task(server.wait_for_request("/empty.html"))
|
||||
await page.route(
|
||||
"**/*", lambda route: asyncio.create_task(route.continue_(method="POST"))
|
||||
)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert (await request).method.decode() == "POST"
|
||||
|
||||
|
||||
async def test_request_continue_should_amend_post_data(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.continue_(post_data=b"doggo")),
|
||||
)
|
||||
|
||||
[server_request, _] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate(
|
||||
"""
|
||||
() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })
|
||||
"""
|
||||
),
|
||||
)
|
||||
assert server_request.post_body
|
||||
assert server_request.post_body.decode() == "doggo"
|
||||
|
||||
|
||||
async def test_should_override_request_url(page: Page, server: Server) -> None:
|
||||
request = asyncio.create_task(server.wait_for_request("/empty.html"))
|
||||
await page.route(
|
||||
"**/foo",
|
||||
lambda route: asyncio.create_task(route.continue_(url=server.EMPTY_PAGE)),
|
||||
)
|
||||
|
||||
await page.goto(server.PREFIX + "/foo")
|
||||
assert (await request).method == b"GET"
|
||||
|
||||
|
||||
async def test_should_raise_except(page: Page, server: Server) -> None:
|
||||
exc_fut: "asyncio.Future[Optional[Exception]]" = asyncio.Future()
|
||||
|
||||
async def capture_exception(route: Route) -> None:
|
||||
try:
|
||||
await route.continue_(url="file:///tmp/does-not-exist")
|
||||
exc_fut.set_result(None)
|
||||
except Exception as e:
|
||||
exc_fut.set_result(e)
|
||||
|
||||
await page.route("**/*", capture_exception)
|
||||
asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
assert "New URL must have same protocol as overridden URL" in str(await exc_fut)
|
||||
|
||||
|
||||
async def test_should_amend_utf8_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(route.continue_(post_data="пушкин")),
|
||||
)
|
||||
|
||||
[server_request, result] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
assert server_request.method == b"POST"
|
||||
assert server_request.post_body
|
||||
assert server_request.post_body.decode("utf8") == "пушкин"
|
||||
|
||||
|
||||
async def test_should_amend_binary_post_data(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: asyncio.create_task(
|
||||
route.continue_(post_data=b"\x00\x01\x02\x03\x04")
|
||||
),
|
||||
)
|
||||
|
||||
[server_request, result] = await asyncio.gather(
|
||||
server.wait_for_request("/sleep.zzz"),
|
||||
page.evaluate("fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
|
||||
)
|
||||
assert server_request.method == b"POST"
|
||||
assert server_request.post_body == b"\x00\x01\x02\x03\x04"
|
||||
|
||||
|
||||
async def test_continue_should_not_change_multipart_form_data_body(
|
||||
page: Page, server: Server, browser_name: str
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
server.set_route(
|
||||
"/upload",
|
||||
lambda context: (
|
||||
context.write(b"done"),
|
||||
context.setHeader("Content-Type", "text/plain"),
|
||||
context.finish(),
|
||||
),
|
||||
)
|
||||
|
||||
async def send_form_data() -> TestServerRequest:
|
||||
req_task = asyncio.create_task(server.wait_for_request("/upload"))
|
||||
status = await page.evaluate(
|
||||
"""async () => {
|
||||
const newFile = new File(['file content'], 'file.txt');
|
||||
const formData = new FormData();
|
||||
formData.append('file', newFile);
|
||||
const response = await fetch('/upload', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: formData,
|
||||
});
|
||||
return response.status;
|
||||
}"""
|
||||
)
|
||||
req = await req_task
|
||||
assert status == 200
|
||||
return req
|
||||
|
||||
req_before = await send_form_data()
|
||||
await page.route("**/*", lambda route: route.continue_())
|
||||
req_after = await send_form_data()
|
||||
|
||||
file_content = (
|
||||
'Content-Disposition: form-data; name="file"; filename="file.txt"\r\n'
|
||||
"Content-Type: application/octet-stream\r\n"
|
||||
"\r\n"
|
||||
"file content\r\n"
|
||||
"------"
|
||||
)
|
||||
assert req_before.post_body
|
||||
assert req_after.post_body
|
||||
assert file_content in req_before.post_body.decode()
|
||||
assert file_content in req_after.post_body.decode()
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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.async_api import Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_fetch_original_request_and_fulfill(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(response=response)
|
||||
|
||||
await page.route("**/*", handle)
|
||||
response = await page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 200
|
||||
assert await page.title() == "Woof-Woof"
|
||||
|
||||
|
||||
async def test_should_fulfill_json(page: Page, server: Server) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
await route.fulfill(status=201, headers={"foo": "bar"}, json={"bar": "baz"})
|
||||
|
||||
await page.route("**/*", handle)
|
||||
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert response.headers["content-type"] == "application/json"
|
||||
assert await response.json() == {"bar": "baz"}
|
||||
|
||||
|
||||
async 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 = {}
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
response = await route.fetch()
|
||||
json = await response.json()
|
||||
original["tags"] = json["tags"]
|
||||
json["tags"] = ["c"]
|
||||
await route.fulfill(response=response, json=json)
|
||||
|
||||
await page.route("**/*", handle)
|
||||
|
||||
response = await 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 await response.json() == {"tags": ["c"]}
|
||||
@@ -0,0 +1,191 @@
|
||||
# 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 pathlib import Path
|
||||
|
||||
from twisted.web import http
|
||||
|
||||
from playwright.async_api import Page, Route
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_fulfill_intercepted_response(page: Page, server: Server) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(
|
||||
response=response,
|
||||
status=201,
|
||||
headers={"foo": "bar"},
|
||||
content_type="text/plain",
|
||||
body="Yo, page!",
|
||||
)
|
||||
|
||||
await page.route("**/*", handle)
|
||||
response = await 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 await page.evaluate("() => document.body.textContent") == "Yo, page!"
|
||||
|
||||
|
||||
async def test_should_fulfill_response_with_empty_body(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
async def handle(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(
|
||||
response=response, status=201, body="", headers={"content-length": "0"}
|
||||
)
|
||||
|
||||
await page.route("**/*", handle)
|
||||
response = await page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == ""
|
||||
|
||||
|
||||
async 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)
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
await page.request.fetch(route.request)
|
||||
await route.fulfill(status=201)
|
||||
|
||||
await page.route("**/*", handle)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == ""
|
||||
if browser_name == "webkit":
|
||||
assert response.headers == {"content-type": "text/plain"}
|
||||
else:
|
||||
assert response.headers == {}
|
||||
|
||||
|
||||
async 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 = await page.request.get(server.PREFIX + "/sample")
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: route.fulfill(
|
||||
response=sample_response, status=201, content_type="text/plain"
|
||||
),
|
||||
)
|
||||
response = await page.goto(server.EMPTY_PAGE)
|
||||
assert response
|
||||
assert response.status == 201
|
||||
assert await response.text() == "Woo-hoo"
|
||||
assert response.headers["foo"] == "bar"
|
||||
|
||||
|
||||
async def test_should_support_fulfill_after_intercept(
|
||||
page: Page, server: Server, assetdir: Path
|
||||
) -> None:
|
||||
request_future = asyncio.create_task(server.wait_for_request("/title.html"))
|
||||
|
||||
async def handle_route(route: Route) -> None:
|
||||
response = await page.request.fetch(route.request)
|
||||
await route.fulfill(response=response)
|
||||
|
||||
await page.route("**", handle_route)
|
||||
response = await page.goto(server.PREFIX + "/title.html")
|
||||
assert response
|
||||
request = await request_future
|
||||
assert request.uri.decode() == "/title.html"
|
||||
original = (assetdir / "title.html").read_text()
|
||||
assert await response.text() == original
|
||||
|
||||
|
||||
async def test_should_give_access_to_the_intercepted_response(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_task: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route("**/title.html", lambda route: route_task.set_result(route))
|
||||
|
||||
eval_task = asyncio.create_task(
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + "/title.html")
|
||||
)
|
||||
|
||||
route = await route_task
|
||||
response = await page.request.fetch(route.request)
|
||||
|
||||
assert response.status == 200
|
||||
assert response.status_text == "OK"
|
||||
assert response.ok is True
|
||||
assert response.url.endswith("/title.html") is True
|
||||
assert response.headers["content-type"] == "text/html; charset=utf-8"
|
||||
assert list(
|
||||
filter(
|
||||
lambda header: header["name"].lower() == "content-type",
|
||||
response.headers_array,
|
||||
)
|
||||
) == [{"name": "Content-Type", "value": "text/html; charset=utf-8"}]
|
||||
|
||||
await asyncio.gather(
|
||||
route.fulfill(response=response),
|
||||
eval_task,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_give_access_to_the_intercepted_response_body(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_task: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route("**/simple.json", lambda route: route_task.set_result(route))
|
||||
|
||||
eval_task = asyncio.create_task(
|
||||
page.evaluate("url => fetch(url)", server.PREFIX + "/simple.json")
|
||||
)
|
||||
|
||||
route = await route_task
|
||||
response = await page.request.fetch(route.request)
|
||||
|
||||
assert await response.text() == '{"foo": "bar"}\n'
|
||||
|
||||
await asyncio.gather(
|
||||
route.fulfill(response=response),
|
||||
eval_task,
|
||||
)
|
||||
|
||||
|
||||
async def test_should_intercept_by_glob(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.route(
|
||||
"http://localhos**?*oo",
|
||||
lambda route: route.fulfill(body="intercepted", status=200),
|
||||
)
|
||||
|
||||
result = await page.evaluate(
|
||||
"url => fetch(url).then(r => r.text())", server.PREFIX + "/?foo"
|
||||
)
|
||||
|
||||
assert result == "intercepted"
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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.async_api import Browser, Page, ResourceTiming
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server) -> None:
|
||||
async with page.expect_event("requestfinished") as request_info:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
request = await 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
|
||||
|
||||
|
||||
async 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))
|
||||
await 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
|
||||
|
||||
|
||||
async def test_should_work_for_ssl(browser: Browser, https_server: Server) -> None:
|
||||
page = await browser.new_page(ignore_https_errors=True)
|
||||
async with page.expect_event("requestfinished") as request_info:
|
||||
await page.goto(https_server.EMPTY_PAGE)
|
||||
request = await 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
|
||||
await page.close()
|
||||
|
||||
|
||||
@pytest.mark.skip_browser("webkit") # In WebKit, redirects don"t carry the timing info
|
||||
async 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))
|
||||
await page.goto(server.PREFIX + "/foo.html")
|
||||
for r in responses:
|
||||
await 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,381 @@
|
||||
# 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
|
||||
import re
|
||||
from typing import Any, Awaitable, Callable, Literal, Tuple, Union
|
||||
|
||||
from playwright.async_api import Frame, Page, WebSocketRoute
|
||||
from playwright.async_api._generated import Browser
|
||||
from tests.server import Server, WebSocketProtocol
|
||||
|
||||
|
||||
async def assert_equal(
|
||||
actual_cb: Callable[[], Union[Any, Awaitable[Any]]], expected: Any
|
||||
) -> None:
|
||||
__tracebackhide__ = True
|
||||
start_time = asyncio.get_event_loop().time()
|
||||
attempts = 0
|
||||
while True:
|
||||
actual = actual_cb()
|
||||
if asyncio.iscoroutine(actual):
|
||||
actual = await actual
|
||||
if actual == expected:
|
||||
return
|
||||
attempts += 1
|
||||
if asyncio.get_event_loop().time() - start_time > 5:
|
||||
raise TimeoutError(f"Timed out after 10 seconds. Last actual was: {actual}")
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
|
||||
async def setup_ws(
|
||||
target: Union[Page, Frame],
|
||||
server: Server,
|
||||
protocol: Union[Literal["blob"], Literal["arraybuffer"]],
|
||||
) -> None:
|
||||
await target.goto(server.EMPTY_PAGE)
|
||||
await 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:' + await event.data.text();
|
||||
else
|
||||
data = 'arraybuffer:' + await (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},
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_with_ws_close(page: Page, server: Server) -> None:
|
||||
future: asyncio.Future[WebSocketRoute] = asyncio.Future()
|
||||
|
||||
def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
ws.connect_to_server()
|
||||
future.set_result(ws)
|
||||
|
||||
await page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
|
||||
ws_task = server.wait_for_web_socket()
|
||||
await setup_ws(page, server, "blob")
|
||||
ws = await ws_task
|
||||
|
||||
route = await future
|
||||
route.send("hello")
|
||||
await assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=hello origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
|
||||
closed_promise: asyncio.Future[Tuple[int, str]] = asyncio.Future()
|
||||
ws.events.once(
|
||||
"close", lambda code, reason: closed_promise.set_result((code, reason))
|
||||
)
|
||||
await route.close(code=3009, reason="oops")
|
||||
await 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 await closed_promise == (3009, "oops")
|
||||
|
||||
|
||||
async def test_should_pattern_match(page: Page, server: Server) -> None:
|
||||
await page.route_web_socket(
|
||||
re.compile(r".*/ws$"), lambda ws: ws.connect_to_server()
|
||||
)
|
||||
await page.route_web_socket(
|
||||
"**/mock-ws", lambda ws: ws.on_message(lambda message: ws.send("mock-response"))
|
||||
)
|
||||
|
||||
ws_task = server.wait_for_web_socket()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await 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 = await ws_task
|
||||
ws.events.on("message", lambda payload, isBinary: ws.sendMessage(b"response"))
|
||||
|
||||
await page.evaluate("window.ws1.send('request')")
|
||||
await assert_equal(lambda: page.evaluate("window.log"), ["ws1:response"])
|
||||
|
||||
await page.evaluate("window.ws2.send('request')")
|
||||
await assert_equal(
|
||||
lambda: page.evaluate("window.log"), ["ws1:response", "ws2:mock-response"]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_with_server(page: Page, server: Server) -> None:
|
||||
future: asyncio.Future[WebSocketRoute] = asyncio.Future()
|
||||
|
||||
async 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")
|
||||
future.set_result(ws)
|
||||
|
||||
await page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
ws_task = server.wait_for_web_socket()
|
||||
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)
|
||||
|
||||
await setup_ws(page, server, "blob")
|
||||
ws = await ws_task
|
||||
await assert_equal(lambda: log, ["message: fake"])
|
||||
|
||||
ws.sendMessage(b"to-modify")
|
||||
ws.sendMessage(b"to-block")
|
||||
ws.sendMessage(b"pass-server")
|
||||
await 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=",
|
||||
],
|
||||
)
|
||||
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.ws.send('to-respond');
|
||||
window.ws.send('to-modify');
|
||||
window.ws.send('to-block');
|
||||
window.ws.send('pass-client');
|
||||
}"""
|
||||
)
|
||||
await assert_equal(
|
||||
lambda: log, ["message: fake", "message: modified", "message: pass-client"]
|
||||
)
|
||||
await 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=",
|
||||
],
|
||||
)
|
||||
|
||||
route = await future
|
||||
route.send("another")
|
||||
await 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=",
|
||||
],
|
||||
)
|
||||
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.ws.send('pass-client-2');
|
||||
}"""
|
||||
)
|
||||
await assert_equal(
|
||||
lambda: log,
|
||||
[
|
||||
"message: fake",
|
||||
"message: modified",
|
||||
"message: pass-client",
|
||||
"message: pass-client-2",
|
||||
],
|
||||
)
|
||||
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
window.ws.close(3009, 'problem');
|
||||
}"""
|
||||
)
|
||||
await assert_equal(
|
||||
lambda: log,
|
||||
[
|
||||
"message: fake",
|
||||
"message: modified",
|
||||
"message: pass-client",
|
||||
"message: pass-client-2",
|
||||
"close: code=3009 reason=problem",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_without_server(page: Page, server: Server) -> None:
|
||||
future: asyncio.Future[WebSocketRoute] = asyncio.Future()
|
||||
|
||||
async 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)
|
||||
future.set_result(ws)
|
||||
|
||||
await page.route_web_socket(re.compile(".*"), _handle_ws)
|
||||
await setup_ws(page, server, "blob")
|
||||
|
||||
await page.evaluate(
|
||||
"""async () => {
|
||||
await window.wsOpened;
|
||||
window.ws.send('to-respond');
|
||||
window.ws.send('to-block');
|
||||
window.ws.send('to-respond');
|
||||
}"""
|
||||
)
|
||||
|
||||
await 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=",
|
||||
],
|
||||
)
|
||||
|
||||
route = await future
|
||||
route.send("another")
|
||||
# wait for the message to be processed
|
||||
await page.wait_for_timeout(100)
|
||||
await route.close(code=3008, reason="oops")
|
||||
await 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",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_with_base_url(browser: Browser, server: Server) -> None:
|
||||
context = await browser.new_context(base_url=f"http://localhost:{server.PORT}")
|
||||
page = await context.new_page()
|
||||
|
||||
async def _handle_ws(ws: WebSocketRoute) -> None:
|
||||
ws.on_message(lambda message: ws.send(message))
|
||||
|
||||
await page.route_web_socket("/ws", _handle_ws)
|
||||
await setup_ws(page, server, "blob")
|
||||
|
||||
await page.evaluate(
|
||||
"""async () => {
|
||||
await window.wsOpened;
|
||||
window.ws.send('echo');
|
||||
}"""
|
||||
)
|
||||
|
||||
await assert_equal(
|
||||
lambda: page.evaluate("window.log"),
|
||||
[
|
||||
"open",
|
||||
f"message: data=echo origin=ws://localhost:{server.PORT} lastEventId=",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
async 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
|
||||
await page.route_web_socket(f"ws://localhost:{server.PORT}", handle_ws)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await 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},
|
||||
)
|
||||
|
||||
await assert_equal(
|
||||
lambda: page.evaluate("window.ws.readyState"), 1 # WebSocket.OPEN
|
||||
)
|
||||
await page.evaluate("window.ws.send('query')")
|
||||
await assert_equal(lambda: log, ["query"])
|
||||
await assert_equal(lambda: page.evaluate("window.log"), ["response"])
|
||||
@@ -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 asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Page, ScreencastFrame
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_expose_screencast_property(page: Page) -> None:
|
||||
assert page.screencast is page.screencast
|
||||
|
||||
|
||||
async def test_start_should_deliver_frames_via_callback(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
received: list = []
|
||||
event = asyncio.Event()
|
||||
|
||||
def on_frame(frame: ScreencastFrame) -> None:
|
||||
received.append(frame["data"])
|
||||
event.set()
|
||||
|
||||
await page.screencast.start(on_frame=on_frame)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await 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):
|
||||
await page.evaluate(
|
||||
"() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))"
|
||||
)
|
||||
await page.screenshot()
|
||||
await asyncio.wait_for(event.wait(), timeout=10)
|
||||
await page.screencast.stop()
|
||||
assert len(received) >= 1
|
||||
assert all(isinstance(d, bytes) and len(d) > 0 for d in received)
|
||||
|
||||
|
||||
async def test_starting_twice_should_throw(page: Page) -> None:
|
||||
await page.screencast.start(on_frame=lambda f: None)
|
||||
try:
|
||||
with pytest.raises(Exception, match="already started"):
|
||||
await page.screencast.start(on_frame=lambda f: None)
|
||||
finally:
|
||||
await page.screencast.stop()
|
||||
|
||||
|
||||
async def test_show_overlays_and_overlay_apis_should_not_throw(page: Page) -> None:
|
||||
await page.screencast.start(on_frame=lambda f: None)
|
||||
try:
|
||||
await page.screencast.show_overlay("<div>hello</div>", duration=100)
|
||||
await page.screencast.show_chapter("ch", description="desc", duration=100)
|
||||
await page.screencast.hide_overlays()
|
||||
await page.screencast.show_overlays()
|
||||
await page.screencast.show_actions(duration=100, position="top-right")
|
||||
await page.screencast.hide_actions()
|
||||
finally:
|
||||
await page.screencast.stop()
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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 Callable
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from playwright.async_api import Page
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
def assert_image_file_format(path: Path, image_format: str) -> None:
|
||||
with Image.open(path) as img:
|
||||
assert img.format == image_format
|
||||
|
||||
|
||||
async def test_should_screenshot_with_mask(
|
||||
page: Page, server: Server, assert_to_be_golden: Callable[[bytes, str], None]
|
||||
) -> None:
|
||||
await page.set_viewport_size(
|
||||
{
|
||||
"width": 500,
|
||||
"height": 500,
|
||||
}
|
||||
)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
assert_to_be_golden(
|
||||
await page.screenshot(mask=[page.locator("div").nth(5)]),
|
||||
"mask-should-work-with-page.png",
|
||||
)
|
||||
assert_to_be_golden(
|
||||
await page.locator("body").screenshot(mask=[page.locator("div").nth(5)]),
|
||||
"mask-should-work-with-locator.png",
|
||||
)
|
||||
assert_to_be_golden(
|
||||
await must(await page.query_selector("body")).screenshot(
|
||||
mask=[page.locator("div").nth(5)]
|
||||
),
|
||||
"mask-should-work-with-element-handle.png",
|
||||
)
|
||||
|
||||
|
||||
async def test_should_infer_screenshot_type_from_path(
|
||||
page: Page, tmp_path: Path
|
||||
) -> None:
|
||||
output_png_file = tmp_path / "foo.png"
|
||||
await page.screenshot(path=output_png_file)
|
||||
assert_image_file_format(output_png_file, "PNG")
|
||||
|
||||
output_jpeg_file = tmp_path / "bar.jpeg"
|
||||
await page.screenshot(path=output_jpeg_file)
|
||||
assert_image_file_format(output_jpeg_file, "JPEG")
|
||||
|
||||
output_jpg_file = tmp_path / "bar.jpg"
|
||||
await page.screenshot(path=output_jpg_file)
|
||||
assert_image_file_format(output_jpg_file, "JPEG")
|
||||
|
||||
|
||||
async def test_should_screenshot_with_type_argument(page: Page, tmp_path: Path) -> None:
|
||||
output_jpeg_with_png_extension = tmp_path / "foo_jpeg.png"
|
||||
await page.screenshot(path=output_jpeg_with_png_extension, type="jpeg")
|
||||
assert_image_file_format(output_jpeg_with_png_extension, "JPEG")
|
||||
|
||||
output_png_with_jpeg_extension = tmp_path / "bar_png.jpeg"
|
||||
await page.screenshot(path=output_png_with_jpeg_extension, type="png")
|
||||
assert_image_file_format(output_png_with_jpeg_extension, "PNG")
|
||||
@@ -0,0 +1,50 @@
|
||||
# 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.async_api import Error, Page, Playwright
|
||||
|
||||
|
||||
async def test_should_use_data_test_id_in_strict_errors(
|
||||
page: Page, playwright: Playwright
|
||||
) -> None:
|
||||
playwright.selectors.set_test_id_attribute("data-custom-id")
|
||||
try:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div>
|
||||
<div></div>
|
||||
<div>
|
||||
<div></div>
|
||||
<div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class='foo bar:0' data-custom-id='One'>
|
||||
</div>
|
||||
<div class='foo bar:1' data-custom-id='Two'>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.locator(".foo").hover()
|
||||
assert "strict mode violation" in exc_info.value.message
|
||||
assert '<div class="foo bar:0' in exc_info.value.message
|
||||
assert '<div class="foo bar:1' in exc_info.value.message
|
||||
assert 'aka get_by_test_id("One")' in exc_info.value.message
|
||||
assert 'aka get_by_test_id("Two")' in exc_info.value.message
|
||||
finally:
|
||||
playwright.selectors.set_test_id_attribute("data-testid")
|
||||
@@ -0,0 +1,218 @@
|
||||
# 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.async_api import Page, expect
|
||||
|
||||
|
||||
async def test_get_by_escaping(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<label id=label for=control>Hello my
|
||||
wo"rld</label><input id=control />"""
|
||||
)
|
||||
await page.eval_on_selector(
|
||||
"input",
|
||||
"""input => {
|
||||
input.setAttribute('placeholder', 'hello my\\nwo"rld');
|
||||
input.setAttribute('title', 'hello my\\nwo"rld');
|
||||
input.setAttribute('alt', 'hello my\\nwo"rld');
|
||||
}""",
|
||||
)
|
||||
await expect(page.get_by_text('hello my\nwo"rld')).to_have_attribute("id", "label")
|
||||
await expect(page.get_by_text('hello my wo"rld')).to_have_attribute(
|
||||
"id", "label"
|
||||
)
|
||||
await expect(page.get_by_label('hello my\nwo"rld')).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_placeholder('hello my\nwo"rld')).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_alt_text('hello my\nwo"rld')).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_title('hello my\nwo"rld')).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<label id=label for=control>Hello my
|
||||
world</label><input id=control />"""
|
||||
)
|
||||
await page.eval_on_selector(
|
||||
"input",
|
||||
"""input => {
|
||||
input.setAttribute('placeholder', 'hello my\\nworld');
|
||||
input.setAttribute('title', 'hello my\\nworld');
|
||||
input.setAttribute('alt', 'hello my\\nworld');
|
||||
}""",
|
||||
)
|
||||
await expect(page.get_by_text("hello my\nworld")).to_have_attribute("id", "label")
|
||||
await expect(page.get_by_text("hello my world")).to_have_attribute(
|
||||
"id", "label"
|
||||
)
|
||||
await expect(page.get_by_label("hello my\nworld")).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_placeholder("hello my\nworld")).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_alt_text("hello my\nworld")).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
await expect(page.get_by_title("hello my\nworld")).to_have_attribute(
|
||||
"id", "control"
|
||||
)
|
||||
|
||||
await page.set_content("""<div id=target title="my title">Text here</div>""")
|
||||
await expect(page.get_by_title("my title", exact=True)).to_have_count(
|
||||
1, timeout=500
|
||||
)
|
||||
await expect(page.get_by_title("my t\\itle", exact=True)).to_have_count(
|
||||
0, timeout=500
|
||||
)
|
||||
await expect(page.get_by_title("my t\\\\itle", exact=True)).to_have_count(
|
||||
0, timeout=500
|
||||
)
|
||||
|
||||
await page.set_content(
|
||||
"""<label for=target>foo >> bar</label><input id=target>"""
|
||||
)
|
||||
await page.eval_on_selector(
|
||||
"input",
|
||||
"""input => {
|
||||
input.setAttribute('placeholder', 'foo >> bar');
|
||||
input.setAttribute('title', 'foo >> bar');
|
||||
input.setAttribute('alt', 'foo >> bar');
|
||||
}""",
|
||||
)
|
||||
assert await page.get_by_text("foo >> bar").text_content() == "foo >> bar"
|
||||
await expect(page.locator("label")).to_have_text("foo >> bar")
|
||||
await expect(page.get_by_text("foo >> bar")).to_have_text("foo >> bar")
|
||||
assert (
|
||||
await page.get_by_text(re.compile("foo >> bar")).text_content() == "foo >> bar"
|
||||
)
|
||||
await expect(page.get_by_label("foo >> bar")).to_have_attribute("id", "target")
|
||||
await expect(page.get_by_label(re.compile("foo >> bar"))).to_have_attribute(
|
||||
"id", "target"
|
||||
)
|
||||
await expect(page.get_by_placeholder("foo >> bar")).to_have_attribute(
|
||||
"id", "target"
|
||||
)
|
||||
await expect(page.get_by_alt_text("foo >> bar")).to_have_attribute("id", "target")
|
||||
await expect(page.get_by_title("foo >> bar")).to_have_attribute("id", "target")
|
||||
await expect(page.get_by_placeholder(re.compile("foo >> bar"))).to_have_attribute(
|
||||
"id", "target"
|
||||
)
|
||||
await expect(page.get_by_alt_text(re.compile("foo >> bar"))).to_have_attribute(
|
||||
"id", "target"
|
||||
)
|
||||
await expect(page.get_by_title(re.compile("foo >> bar"))).to_have_attribute(
|
||||
"id", "target"
|
||||
)
|
||||
|
||||
|
||||
async def test_get_by_role_escaping(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<a href="https://playwright.dev">issues 123</a>
|
||||
<a href="https://playwright.dev">he llo 56</a>
|
||||
<button>Click me</button>
|
||||
"""
|
||||
)
|
||||
assert await page.get_by_role("button").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"<button>Click me</button>",
|
||||
]
|
||||
assert await page.get_by_role("link").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"""<a href="https://playwright.dev">issues 123</a>""",
|
||||
"""<a href="https://playwright.dev">he llo 56</a>""",
|
||||
]
|
||||
|
||||
assert await page.get_by_role("link", name="issues 123").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"""<a href="https://playwright.dev">issues 123</a>""",
|
||||
]
|
||||
assert await page.get_by_role("link", name="sues").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"""<a href="https://playwright.dev">issues 123</a>""",
|
||||
]
|
||||
assert await page.get_by_role("link", name=" he \n llo ").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"""<a href="https://playwright.dev">he llo 56</a>""",
|
||||
]
|
||||
assert (
|
||||
await page.get_by_role("button", name="issues").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
)
|
||||
== []
|
||||
)
|
||||
|
||||
assert (
|
||||
await page.get_by_role("link", name="sues", exact=True).evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert await page.get_by_role(
|
||||
"link", name=" he \n llo 56 ", exact=True
|
||||
).evaluate_all("els => els.map(e => e.outerHTML)") == [
|
||||
"""<a href="https://playwright.dev">he llo 56</a>""",
|
||||
]
|
||||
|
||||
assert await page.get_by_role("button", name="Click me", exact=True).evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
) == [
|
||||
"<button>Click me</button>",
|
||||
]
|
||||
assert (
|
||||
await page.get_by_role("button", name="Click \\me", exact=True).evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert (
|
||||
await page.get_by_role("button", name="Click \\\\me", exact=True).evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
)
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
async def test_include_hidden_should_work(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content("""<button style="display: none">Hidden</button>""")
|
||||
assert (
|
||||
await page.get_by_role("button", name="Hidden").evaluate_all(
|
||||
"els => els.map(e => e.outerHTML)"
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert await page.get_by_role(
|
||||
"button", name="Hidden", include_hidden=True
|
||||
).evaluate_all("els => els.map(e => e.outerHTML)") == [
|
||||
"""<button style="display: none">Hidden</button>""",
|
||||
]
|
||||
@@ -0,0 +1,82 @@
|
||||
# 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._impl._browser import Browser
|
||||
from playwright._impl._errors import Error
|
||||
from playwright._impl._selectors import Selectors
|
||||
from playwright.async_api import Page
|
||||
|
||||
|
||||
async def test_should_work_with_internal_and(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div class=foo>hello</div><div class=bar>world</div>
|
||||
<span class=foo>hello2</span><span class=bar>world2</span>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'div >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == []
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'div >> internal:and=".foo"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello"]
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'div >> internal:and=".bar"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["world"]
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'span >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello2", "world2"]
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'.foo >> internal:and="div"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["hello"]
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
'.bar >> internal:and="span"', "els => els.map(e => e.textContent)"
|
||||
)
|
||||
) == ["world2"]
|
||||
|
||||
|
||||
async def test_should_throw_already_registered_error_when_registering(
|
||||
selectors: Selectors,
|
||||
browser: Browser,
|
||||
) -> None:
|
||||
create_tag_selector = """
|
||||
() => ({
|
||||
query(root, selector) {
|
||||
return root.querySelector(selector);
|
||||
},
|
||||
queryAll(root, selector) {
|
||||
return Array.from(root.querySelectorAll(selector));
|
||||
}
|
||||
})
|
||||
"""
|
||||
name = f"alreadyRegistered-{browser.browser_type.name}"
|
||||
await selectors.register(name, create_tag_selector)
|
||||
with pytest.raises(
|
||||
Error,
|
||||
match=f'Selectors.register: "{name}" selector engine has been already registered',
|
||||
):
|
||||
await selectors.register(name, create_tag_selector)
|
||||
@@ -0,0 +1,283 @@
|
||||
# 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.async_api import Error, Page, expect
|
||||
|
||||
|
||||
async def test_has_text_and_internal_text_should_match_full_node_text_in_strict_mode(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div id=div1>hello<span>world</span></div>
|
||||
<div id=div2>hello</div>
|
||||
"""
|
||||
)
|
||||
await expect(page.get_by_text("helloworld", exact=True)).to_have_id("div1")
|
||||
await expect(page.get_by_text("hello", exact=True)).to_have_id("div2")
|
||||
await expect(page.locator("div", has_text=re.compile("^helloworld$"))).to_have_id(
|
||||
"div1"
|
||||
)
|
||||
await expect(page.locator("div", has_text=re.compile("^hello$"))).to_have_id("div2")
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<div id=div1><span id=span1>hello</span>world</div>
|
||||
<div id=div2><span id=span2>hello</span></div>
|
||||
"""
|
||||
)
|
||||
await expect(page.get_by_text("helloworld", exact=True)).to_have_id("div1")
|
||||
assert await page.get_by_text("hello", exact=True).evaluate_all(
|
||||
"els => els.map(e => e.id)"
|
||||
) == ["span1", "span2"]
|
||||
await expect(page.locator("div", has_text=re.compile("^helloworld$"))).to_have_id(
|
||||
"div1"
|
||||
)
|
||||
await expect(page.locator("div", has_text=re.compile("^hello$"))).to_have_id("div2")
|
||||
|
||||
|
||||
async def test_should_work(page: Page) -> None:
|
||||
await page.set_content(
|
||||
"""
|
||||
<div>yo</div><div>ya</div><div>\nye </div>
|
||||
"""
|
||||
)
|
||||
assert await page.eval_on_selector("text=ya", "e => e.outerHTML") == "<div>ya</div>"
|
||||
assert (
|
||||
await page.eval_on_selector('text="ya"', "e => e.outerHTML") == "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/^[ay]+$/", "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/Ya/i", "e => e.outerHTML") == "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=ye", "e => e.outerHTML")
|
||||
== "<div>\nye </div>"
|
||||
)
|
||||
assert ">\nye </div>" in await page.get_by_text("ye").evaluate("e => e.outerHTML")
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<div> ye </div><div>ye</div>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="ye"', "e => e.outerHTML")
|
||||
== "<div> ye </div>"
|
||||
)
|
||||
assert "> ye </div>" in await page.get_by_text("ye", exact=True).first.evaluate(
|
||||
"e => e.outerHTML"
|
||||
)
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<div>yo</div><div>"ya</div><div> hello world! </div>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="\\"ya"', "e => e.outerHTML")
|
||||
== '<div>"ya</div>'
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/hello/", "e => e.outerHTML")
|
||||
== "<div> hello world! </div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/^\\s*heLLo/i", "e => e.outerHTML")
|
||||
== "<div> hello world! </div>"
|
||||
)
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<div>yo<div>ya</div>hey<div>hey</div></div>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=hey", "e => e.outerHTML") == "<div>hey</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text=yo>>text="ya"', "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text=yo>> text="ya"', "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=yo >>text='ya'", "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=yo >> text='ya'", "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("'yo'>>\"ya\"", "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("\"yo\" >> 'ya'", "e => e.outerHTML")
|
||||
== "<div>ya</div>"
|
||||
)
|
||||
|
||||
await page.set_content(
|
||||
"""
|
||||
<div>yo<span id="s1"></span></div><div>yo<span id="s2"></span><span id="s3"></span></div>
|
||||
"""
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"text=yo", "es => es.map(e => e.outerHTML).join('\\n')"
|
||||
)
|
||||
== '<div>yo<span id="s1"></span></div>\n<div>yo<span id="s2"></span><span id="s3"></span></div>'
|
||||
)
|
||||
|
||||
await page.set_content("<div>'</div><div>\"</div><div>\\</div><div>x</div>")
|
||||
assert (
|
||||
await page.eval_on_selector("text='\\''", "e => e.outerHTML") == "<div>'</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text='\"'", "e => e.outerHTML") == '<div>"</div>'
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="\\""', "e => e.outerHTML") == '<div>"</div>'
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="\'"', "e => e.outerHTML") == "<div>'</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="\\x"', "e => e.outerHTML") == "<div>x</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text='\\x'", "e => e.outerHTML") == "<div>x</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text='\\\\'", "e => e.outerHTML")
|
||||
== "<div>\\</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="\\\\"', "e => e.outerHTML")
|
||||
== "<div>\\</div>"
|
||||
)
|
||||
assert await page.eval_on_selector('text="', "e => e.outerHTML") == '<div>"</div>'
|
||||
assert await page.eval_on_selector("text='", "e => e.outerHTML") == "<div>'</div>"
|
||||
assert await page.eval_on_selector('"x"', "e => e.outerHTML") == "<div>x</div>"
|
||||
assert await page.eval_on_selector("'x'", "e => e.outerHTML") == "<div>x</div>"
|
||||
with pytest.raises(Error):
|
||||
await page.query_selector_all('"')
|
||||
with pytest.raises(Error):
|
||||
await page.query_selector_all("'")
|
||||
|
||||
await page.set_content("<div> ' </div><div> \" </div>")
|
||||
assert await page.eval_on_selector('text="', "e => e.outerHTML") == '<div> " </div>'
|
||||
assert await page.eval_on_selector("text='", "e => e.outerHTML") == "<div> ' </div>"
|
||||
|
||||
await page.set_content("<div>Hi''>>foo=bar</div>")
|
||||
assert (
|
||||
await page.eval_on_selector("text=\"Hi''>>foo=bar\"", "e => e.outerHTML")
|
||||
== "<div>Hi''>>foo=bar</div>"
|
||||
)
|
||||
await page.set_content("<div>Hi'\">>foo=bar</div>")
|
||||
assert (
|
||||
await page.eval_on_selector('text="Hi\'\\">>foo=bar"', "e => e.outerHTML")
|
||||
== "<div>Hi'\">>foo=bar</div>"
|
||||
)
|
||||
|
||||
await page.set_content("<div>Hi>><span></span></div>")
|
||||
assert (
|
||||
await page.eval_on_selector('text="Hi>>">>span', "e => e.outerHTML")
|
||||
== "<span></span>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/Hi\\>\\>/ >> span", "e => e.outerHTML")
|
||||
== "<span></span>"
|
||||
)
|
||||
|
||||
await page.set_content("<div>a<br>b</div><div>a</div>")
|
||||
assert (
|
||||
await page.eval_on_selector("text=a", "e => e.outerHTML") == "<div>a<br>b</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=b", "e => e.outerHTML") == "<div>a<br>b</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=ab", "e => e.outerHTML")
|
||||
== "<div>a<br>b</div>"
|
||||
)
|
||||
assert await page.query_selector("text=abc") is None
|
||||
assert await page.eval_on_selector_all("text=a", "els => els.length") == 2
|
||||
assert await page.eval_on_selector_all("text=b", "els => els.length") == 1
|
||||
assert await page.eval_on_selector_all("text=ab", "els => els.length") == 1
|
||||
assert await page.eval_on_selector_all("text=abc", "els => els.length") == 0
|
||||
|
||||
await page.set_content("<div></div><span></span>")
|
||||
await page.eval_on_selector(
|
||||
"div",
|
||||
"""div => {
|
||||
div.appendChild(document.createTextNode('hello'))
|
||||
div.appendChild(document.createTextNode('world'))
|
||||
}""",
|
||||
)
|
||||
await page.eval_on_selector(
|
||||
"span",
|
||||
"""span => {
|
||||
span.appendChild(document.createTextNode('hello'))
|
||||
span.appendChild(document.createTextNode('world'))
|
||||
}""",
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=lowo", "e => e.outerHTML")
|
||||
== "<div>helloworld</div>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector_all(
|
||||
"text=lowo", "els => els.map(e => e.outerHTML).join('')"
|
||||
)
|
||||
== "<div>helloworld</div><span>helloworld</span>"
|
||||
)
|
||||
|
||||
await page.set_content("<span>Sign in</span><span>Hello\n \nworld</span>")
|
||||
assert (
|
||||
await page.eval_on_selector("text=Sign in", "e => e.outerHTML")
|
||||
== "<span>Sign in</span>"
|
||||
)
|
||||
assert len((await page.query_selector_all("text=Sign \tin"))) == 1
|
||||
assert len((await page.query_selector_all('text="Sign in"'))) == 1
|
||||
assert (
|
||||
await page.eval_on_selector("text=lo wo", "e => e.outerHTML")
|
||||
== "<span>Hello\n \nworld</span>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector('text="Hello world"', "e => e.outerHTML")
|
||||
== "<span>Hello\n \nworld</span>"
|
||||
)
|
||||
assert await page.query_selector('text="lo wo"') is None
|
||||
assert len((await page.query_selector_all("text=lo \nwo"))) == 1
|
||||
assert len(await page.query_selector_all('text="lo \nwo"')) == 0
|
||||
|
||||
await page.set_content("<div>let's<span>hello</span></div>")
|
||||
assert (
|
||||
await page.eval_on_selector("text=/let's/i >> span", "e => e.outerHTML")
|
||||
== "<span>hello</span>"
|
||||
)
|
||||
assert (
|
||||
await page.eval_on_selector("text=/let\\'s/i >> span", "e => e.outerHTML")
|
||||
== "<span>hello</span>"
|
||||
)
|
||||
@@ -0,0 +1,237 @@
|
||||
# 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 typing import AsyncGenerator, Optional, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, BrowserContext, ElementHandle, JSHandle, Page
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def context(browser: Browser) -> AsyncGenerator[BrowserContext, None]:
|
||||
context = await browser.new_context(has_touch=True)
|
||||
yield context
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_should_send_all_of_the_correct_events(page: Page) -> None:
|
||||
await 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>
|
||||
"""
|
||||
)
|
||||
await page.tap("#a")
|
||||
element_handle = await track_events(await page.query_selector("#b"))
|
||||
await page.tap("#b")
|
||||
assert await element_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
"mouseover",
|
||||
"mouseenter",
|
||||
"mousemove",
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"click",
|
||||
]
|
||||
|
||||
|
||||
async def test_should_not_send_mouse_events_touchstart_is_canceled(page: Page) -> None:
|
||||
await page.set_content("hello world")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
// touchstart is not cancelable unless passive is false
|
||||
document.addEventListener('touchstart', t => t.preventDefault(), {passive: false});
|
||||
}"""
|
||||
)
|
||||
events_handle = await track_events(await page.query_selector("body"))
|
||||
await page.tap("body")
|
||||
assert await events_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
]
|
||||
|
||||
|
||||
async def test_should_not_send_mouse_events_touchend_is_canceled(page: Page) -> None:
|
||||
await page.set_content("hello world")
|
||||
await page.evaluate(
|
||||
"""() => {
|
||||
// touchstart is not cancelable unless passive is false
|
||||
document.addEventListener('touchend', t => t.preventDefault());
|
||||
}"""
|
||||
)
|
||||
events_handle = await track_events(await page.query_selector("body"))
|
||||
await page.tap("body")
|
||||
assert await events_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
]
|
||||
|
||||
|
||||
async def test_should_work_with_modifiers(page: Page) -> None:
|
||||
await page.set_content("hello world")
|
||||
alt_key_promise = asyncio.create_task(
|
||||
page.evaluate(
|
||||
"""() => new Promise(resolve => {
|
||||
document.addEventListener('touchstart', event => {
|
||||
resolve(event.altKey);
|
||||
}, {passive: false});
|
||||
})"""
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0) # make sure the evals hit the page
|
||||
await page.evaluate("""() => void 0""")
|
||||
await page.tap("body", modifiers=["Alt"])
|
||||
assert await alt_key_promise is True
|
||||
|
||||
|
||||
async def test_should_send_well_formed_touch_points(page: Page) -> None:
|
||||
promises = asyncio.gather(
|
||||
page.evaluate(
|
||||
"""() => new Promise(resolve => {
|
||||
document.addEventListener('touchstart', event => {
|
||||
resolve([...event.touches].map(t => ({
|
||||
identifier: t.identifier,
|
||||
clientX: t.clientX,
|
||||
clientY: t.clientY,
|
||||
pageX: t.pageX,
|
||||
pageY: t.pageY,
|
||||
radiusX: 'radiusX' in t ? t.radiusX : t['webkitRadiusX'],
|
||||
radiusY: 'radiusY' in t ? t.radiusY : t['webkitRadiusY'],
|
||||
rotationAngle: 'rotationAngle' in t ? t.rotationAngle : t['webkitRotationAngle'],
|
||||
force: 'force' in t ? t.force : t['webkitForce'],
|
||||
})));
|
||||
}, false);
|
||||
})"""
|
||||
),
|
||||
page.evaluate(
|
||||
"""() => new Promise(resolve => {
|
||||
document.addEventListener('touchend', event => {
|
||||
resolve([...event.touches].map(t => ({
|
||||
identifier: t.identifier,
|
||||
clientX: t.clientX,
|
||||
clientY: t.clientY,
|
||||
pageX: t.pageX,
|
||||
pageY: t.pageY,
|
||||
radiusX: 'radiusX' in t ? t.radiusX : t['webkitRadiusX'],
|
||||
radiusY: 'radiusY' in t ? t.radiusY : t['webkitRadiusY'],
|
||||
rotationAngle: 'rotationAngle' in t ? t.rotationAngle : t['webkitRotationAngle'],
|
||||
force: 'force' in t ? t.force : t['webkitForce'],
|
||||
})));
|
||||
}, false);
|
||||
})"""
|
||||
),
|
||||
)
|
||||
# make sure the evals hit the page
|
||||
await page.evaluate("""() => void 0""")
|
||||
await page.touchscreen.tap(40, 60)
|
||||
[touchstart, touchend] = await promises
|
||||
assert touchstart == [
|
||||
{
|
||||
"clientX": 40,
|
||||
"clientY": 60,
|
||||
"force": 1,
|
||||
"identifier": 0,
|
||||
"pageX": 40,
|
||||
"pageY": 60,
|
||||
"radiusX": 1,
|
||||
"radiusY": 1,
|
||||
"rotationAngle": 0,
|
||||
}
|
||||
]
|
||||
assert touchend == []
|
||||
|
||||
|
||||
async def test_should_wait_until_an_element_is_visible_to_tap_it(page: Page) -> None:
|
||||
div = cast(
|
||||
ElementHandle,
|
||||
await page.evaluate_handle(
|
||||
"""() => {
|
||||
const button = document.createElement('button');
|
||||
button.textContent = 'not clicked';
|
||||
document.body.appendChild(button);
|
||||
button.style.display = 'none';
|
||||
return button;
|
||||
}"""
|
||||
),
|
||||
)
|
||||
tap_promise = asyncio.create_task(div.tap())
|
||||
await asyncio.sleep(0) # issue tap
|
||||
await div.evaluate("""div => div.onclick = () => div.textContent = 'clicked'""")
|
||||
await div.evaluate("""div => div.style.display = 'block'""")
|
||||
await tap_promise
|
||||
assert await div.text_content() == "clicked"
|
||||
|
||||
|
||||
async def test_locators_tap(page: Page) -> None:
|
||||
await 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>
|
||||
"""
|
||||
)
|
||||
await page.locator("#a").tap()
|
||||
element_handle = await track_events(await page.query_selector("#b"))
|
||||
await page.locator("#b").tap()
|
||||
assert await element_handle.json_value() == [
|
||||
"pointerover",
|
||||
"pointerenter",
|
||||
"pointerdown",
|
||||
"touchstart",
|
||||
"pointerup",
|
||||
"pointerout",
|
||||
"pointerleave",
|
||||
"touchend",
|
||||
"mouseover",
|
||||
"mouseenter",
|
||||
"mousemove",
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"click",
|
||||
]
|
||||
|
||||
|
||||
async def track_events(target: Optional[ElementHandle]) -> JSHandle:
|
||||
assert target
|
||||
return await 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,445 @@
|
||||
# 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
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import AsyncContextManager, Callable
|
||||
|
||||
from playwright.async_api import (
|
||||
Browser,
|
||||
BrowserContext,
|
||||
BrowserType,
|
||||
Page,
|
||||
Playwright,
|
||||
Response,
|
||||
expect,
|
||||
)
|
||||
from tests.server import Server
|
||||
|
||||
from .conftest import TraceViewerPage
|
||||
|
||||
|
||||
async def test_browser_context_output_trace(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await context.tracing.stop(path=tmp_path / "trace.zip")
|
||||
assert Path(tmp_path / "trace.zip").exists()
|
||||
|
||||
|
||||
async def test_start_stop(browser: Browser) -> None:
|
||||
context = await browser.new_context()
|
||||
await context.tracing.start()
|
||||
await context.tracing.stop()
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_browser_context_should_not_throw_when_stopping_without_start_but_not_exporting(
|
||||
context: BrowserContext,
|
||||
) -> None:
|
||||
await context.tracing.stop()
|
||||
|
||||
|
||||
async def test_browser_context_output_trace_chunk(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
button = page.locator(".box").first
|
||||
|
||||
await context.tracing.start_chunk(title="foo")
|
||||
await button.click()
|
||||
await context.tracing.stop_chunk(path=tmp_path / "trace1.zip")
|
||||
assert Path(tmp_path / "trace1.zip").exists()
|
||||
|
||||
await context.tracing.start_chunk(title="foo")
|
||||
await button.click()
|
||||
await context.tracing.stop_chunk(path=tmp_path / "trace2.zip")
|
||||
assert Path(tmp_path / "trace2.zip").exists()
|
||||
|
||||
|
||||
async def test_should_collect_sources(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start(sources=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<button>Click</button>")
|
||||
|
||||
async def my_method_outer() -> None:
|
||||
async def my_method_inner() -> None:
|
||||
await page.get_by_text("Click").click()
|
||||
|
||||
await my_method_inner()
|
||||
|
||||
await my_method_outer()
|
||||
path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=path)
|
||||
|
||||
async with show_trace_viewer(path) as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
]
|
||||
)
|
||||
await trace_viewer.show_source_tab()
|
||||
# Check that stack frames are shown (they might be anonymous in Python)
|
||||
await 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"),
|
||||
]
|
||||
)
|
||||
|
||||
await trace_viewer.select_action("Set content")
|
||||
# Check that the source file is shown
|
||||
await expect(
|
||||
trace_viewer.page.locator(".source-tab-file-name")
|
||||
).to_have_attribute("title", re.compile(r".*test_.*\.py"))
|
||||
await expect(trace_viewer.page.locator(".source-line-running")).to_contain_text(
|
||||
'page.set_content("<button>Click</button>")'
|
||||
)
|
||||
|
||||
|
||||
async def test_should_collect_trace_with_resources_but_no_js(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
await page.goto(server.PREFIX + "/frames/frame.html")
|
||||
await page.set_content("<button>Click</button>")
|
||||
await page.click('"Click"')
|
||||
await page.mouse.move(20, 20)
|
||||
await page.mouse.dblclick(30, 30)
|
||||
await page.request.get(server.EMPTY_PAGE)
|
||||
await page.keyboard.insert_text("abc")
|
||||
await page.wait_for_timeout(2000) # Give it some time to produce screenshots.
|
||||
await page.route("**/empty.html", lambda route: route.continue_())
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
await page.close()
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=trace_file_path)
|
||||
|
||||
async with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
await 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"),
|
||||
]
|
||||
)
|
||||
|
||||
await trace_viewer.select_action("Set content")
|
||||
await expect(
|
||||
trace_viewer.page.locator(".browser-frame-address-bar")
|
||||
).to_have_text(server.PREFIX + "/frames/frame.html")
|
||||
frame = await trace_viewer.snapshot_frame("Set content", 0, False)
|
||||
await expect(frame.locator("button")).to_have_text("Click")
|
||||
|
||||
|
||||
async def test_should_correctly_determine_sync_apiname(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable,
|
||||
) -> None:
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
|
||||
received_response: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handle_response(response: Response) -> None:
|
||||
await response.request.all_headers()
|
||||
await response.text()
|
||||
received_response.set_result(None)
|
||||
|
||||
page.once("response", _handle_response)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await received_response
|
||||
await page.close()
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=trace_file_path)
|
||||
|
||||
async with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/grid\.html"'),
|
||||
re.compile(r"Close"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_collect_two_traces(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<button>Click</button>")
|
||||
await page.click('"Click"')
|
||||
tracing1_path = tmp_path / "trace1.zip"
|
||||
await context.tracing.stop(path=tracing1_path)
|
||||
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
await page.dblclick('"Click"')
|
||||
await page.close()
|
||||
tracing2_path = tmp_path / "trace2.zip"
|
||||
await context.tracing.stop(path=tracing2_path)
|
||||
|
||||
async with show_trace_viewer(tracing1_path) as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/empty\.html"'),
|
||||
re.compile(r"Set content"),
|
||||
re.compile(r"Click"),
|
||||
]
|
||||
)
|
||||
|
||||
async with show_trace_viewer(tracing2_path) as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r"Double click"),
|
||||
re.compile(r"Close"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_work_with_playwright_context_managers(
|
||||
context: BrowserContext,
|
||||
page: Page,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content("<button>Click</button>")
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate('() => console.log("hello")')
|
||||
await page.click('"Click"')
|
||||
assert (await message_info.value).text == "hello"
|
||||
|
||||
async with page.expect_popup():
|
||||
await page.evaluate("window._popup = window.open(document.location.href)")
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=trace_file_path)
|
||||
|
||||
async with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
await 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"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async 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], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start(screenshots=True, snapshots=True)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.wait_for_load_state("load")
|
||||
await page.wait_for_load_state("load")
|
||||
|
||||
trace_file_path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=trace_file_path)
|
||||
|
||||
async with show_trace_viewer(trace_file_path) as trace_viewer:
|
||||
await 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"'),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_respect_traces_dir_and_name(
|
||||
browser_type: BrowserType,
|
||||
server: Server,
|
||||
tmp_path: Path,
|
||||
launch_arguments: dict,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
traces_dir = tmp_path / "traces"
|
||||
browser = await browser_type.launch(traces_dir=traces_dir, **launch_arguments)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
await context.tracing.start(name="name1", snapshots=True)
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
await context.tracing.stop_chunk(path=tmp_path / "trace1.zip")
|
||||
assert (traces_dir / "name1.trace").exists()
|
||||
assert (traces_dir / "name1.network").exists()
|
||||
|
||||
await context.tracing.start_chunk(name="name2")
|
||||
await page.goto(server.PREFIX + "/har.html")
|
||||
await context.tracing.stop(path=tmp_path / "trace2.zip")
|
||||
assert (traces_dir / "name2.trace").exists()
|
||||
assert (traces_dir / "name2.network").exists()
|
||||
|
||||
await browser.close()
|
||||
|
||||
async with show_trace_viewer(tmp_path / "trace1.zip") as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile('Navigate to "/one-style\\.html"'),
|
||||
]
|
||||
)
|
||||
frame = await trace_viewer.snapshot_frame(
|
||||
'Navigate to "/one-style.html"', 0, False
|
||||
)
|
||||
await expect(frame.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
await expect(frame.locator("body")).to_have_text("hello, world!")
|
||||
|
||||
async with show_trace_viewer(tmp_path / "trace2.zip") as trace_viewer:
|
||||
await expect(trace_viewer.action_titles).to_have_text(
|
||||
[
|
||||
re.compile(r'Navigate to "/har\.html"'),
|
||||
]
|
||||
)
|
||||
frame = await trace_viewer.snapshot_frame('Navigate to "/har.html"', 0, False)
|
||||
await expect(frame.locator("body")).to_have_css(
|
||||
"background-color", "rgb(255, 192, 203)"
|
||||
)
|
||||
await expect(frame.locator("body")).to_have_text("hello, world!")
|
||||
|
||||
|
||||
async def test_should_show_tracing_group_in_action_list(
|
||||
context: BrowserContext,
|
||||
tmp_path: Path,
|
||||
show_trace_viewer: Callable[[Path], AsyncContextManager[TraceViewerPage]],
|
||||
) -> None:
|
||||
await context.tracing.start()
|
||||
page = await context.new_page()
|
||||
|
||||
await context.tracing.group("outer group")
|
||||
await page.goto("data:text/html,<!DOCTYPE html><body><div>Hello world</div></body>")
|
||||
await context.tracing.group("inner group 1")
|
||||
await page.locator("body").click()
|
||||
await context.tracing.group_end()
|
||||
await context.tracing.group("inner group 2")
|
||||
await page.get_by_text("Hello").is_visible()
|
||||
await context.tracing.group_end()
|
||||
await context.tracing.group_end()
|
||||
|
||||
trace_path = tmp_path / "trace.zip"
|
||||
await context.tracing.stop(path=trace_path)
|
||||
|
||||
async with show_trace_viewer(trace_path) as trace_viewer:
|
||||
await trace_viewer.expand_action("inner group 1")
|
||||
await 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"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def test_should_start_and_stop_har(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
har_path = tmp_path / "test.har"
|
||||
await context.tracing.start_har(path=har_path, content="embed", mode="full")
|
||||
await page.goto(server.PREFIX + "/empty.html")
|
||||
await context.tracing.stop_har()
|
||||
await context.close()
|
||||
assert har_path.exists()
|
||||
assert har_path.stat().st_size > 0
|
||||
|
||||
|
||||
async def test_should_record_a_har_with_options(
|
||||
browser: Browser, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
# Ported from upstream tests/library/har.spec.ts.
|
||||
context = await browser.new_context()
|
||||
har_path = tmp_path / "tracing.har"
|
||||
await context.tracing.start_har(
|
||||
path=har_path, mode="minimal", url_filter="**/one-style.css"
|
||||
)
|
||||
page = await context.new_page()
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
await context.tracing.stop_har()
|
||||
await 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"]
|
||||
# Minimal mode drops body sizes.
|
||||
assert log["entries"][0]["request"]["bodySize"] == -1
|
||||
|
||||
|
||||
async def test_should_record_a_zipped_har_for_apirequestcontext(
|
||||
playwright: Playwright, server: Server, tmp_path: Path
|
||||
) -> None:
|
||||
# Ported from upstream tests/library/har.spec.ts.
|
||||
request = await playwright.request.new_context()
|
||||
har_path = tmp_path / "tracing.har.zip"
|
||||
await request.tracing.start_har(path=har_path, content="attach")
|
||||
await request.get(server.PREFIX + "/simple.json")
|
||||
await request.tracing.stop_har()
|
||||
await 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,509 @@
|
||||
# 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
|
||||
import re
|
||||
|
||||
from playwright.async_api import BrowserContext, Error, Page, Route
|
||||
from tests.server import Server
|
||||
from tests.utils import must
|
||||
|
||||
|
||||
async def test_context_unroute_should_not_wait_for_pending_handlers_to_complete(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.continue_()
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
await route.fallback()
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
await context.unroute(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
route_barrier_future.set_result(None)
|
||||
await navigation_task
|
||||
assert second_handler_called
|
||||
|
||||
|
||||
async def test_context_unroute_all_removes_all_handlers(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await context.route(
|
||||
"**/*",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
await context.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
await context.unroute_all()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
|
||||
async def test_context_unroute_all_should_not_wait_for_pending_handlers_to_complete(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.abort()
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
await route.fallback()
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
did_unroute = False
|
||||
|
||||
async def _unroute_promise() -> None:
|
||||
nonlocal did_unroute
|
||||
await context.unroute_all(behavior="wait")
|
||||
did_unroute = True
|
||||
|
||||
unroute_task = asyncio.create_task(_unroute_promise())
|
||||
await asyncio.sleep(0.5)
|
||||
assert did_unroute is False
|
||||
route_barrier_future.set_result(None)
|
||||
await unroute_task
|
||||
assert did_unroute
|
||||
await navigation_task
|
||||
assert second_handler_called is False
|
||||
|
||||
|
||||
async def test_context_unroute_all_should_not_wait_for_pending_handlers_to_complete_if_behavior_is_ignore_errors(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.abort()
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
raise Exception("Handler error")
|
||||
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
did_unroute = False
|
||||
|
||||
async def _unroute_promise() -> None:
|
||||
await context.unroute_all(behavior="ignoreErrors")
|
||||
nonlocal did_unroute
|
||||
did_unroute = True
|
||||
|
||||
unroute_task = asyncio.create_task(_unroute_promise())
|
||||
await asyncio.sleep(0.5)
|
||||
await unroute_task
|
||||
assert did_unroute
|
||||
route_barrier_future.set_result(None)
|
||||
try:
|
||||
await navigation_task
|
||||
except Error:
|
||||
pass
|
||||
# The error in the unrouted handler should be silently caught and remaining handler called.
|
||||
assert not second_handler_called
|
||||
|
||||
|
||||
async def test_page_close_should_not_wait_for_active_route_handlers_on_the_owning_context(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await context.route(
|
||||
re.compile(".*"),
|
||||
lambda route: route_future.set_result(route),
|
||||
)
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
lambda route: route.fallback(),
|
||||
)
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
await route_future
|
||||
await page.close()
|
||||
|
||||
|
||||
async def test_context_close_should_not_wait_for_active_route_handlers_on_the_owned_pages(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
lambda route: route_future.set_result(route),
|
||||
)
|
||||
await page.route(re.compile(".*"), lambda route: route.fallback())
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
await route_future
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_page_unroute_should_not_wait_for_pending_handlers_to_complete(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.continue_()
|
||||
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
await route.fallback()
|
||||
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
await page.unroute(
|
||||
re.compile(".*"),
|
||||
_handler2,
|
||||
)
|
||||
route_barrier_future.set_result(None)
|
||||
await navigation_task
|
||||
assert second_handler_called
|
||||
|
||||
|
||||
async def test_page_unroute_all_removes_all_routes(page: Page, server: Server) -> None:
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
await page.route(
|
||||
"**/empty.html",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
await page.unroute_all()
|
||||
response = must(await page.goto(server.EMPTY_PAGE))
|
||||
assert response.ok
|
||||
|
||||
|
||||
async def test_page_unroute_should_wait_for_pending_handlers_to_complete(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.abort()
|
||||
|
||||
await page.route(
|
||||
"**/*",
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
await route.fallback()
|
||||
|
||||
await page.route(
|
||||
"**/*",
|
||||
_handler2,
|
||||
)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
did_unroute = False
|
||||
|
||||
async def _unroute_promise() -> None:
|
||||
await page.unroute_all(behavior="wait")
|
||||
nonlocal did_unroute
|
||||
did_unroute = True
|
||||
|
||||
unroute_task = asyncio.create_task(_unroute_promise())
|
||||
await asyncio.sleep(0.5)
|
||||
assert did_unroute is False
|
||||
route_barrier_future.set_result(None)
|
||||
await unroute_task
|
||||
assert did_unroute
|
||||
await navigation_task
|
||||
assert second_handler_called is False
|
||||
|
||||
|
||||
async def test_page_unroute_all_should_not_wait_for_pending_handlers_to_complete_if_behavior_is_ignore_errors(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
second_handler_called = False
|
||||
|
||||
async def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
await route.abort()
|
||||
|
||||
await page.route(re.compile(".*"), _handler1)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
route_barrier_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await route_barrier_future
|
||||
raise Exception("Handler error")
|
||||
|
||||
await page.route(re.compile(".*"), _handler2)
|
||||
navigation_task = asyncio.create_task(page.goto(server.EMPTY_PAGE))
|
||||
await route_future
|
||||
did_unroute = False
|
||||
|
||||
async def _unroute_promise() -> None:
|
||||
await page.unroute_all(behavior="ignoreErrors")
|
||||
nonlocal did_unroute
|
||||
did_unroute = True
|
||||
|
||||
unroute_task = asyncio.create_task(_unroute_promise())
|
||||
await asyncio.sleep(0.5)
|
||||
await unroute_task
|
||||
assert did_unroute
|
||||
route_barrier_future.set_result(None)
|
||||
try:
|
||||
await navigation_task
|
||||
except Error:
|
||||
pass
|
||||
# The error in the unrouted handler should be silently caught.
|
||||
assert not second_handler_called
|
||||
|
||||
|
||||
async def test_page_close_does_not_wait_for_active_route_handlers(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
stalling_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
second_handler_called = False
|
||||
|
||||
def _handler1(route: Route) -> None:
|
||||
nonlocal second_handler_called
|
||||
second_handler_called = True
|
||||
|
||||
await page.route(
|
||||
"**/*",
|
||||
_handler1,
|
||||
)
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
|
||||
async def _handler2(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await stalling_future
|
||||
|
||||
await page.route(
|
||||
"**/*",
|
||||
_handler2,
|
||||
)
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
await route_future
|
||||
await page.close()
|
||||
await asyncio.sleep(0.5)
|
||||
assert not second_handler_called
|
||||
stalling_future.cancel()
|
||||
|
||||
|
||||
async def test_route_continue_should_not_throw_if_page_has_been_closed(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
lambda route: route_future.set_result(route),
|
||||
)
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
route = await route_future
|
||||
await page.close()
|
||||
# Should not throw.
|
||||
await route.continue_()
|
||||
|
||||
|
||||
async def test_route_fallback_should_not_throw_if_page_has_been_closed(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route(
|
||||
re.compile(".*"),
|
||||
lambda route: route_future.set_result(route),
|
||||
)
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
route = await route_future
|
||||
await page.close()
|
||||
# Should not throw.
|
||||
await route.fallback()
|
||||
|
||||
|
||||
async def test_route_fulfill_should_not_throw_if_page_has_been_closed(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
await page.route(
|
||||
"**/*",
|
||||
lambda route: route_future.set_result(route),
|
||||
)
|
||||
|
||||
async def _goto_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
except Error:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_goto_ignore_exceptions())
|
||||
route = await route_future
|
||||
await page.close()
|
||||
# Should not throw.
|
||||
await route.fulfill()
|
||||
|
||||
|
||||
async def test_should_not_continue_requests_in_flight_page(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await asyncio.sleep(3)
|
||||
await route.fulfill(status=200)
|
||||
|
||||
async def _evaluate_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.evaluate("() => fetch('/')")
|
||||
except Error:
|
||||
pass
|
||||
|
||||
await page.route(
|
||||
"**/*",
|
||||
handle,
|
||||
)
|
||||
|
||||
asyncio.create_task(_evaluate_ignore_exceptions())
|
||||
await route_future
|
||||
await page.unroute_all(behavior="wait")
|
||||
|
||||
|
||||
async def test_should_not_continue_requests_in_flight_context(
|
||||
page: Page, context: BrowserContext, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
|
||||
route_future: "asyncio.Future[Route]" = asyncio.Future()
|
||||
|
||||
async def handle(route: Route) -> None:
|
||||
route_future.set_result(route)
|
||||
await asyncio.sleep(3)
|
||||
await route.fulfill(status=200)
|
||||
|
||||
async def _evaluate_ignore_exceptions() -> None:
|
||||
try:
|
||||
await page.evaluate("() => fetch('/')")
|
||||
except Error:
|
||||
pass
|
||||
|
||||
await context.route(
|
||||
"**/*",
|
||||
handle,
|
||||
)
|
||||
|
||||
asyncio.create_task(_evaluate_ignore_exceptions())
|
||||
await route_future
|
||||
await context.unroute_all(behavior="wait")
|
||||
@@ -0,0 +1,86 @@
|
||||
# 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
|
||||
|
||||
from playwright.async_api import Browser, BrowserType
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_should_expose_video_path(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(record_video_dir=tmp_path)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
assert page.video
|
||||
path = await page.video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
await page.context.close()
|
||||
|
||||
|
||||
async def test_short_video_should_throw(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(record_video_dir=tmp_path)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
assert page.video
|
||||
path = await page.video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
await page.wait_for_timeout(1000)
|
||||
await page.context.close()
|
||||
assert os.path.exists(path)
|
||||
|
||||
|
||||
async def test_short_video_should_throw_persistent_context(
|
||||
browser_type: BrowserType, tmp_path: Path, launch_arguments: Dict, server: Server
|
||||
) -> None:
|
||||
context = await browser_type.launch_persistent_context(
|
||||
str(tmp_path),
|
||||
**launch_arguments,
|
||||
viewport={"width": 320, "height": 240},
|
||||
record_video_dir=str(tmp_path) + "1",
|
||||
)
|
||||
page = context.pages[0]
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await page.wait_for_timeout(1000)
|
||||
await context.close()
|
||||
|
||||
assert page.video
|
||||
path = await page.video.path()
|
||||
assert str(tmp_path) in str(path)
|
||||
|
||||
|
||||
async def test_should_not_error_if_page_not_closed_before_save_as(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page(record_video_dir=tmp_path)
|
||||
await page.goto(server.PREFIX + "/grid.html")
|
||||
await page.wait_for_timeout(1000) # make sure video has some data
|
||||
out_path = tmp_path / "some-video.webm"
|
||||
assert page.video
|
||||
saved = page.video.save_as(out_path)
|
||||
await page.close()
|
||||
await saved
|
||||
await page.context.close()
|
||||
assert os.path.exists(out_path)
|
||||
|
||||
|
||||
async def test_should_be_None_if_not_recording(
|
||||
browser: Browser, tmp_path: Path, server: Server
|
||||
) -> None:
|
||||
page = await browser.new_page()
|
||||
assert page.video is None
|
||||
await page.close()
|
||||
@@ -0,0 +1,91 @@
|
||||
# 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 datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import ConsoleMessage, Error, Page
|
||||
|
||||
|
||||
async def test_should_timeout(page: Page) -> None:
|
||||
start_time = datetime.now()
|
||||
timeout = 42
|
||||
await page.wait_for_timeout(timeout)
|
||||
assert ((datetime.now() - start_time).microseconds * 1000) >= timeout / 2
|
||||
|
||||
|
||||
async def test_should_accept_a_string(page: Page) -> None:
|
||||
watchdog = page.wait_for_function("window.__FOO === 1")
|
||||
await page.evaluate("window['__FOO'] = 1")
|
||||
await watchdog
|
||||
|
||||
|
||||
async def test_should_work_when_resolved_right_before_execution_context_disposal(
|
||||
page: Page,
|
||||
) -> None:
|
||||
await page.add_init_script("window['__RELOADED'] = true")
|
||||
await page.wait_for_function(
|
||||
"""() => {
|
||||
if (!window['__RELOADED'])
|
||||
window.location.reload();
|
||||
return true;
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
async def test_should_poll_on_interval(page: Page) -> None:
|
||||
polling = 100
|
||||
time_delta = await page.wait_for_function(
|
||||
"""() => {
|
||||
if (!window['__startTime']) {
|
||||
window['__startTime'] = Date.now();
|
||||
return false;
|
||||
}
|
||||
return Date.now() - window['__startTime'];
|
||||
}""",
|
||||
polling=polling,
|
||||
)
|
||||
assert await time_delta.json_value() >= polling
|
||||
|
||||
|
||||
async def test_should_avoid_side_effects_after_timeout(page: Page) -> None:
|
||||
counter = 0
|
||||
|
||||
async def on_console(message: ConsoleMessage) -> None:
|
||||
nonlocal counter
|
||||
counter += 1
|
||||
|
||||
page.on("console", on_console)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.wait_for_function(
|
||||
"""() => {
|
||||
window['counter'] = (window['counter'] || 0) + 1;
|
||||
console.log(window['counter']);
|
||||
}""",
|
||||
polling=1,
|
||||
timeout=1000,
|
||||
)
|
||||
|
||||
saved_counter = counter
|
||||
await page.wait_for_timeout(2000) # Give it some time to produce more logs.
|
||||
|
||||
assert "Timeout 1000ms exceeded" in exc_info.value.message
|
||||
assert counter == saved_counter
|
||||
|
||||
|
||||
async def test_should_throw_on_polling_mutation(page: Page) -> None:
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.wait_for_function("() => true", polling="mutation") # type: ignore
|
||||
assert "Unknown polling option: mutation" in exc_info.value.message
|
||||
@@ -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.
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page
|
||||
from tests.server import Server
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"url => window.location.href = url", server.PREFIX + "/grid.html"
|
||||
)
|
||||
await page.wait_for_url("**/grid.html")
|
||||
assert "grid.html" in page.url
|
||||
|
||||
|
||||
async def test_wait_for_url_should_respect_timeout(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
with pytest.raises(Error) as exc_info:
|
||||
await page.wait_for_url("**/frame.html", timeout=2500)
|
||||
assert "Timeout 2500ms exceeded" in exc_info.value.message
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_both_domcontentloaded_and_load(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.wait_for_url("**/*", wait_until="domcontentloaded")
|
||||
await page.wait_for_url("**/*", wait_until="load")
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_clicking_on_anchor_links(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content('<a href="#foobar">foobar</a>')
|
||||
await page.click("a")
|
||||
await page.wait_for_url("**/*#foobar")
|
||||
assert page.url == server.EMPTY_PAGE + "#foobar"
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_history_push_state(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<a onclick='javascript:pushState()'>SPA</a>
|
||||
<script>
|
||||
function pushState() { history.pushState({}, '', 'wow.html') }
|
||||
</script>
|
||||
"""
|
||||
)
|
||||
await page.click("a")
|
||||
await page.wait_for_url("**/wow.html")
|
||||
assert page.url == server.PREFIX + "/wow.html"
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_history_replace_state(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<a onclick='javascript:replaceState()'>SPA</a>
|
||||
<script>
|
||||
function replaceState() { history.replaceState({}, '', '/replaced.html') }
|
||||
</script>
|
||||
"""
|
||||
)
|
||||
await page.click("a")
|
||||
await page.wait_for_url("**/replaced.html")
|
||||
assert page.url == server.PREFIX + "/replaced.html"
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_dom_history_back_forward(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.set_content(
|
||||
"""
|
||||
<a id=back onclick='javascript:go_back()'>back</a>
|
||||
<a id=forward onclick='javascript:go_forward()'>forward</a>
|
||||
<script>
|
||||
function go_back() { history.back(); }
|
||||
function go_forward() { history.forward(); }
|
||||
history.pushState({}, '', '/first.html')
|
||||
history.pushState({}, '', '/second.html')
|
||||
</script>
|
||||
"""
|
||||
)
|
||||
|
||||
assert page.url == server.PREFIX + "/second.html"
|
||||
|
||||
await page.click("a#back")
|
||||
await page.wait_for_url("**/first.html")
|
||||
assert page.url == server.PREFIX + "/first.html"
|
||||
|
||||
await page.click("a#forward")
|
||||
await page.wait_for_url("**/second.html")
|
||||
assert page.url == server.PREFIX + "/second.html"
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_url_match_for_same_document_navigations(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate("history.pushState({}, '', '/first.html')")
|
||||
await page.evaluate("history.pushState({}, '', '/second.html')")
|
||||
await page.evaluate("history.pushState({}, '', '/third.html')")
|
||||
await page.wait_for_url(re.compile(r"third\.html"))
|
||||
assert "/third.html" in page.url
|
||||
|
||||
|
||||
async def test_wait_for_url_should_work_with_commit(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
await page.evaluate(
|
||||
"url => window.location.href = url", server.PREFIX + "/grid.html"
|
||||
)
|
||||
await page.wait_for_url("**/grid.html", wait_until="commit")
|
||||
assert "grid.html" in page.url
|
||||
@@ -0,0 +1,195 @@
|
||||
# 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 typing import Union
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Error, Page, WebSocket
|
||||
from tests.server import Server, WebSocketProtocol
|
||||
|
||||
|
||||
async def test_should_work(page: Page, server: Server) -> None:
|
||||
server.send_on_web_socket_connection(b"incoming")
|
||||
value = await page.evaluate(
|
||||
"""port => {
|
||||
let cb;
|
||||
const result = new Promise(f => cb = f);
|
||||
const ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
ws.addEventListener('message', data => { ws.close(); cb(data.data); });
|
||||
return result;
|
||||
}""",
|
||||
server.PORT,
|
||||
)
|
||||
assert value == "incoming"
|
||||
pass
|
||||
|
||||
|
||||
async def test_should_emit_close_events(page: Page, server: Server) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
close_future: asyncio.Future[None] = asyncio.Future()
|
||||
async with page.expect_websocket() as ws_info:
|
||||
await page.evaluate(
|
||||
"""port => {
|
||||
const ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
ws.addEventListener('open', data => ws.close());
|
||||
}""",
|
||||
server.PORT,
|
||||
)
|
||||
ws = await ws_info.value
|
||||
ws.on("close", lambda ws: close_future.set_result(None))
|
||||
assert ws.url == f"ws://localhost:{server.PORT}/ws"
|
||||
assert repr(ws) == f"<WebSocket url={ws.url!r}>"
|
||||
await close_future
|
||||
assert ws.is_closed()
|
||||
|
||||
|
||||
async def test_should_emit_frame_events(page: Page, server: Server) -> None:
|
||||
def _handle_ws_connection(ws: WebSocketProtocol) -> None:
|
||||
def _onMessage(payload: bytes, isBinary: bool) -> None:
|
||||
ws.sendMessage(b"incoming", False)
|
||||
ws.sendClose()
|
||||
|
||||
setattr(ws, "onMessage", _onMessage)
|
||||
|
||||
server.once_web_socket_connection(_handle_ws_connection)
|
||||
log = []
|
||||
socket_close_future: "asyncio.Future[None]" = asyncio.Future()
|
||||
|
||||
def on_web_socket(ws: WebSocket) -> None:
|
||||
log.append("open")
|
||||
|
||||
def _on_framesent(payload: Union[bytes, str]) -> None:
|
||||
assert isinstance(payload, str)
|
||||
log.append(f"sent<{payload}>")
|
||||
|
||||
ws.on("framesent", _on_framesent)
|
||||
|
||||
def _on_framereceived(payload: Union[bytes, str]) -> None:
|
||||
assert isinstance(payload, str)
|
||||
log.append(f"received<{payload}>")
|
||||
|
||||
ws.on("framereceived", _on_framereceived)
|
||||
|
||||
def _handle_close(ws: WebSocket) -> None:
|
||||
log.append("close")
|
||||
socket_close_future.set_result(None)
|
||||
|
||||
ws.on("close", _handle_close)
|
||||
|
||||
page.on("websocket", on_web_socket)
|
||||
async with page.expect_event("websocket"):
|
||||
await page.evaluate(
|
||||
"""port => {
|
||||
const ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
ws.addEventListener('open', () => ws.send('outgoing'));
|
||||
ws.addEventListener('message', () => ws.close())
|
||||
}""",
|
||||
server.PORT,
|
||||
)
|
||||
await socket_close_future
|
||||
assert log[0] == "open"
|
||||
assert log[3] == "close"
|
||||
log.sort()
|
||||
assert log == ["close", "open", "received<incoming>", "sent<outgoing>"]
|
||||
|
||||
|
||||
async def test_should_emit_binary_frame_events(page: Page, server: Server) -> None:
|
||||
def _handle_ws_connection(ws: WebSocketProtocol) -> None:
|
||||
ws.sendMessage(b"incoming")
|
||||
|
||||
def _onMessage(payload: bytes, isBinary: bool) -> None:
|
||||
if payload == b"echo-bin":
|
||||
ws.sendMessage(b"\x04\x02", True)
|
||||
ws.sendClose()
|
||||
if payload == b"echo-text":
|
||||
ws.sendMessage(b"text", False)
|
||||
ws.sendClose()
|
||||
|
||||
setattr(ws, "onMessage", _onMessage)
|
||||
|
||||
server.once_web_socket_connection(_handle_ws_connection)
|
||||
done_task: "asyncio.Future[None]" = asyncio.Future()
|
||||
sent = []
|
||||
received = []
|
||||
|
||||
def on_web_socket(ws: WebSocket) -> None:
|
||||
ws.on("framesent", lambda payload: sent.append(payload))
|
||||
ws.on("framereceived", lambda payload: received.append(payload))
|
||||
ws.on("close", lambda _: done_task.set_result(None))
|
||||
|
||||
page.on("websocket", on_web_socket)
|
||||
async with page.expect_event("websocket"):
|
||||
await page.evaluate(
|
||||
"""port => {
|
||||
const ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
ws.addEventListener('open', () => {
|
||||
const binary = new Uint8Array(5);
|
||||
for (let i = 0; i < 5; ++i)
|
||||
binary[i] = i;
|
||||
ws.send(binary);
|
||||
ws.send('echo-bin');
|
||||
});
|
||||
}""",
|
||||
server.PORT,
|
||||
)
|
||||
await done_task
|
||||
assert sent == [b"\x00\x01\x02\x03\x04", "echo-bin"]
|
||||
assert received == ["incoming", b"\x04\x02"]
|
||||
|
||||
|
||||
async def test_should_reject_wait_for_event_on_close_and_error(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
server.send_on_web_socket_connection(b"incoming")
|
||||
async with page.expect_event("websocket") as ws_info:
|
||||
await page.evaluate(
|
||||
"""port => {
|
||||
window.ws = new WebSocket('ws://localhost:' + port + '/ws');
|
||||
}""",
|
||||
server.PORT,
|
||||
)
|
||||
ws = await ws_info.value
|
||||
await ws.wait_for_event("framereceived")
|
||||
with pytest.raises(Error) as exc_info:
|
||||
async with ws.expect_event("framesent"):
|
||||
await page.evaluate("window.ws.close()")
|
||||
assert exc_info.value.message == "Socket closed"
|
||||
|
||||
|
||||
async def test_should_emit_error_event(
|
||||
page: Page, server: Server, browser_name: str, browser_channel: str
|
||||
) -> None:
|
||||
future: "asyncio.Future[str]" = asyncio.Future()
|
||||
|
||||
def _on_ws_socket_error(err: str) -> None:
|
||||
future.set_result(err)
|
||||
|
||||
def _on_websocket(websocket: WebSocket) -> None:
|
||||
websocket.on("socketerror", _on_ws_socket_error)
|
||||
|
||||
page.on(
|
||||
"websocket",
|
||||
_on_websocket,
|
||||
)
|
||||
await page.evaluate(
|
||||
"""port => new WebSocket(`ws://localhost:${port}/bogus-ws`)""",
|
||||
server.PORT,
|
||||
)
|
||||
err = await future
|
||||
if browser_name == "firefox":
|
||||
assert err == "CLOSE_ABNORMAL"
|
||||
else:
|
||||
assert ("" if browser_channel == "msedge" else ": 404") in err
|
||||
@@ -0,0 +1,244 @@
|
||||
# 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 asyncio.futures import Future
|
||||
|
||||
import pytest
|
||||
|
||||
from playwright.async_api import Browser, ConsoleMessage, Error, Page, Worker
|
||||
from tests.server import Server
|
||||
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
|
||||
|
||||
|
||||
async def test_workers_page_workers(page: Page, server: Server) -> None:
|
||||
async with page.expect_worker() as worker_info:
|
||||
await page.goto(server.PREFIX + "/worker/worker.html")
|
||||
worker = await worker_info.value
|
||||
assert "worker.js" in worker.url
|
||||
assert repr(worker) == f"<Worker url={worker.url!r}>"
|
||||
|
||||
assert (
|
||||
await worker.evaluate('() => self["workerFunction"]()')
|
||||
== "worker function result"
|
||||
)
|
||||
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
assert len(page.workers) == 0
|
||||
|
||||
|
||||
async def test_workers_should_emit_created_and_destroyed_events(page: Page) -> None:
|
||||
worker_obj = None
|
||||
async with page.expect_event("worker") as event_info:
|
||||
worker_obj = await page.evaluate_handle(
|
||||
"() => new Worker(URL.createObjectURL(new Blob(['1'], {type: 'application/javascript'})))"
|
||||
)
|
||||
worker = await event_info.value
|
||||
worker_this_obj = await worker.evaluate_handle("() => this")
|
||||
worker_destroyed_promise: Future[Worker] = asyncio.Future()
|
||||
worker.once("close", lambda w: worker_destroyed_promise.set_result(w))
|
||||
await page.evaluate("workerObj => workerObj.terminate()", worker_obj)
|
||||
assert await worker_destroyed_promise == worker
|
||||
with pytest.raises(Error) as exc:
|
||||
await worker_this_obj.get_property("self")
|
||||
assert TARGET_CLOSED_ERROR_MESSAGE in exc.value.message
|
||||
|
||||
|
||||
async def test_workers_should_report_console_logs(page: Page) -> None:
|
||||
async with page.expect_console_message() as message_info:
|
||||
await page.evaluate(
|
||||
'() => new Worker(URL.createObjectURL(new Blob(["console.log(1)"], {type: "application/javascript"})))'
|
||||
)
|
||||
message = await message_info.value
|
||||
assert message.text == "1"
|
||||
|
||||
|
||||
async def test_workers_should_have_JSHandles_for_console_logs(
|
||||
page: Page, browser_name: str
|
||||
) -> None:
|
||||
log_promise: "asyncio.Future[ConsoleMessage]" = asyncio.Future()
|
||||
page.on("console", lambda m: log_promise.set_result(m))
|
||||
await page.evaluate(
|
||||
"() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'})))"
|
||||
)
|
||||
log = await log_promise
|
||||
if browser_name != "firefox":
|
||||
assert log.text == "1 2 3 DedicatedWorkerGlobalScope"
|
||||
else:
|
||||
assert log.text == "1 2 3 JSHandle@object"
|
||||
assert len(log.args) == 4
|
||||
assert await (await log.args[3].get_property("origin")).json_value() == "null"
|
||||
|
||||
|
||||
async def test_workers_should_evaluate(page: Page) -> None:
|
||||
async with page.expect_event("worker") as event_info:
|
||||
await page.evaluate(
|
||||
"() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"
|
||||
)
|
||||
worker = await event_info.value
|
||||
assert await worker.evaluate("1+1") == 2
|
||||
|
||||
|
||||
async def test_workers_should_report_errors(page: Page) -> None:
|
||||
error_promise: "asyncio.Future[Error]" = asyncio.Future()
|
||||
page.on("pageerror", lambda e: error_promise.set_result(e))
|
||||
await page.evaluate(
|
||||
"""() => new Worker(URL.createObjectURL(new Blob([`
|
||||
setTimeout(() => {
|
||||
// Do a console.log just to check that we do not confuse it with an error.
|
||||
console.log('hey');
|
||||
throw new Error('this is my error');
|
||||
})
|
||||
`], {type: 'application/javascript'})))"""
|
||||
)
|
||||
error_log = await error_promise
|
||||
assert "this is my error" in error_log.message
|
||||
|
||||
|
||||
async def test_workers_should_clear_upon_navigation(server: Server, page: Page) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_event("worker") as event_info:
|
||||
await page.evaluate(
|
||||
'() => new Worker(URL.createObjectURL(new Blob(["console.log(1)"], {type: "application/javascript"})))'
|
||||
)
|
||||
worker = await event_info.value
|
||||
assert len(page.workers) == 1
|
||||
destroyed = []
|
||||
worker.once("close", lambda _: destroyed.append(True))
|
||||
await page.goto(server.PREFIX + "/one-style.html")
|
||||
assert destroyed == [True]
|
||||
assert len(page.workers) == 0
|
||||
|
||||
|
||||
async def test_workers_should_clear_upon_cross_process_navigation(
|
||||
server: Server, page: Page
|
||||
) -> None:
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_event("worker") as event_info:
|
||||
await page.evaluate(
|
||||
"() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"
|
||||
)
|
||||
worker = await event_info.value
|
||||
assert len(page.workers) == 1
|
||||
destroyed = []
|
||||
worker.once("close", lambda _: destroyed.append(True))
|
||||
await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
|
||||
assert destroyed == [True]
|
||||
assert len(page.workers) == 0
|
||||
|
||||
|
||||
@pytest.mark.skip_browser(
|
||||
"firefox"
|
||||
) # https://github.com/microsoft/playwright/issues/21760
|
||||
async def test_workers_should_report_network_activity(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
async with page.expect_worker() as worker_info:
|
||||
await page.goto(server.PREFIX + "/worker/worker.html")
|
||||
worker = await worker_info.value
|
||||
url = server.PREFIX + "/one-style.css"
|
||||
async with (
|
||||
page.expect_request(url) as request_info,
|
||||
page.expect_response(url) as response_info,
|
||||
):
|
||||
await worker.evaluate(
|
||||
"url => fetch(url).then(response => response.text()).then(console.log)", url
|
||||
)
|
||||
request = await request_info.value
|
||||
response = await response_info.value
|
||||
assert request.url == url
|
||||
assert response.request == request
|
||||
assert response.ok
|
||||
|
||||
|
||||
@pytest.mark.skip_browser(
|
||||
"firefox"
|
||||
) # https://github.com/microsoft/playwright/issues/21760
|
||||
async def test_workers_should_report_network_activity_on_worker_creation(
|
||||
page: Page, server: Server
|
||||
) -> None:
|
||||
# Chromium needs waitForDebugger enabled for this one.
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
url = server.PREFIX + "/one-style.css"
|
||||
async with (
|
||||
page.expect_request(url) as request_info,
|
||||
page.expect_response(url) as response_info,
|
||||
):
|
||||
await page.evaluate(
|
||||
"""url => new Worker(URL.createObjectURL(new Blob([`
|
||||
fetch("${url}").then(response => response.text()).then(console.log);
|
||||
`], {type: 'application/javascript'})))""",
|
||||
url,
|
||||
)
|
||||
request = await request_info.value
|
||||
response = await response_info.value
|
||||
assert request.url == url
|
||||
assert response.request == request
|
||||
assert response.ok
|
||||
|
||||
|
||||
async def test_workers_should_format_number_using_context_locale(
|
||||
browser: Browser, server: Server, browser_name: str
|
||||
) -> None:
|
||||
context = await browser.new_context(locale="ru-RU")
|
||||
page = await context.new_page()
|
||||
await page.goto(server.EMPTY_PAGE)
|
||||
async with page.expect_worker() as worker_info:
|
||||
await page.evaluate(
|
||||
"() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"
|
||||
)
|
||||
worker = await worker_info.value
|
||||
# https://github.com/microsoft/playwright/issues/38919
|
||||
expected = "10,000.2" if browser_name == "firefox" else "10\u00a0000,2"
|
||||
assert await worker.evaluate("() => (10000.20).toLocaleString()") == expected
|
||||
await context.close()
|
||||
|
||||
|
||||
async def test_worker_should_report_console_event(page: Page) -> None:
|
||||
async with page.expect_worker() as worker_info:
|
||||
await page.evaluate(
|
||||
"() => { window.worker = new Worker(URL.createObjectURL(new Blob(['42'], { type: 'application/javascript' }))); }"
|
||||
)
|
||||
worker = await worker_info.value
|
||||
|
||||
async with worker.expect_event("console") as message1_info:
|
||||
async with page.expect_console_message() as message2_info:
|
||||
async with page.context.expect_console_message() as message3_info:
|
||||
await worker.evaluate("() => { console.log('hello from worker'); }")
|
||||
|
||||
message1 = await message1_info.value
|
||||
message2 = await message2_info.value
|
||||
message3 = await message3_info.value
|
||||
|
||||
assert message1.text == "hello from worker"
|
||||
assert message1 is message2
|
||||
assert message1 is message3
|
||||
assert message1.worker is worker
|
||||
|
||||
|
||||
async def test_worker_should_report_console_event_when_not_listening_on_page_or_context(
|
||||
page: Page,
|
||||
) -> None:
|
||||
async with page.expect_worker() as worker_info:
|
||||
await page.evaluate(
|
||||
"() => { window.worker = new Worker(URL.createObjectURL(new Blob(['42'], { type: 'application/javascript' }))); }"
|
||||
)
|
||||
worker = await worker_info.value
|
||||
|
||||
async with worker.expect_event("console") as message_info:
|
||||
await worker.evaluate("() => { console.log('hello from worker'); }")
|
||||
|
||||
message = await message_info.value
|
||||
assert message.text == "hello from worker"
|
||||
assert message.worker is worker
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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.async_api import (
|
||||
ElementHandle,
|
||||
Error,
|
||||
Frame,
|
||||
Page,
|
||||
Selectors,
|
||||
ViewportSize,
|
||||
)
|
||||
|
||||
|
||||
class Utils:
|
||||
async def attach_frame(self, page: Page, frame_id: str, url: str) -> Frame:
|
||||
handle = await 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},
|
||||
)
|
||||
frame = await cast(ElementHandle, handle.as_element()).content_frame()
|
||||
assert frame
|
||||
return frame
|
||||
|
||||
async def detach_frame(self, page: Page, frame_id: str) -> None:
|
||||
await 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
|
||||
|
||||
async 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 await page.evaluate("window.innerWidth") == width
|
||||
assert await page.evaluate("window.innerHeight") == height
|
||||
|
||||
async def register_selector_engine(
|
||||
self, selectors: Selectors, *args: Any, **kwargs: Any
|
||||
) -> None:
|
||||
try:
|
||||
await 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