Skip to content

Commit

Permalink
make tests pass
Browse files Browse the repository at this point in the history
  • Loading branch information
mxschmitt committed Oct 7, 2024
1 parent 3ed5b5c commit fedfaed
Show file tree
Hide file tree
Showing 12 changed files with 368 additions and 195 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ Playwright is a Python library to automate [Chromium](https://www.chromium.org/H

| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->130.0.6723.19<!-- GEN:stop --> ||||
| Chromium <!-- GEN:chromium-version -->130.0.6723.31<!-- GEN:stop --> ||||
| WebKit <!-- GEN:webkit-version -->18.0<!-- GEN:stop --> ||||
| Firefox <!-- GEN:firefox-version -->130.0<!-- GEN:stop --> ||||
| Firefox <!-- GEN:firefox-version -->131.0<!-- GEN:stop --> ||||

## Documentation

Expand Down
2 changes: 1 addition & 1 deletion playwright/_impl/_browser_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ async def _on_route(self, route: Route) -> None:
try:
# If the page is closed or unrouteAll() was called without waiting and interception disabled,
# the method will throw an error - silence it.
await route._internal_continue(is_internal=True)
await route._inner_continue(True)
except Exception:
pass

Expand Down
6 changes: 5 additions & 1 deletion playwright/_impl/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ def __init__(
self._channel: Channel = Channel(self._connection, self)
self._initializer = initializer
self._was_collected = False
self._is_internal_type = False

self._connection._objects[guid] = self
if self._parent:
Expand All @@ -156,6 +157,9 @@ def _adopt(self, child: "ChannelOwner") -> None:
self._objects[child._guid] = child
child._parent = self

def mark_as_internal_type(self) -> None:
self._is_internal_type = True

def _set_event_to_subscription_mapping(self, mapping: Dict[str, str]) -> None:
self._event_to_subscription_mapping = mapping

Expand Down Expand Up @@ -353,7 +357,7 @@ def _send_message_to_server(
"params": self._replace_channels_with_guids(params),
"metadata": metadata,
}
if self._tracing_count > 0 and frames and object._guid != "localUtils":
if self._tracing_count > 0 and frames and not object._is_internal_type:
self.local_utils.add_stack_to_tracing_no_reply(id, frames)

self._transport.send(message)
Expand Down
21 changes: 2 additions & 19 deletions playwright/_impl/_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import typing
from pathlib import Path
from typing import Any, Dict, List, Optional, Union, cast
from urllib.parse import parse_qs

import playwright._impl._network as network
from playwright._impl._api_structures import (
Expand Down Expand Up @@ -405,7 +404,8 @@ async def _inner_fetch(
"fetch",
{
"url": url,
"params": params_to_protocol(params),
"params": object_to_array(params) if isinstance(params, dict) else None,
"encodedParams": params if isinstance(params, str) else None,
"method": method,
"headers": serialized_headers,
"postData": post_data,
Expand All @@ -430,23 +430,6 @@ async def storage_state(
return result


def params_to_protocol(params: Optional[ParamsType]) -> Optional[List[NameValue]]:
if not params:
return None
if isinstance(params, dict):
return object_to_array(params)
if params.startswith("?"):
params = params[1:]
parsed = parse_qs(params)
if not parsed:
return None
out = []
for name, values in parsed.items():
for value in values:
out.append(NameValue(name=name, value=value))
return out


def file_payload_to_json(payload: FilePayload) -> ServerFilePayload:
return ServerFilePayload(
name=payload["name"],
Expand Down
1 change: 1 addition & 0 deletions playwright/_impl/_local_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __init__(
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
) -> None:
super().__init__(parent, type, guid, initializer)
self.mark_as_internal_type()
self.devices = {
device["name"]: parse_device_descriptor(device["descriptor"])
for device in initializer["deviceDescriptors"]
Expand Down
79 changes: 31 additions & 48 deletions playwright/_impl/_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
)
from playwright._impl._connection import (
ChannelOwner,
Connection,
from_channel,
from_nullable_channel,
)
Expand Down Expand Up @@ -318,6 +317,7 @@ def __init__(
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
) -> None:
super().__init__(parent, type, guid, initializer)
self.mark_as_internal_type()
self._handling_future: Optional[asyncio.Future["bool"]] = None
self._context: "BrowserContext" = cast("BrowserContext", None)
self._did_throw = False
Expand Down Expand Up @@ -350,7 +350,6 @@ async def abort(self, errorCode: str = None) -> None:
"abort",
{
"errorCode": errorCode,
"requestUrl": self.request._initializer["url"],
},
)
)
Expand Down Expand Up @@ -433,7 +432,6 @@ async def _inner_fulfill(
if length and "content-length" not in headers:
headers["content-length"] = str(length)
params["headers"] = serialize_headers(headers)
params["requestUrl"] = self.request._initializer["url"]

await self._race_with_page_close(self._channel.send("fulfill", params))

Expand Down Expand Up @@ -492,43 +490,28 @@ async def continue_(

async def _inner() -> None:
self.request._apply_fallback_overrides(overrides)
await self._internal_continue()
await self._inner_continue(False)

return await self._handle_route(_inner)

def _internal_continue(
self, is_internal: bool = False
) -> Coroutine[Any, Any, None]:
async def continue_route() -> None:
try:
params: Dict[str, Any] = {}
params["url"] = self.request._fallback_overrides.url
params["method"] = self.request._fallback_overrides.method
params["headers"] = self.request._fallback_overrides.headers
if self.request._fallback_overrides.post_data_buffer is not None:
params["postData"] = base64.b64encode(
self.request._fallback_overrides.post_data_buffer
).decode()
params = locals_to_params(params)

if "headers" in params:
params["headers"] = serialize_headers(params["headers"])
params["requestUrl"] = self.request._initializer["url"]
params["isFallback"] = is_internal
await self._connection.wrap_api_call(
lambda: self._race_with_page_close(
self._channel.send(
"continue",
params,
)
),
is_internal,
)
except Exception as e:
if not is_internal:
raise e

return continue_route()
async def _inner_continue(self, is_fallback: bool = False) -> None:
options = self.request._fallback_overrides
await self._race_with_page_close(
self._channel.send(
"continue",
{
"url": options.url,
"method": options.method,
"headers": serialize_headers(options.headers)
if options.headers
else None,
"postData": base64.b64encode(options.post_data_buffer).decode()
if options.post_data_buffer is not None
else None,
"isFallback": is_fallback,
},
)
)

async def _redirected_navigation_request(self, url: str) -> None:
await self._handle_route(
Expand Down Expand Up @@ -586,7 +569,7 @@ def close(self, code: int = None, reason: str = None) -> None:
},
)
)
except:
except Exception:
pass

def send(self, message: Union[str, bytes]) -> None:
Expand Down Expand Up @@ -636,7 +619,7 @@ def _channel_message_from_page(self, event: Dict) -> None:
elif self._connected:
try:
asyncio.create_task(self._channel.send("sendToServer", event))
except:
except Exception:
pass

def _channel_message_from_server(self, event: Dict) -> None:
Expand All @@ -649,7 +632,7 @@ def _channel_message_from_server(self, event: Dict) -> None:
else:
try:
asyncio.create_task(self._channel.send("sendToPage", event))
except:
except Exception:
pass

def _channel_close_page(self, event: Dict) -> None:
Expand All @@ -658,7 +641,7 @@ def _channel_close_page(self, event: Dict) -> None:
else:
try:
asyncio.create_task(self._channel.send("closeServer", event))
except:
except Exception:
pass

def _channel_close_server(self, event: Dict) -> None:
Expand All @@ -667,7 +650,7 @@ def _channel_close_server(self, event: Dict) -> None:
else:
try:
asyncio.create_task(self._channel.send("closePage", event))
except:
except Exception:
pass

@property
Expand All @@ -679,7 +662,7 @@ async def close(self, code: int = None, reason: str = None) -> None:
await self._channel.send(
"closePage", {"code": code, "reason": reason, "wasClean": True}
)
except:
except Exception:
pass

def connect_to_server(self) -> "WebSocketRoute":
Expand All @@ -697,7 +680,7 @@ def send(self, message: Union[str, bytes]) -> None:
"sendToPage", {"message": message, "isBase64": False}
)
)
except:
except Exception:
pass
else:
try:
Expand All @@ -710,7 +693,7 @@ def send(self, message: Union[str, bytes]) -> None:
},
)
)
except:
except Exception:
pass

def on_message(self, handler: Callable[[Union[str, bytes]], Any]) -> None:
Expand Down Expand Up @@ -758,9 +741,9 @@ def matches(self, ws_url: str) -> bool:
return self.matcher.matches(ws_url)

async def handle(self, websocket_route: "WebSocketRoute") -> None:
maybe_future = self.handler(websocket_route)
if maybe_future:
breakpoint()
coro_or_future = self.handler(websocket_route)
if asyncio.iscoroutine(coro_or_future):
await coro_or_future
await websocket_route._after_handle()


Expand Down
2 changes: 1 addition & 1 deletion playwright/_impl/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ async def _on_web_socket_route(self, web_socket_route: WebSocketRoute) -> None:
if route_handler:
await route_handler.handle(web_socket_route)
else:
web_socket_route.connect_to_server()
await self._browser_context._on_web_socket_route(web_socket_route)

def _on_binding(self, binding_call: "BindingCall") -> None:
func = self._bindings.get(binding_call._initializer["name"])
Expand Down
20 changes: 7 additions & 13 deletions playwright/_impl/_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,10 @@ async def start(
params = locals_to_params(locals())
self._include_sources = bool(sources)

async def _inner_start() -> str:
await self._channel.send("tracingStart", params)
return await self._channel.send(
"tracingStartChunk", {"title": title, "name": name}
)

trace_name = await self._connection.wrap_api_call(_inner_start, True)
await self._channel.send("tracingStart", params)
trace_name = await self._channel.send(
"tracingStartChunk", {"title": title, "name": name}
)
await self._start_collecting_stacks(trace_name)

async def start_chunk(self, title: str = None, name: str = None) -> None:
Expand All @@ -64,14 +61,11 @@ async def _start_collecting_stacks(self, trace_name: str) -> None:
)

async def stop_chunk(self, path: Union[pathlib.Path, str] = None) -> None:
await self._connection.wrap_api_call(lambda: self._do_stop_chunk(path), True)
await self._do_stop_chunk(path)

async def stop(self, path: Union[pathlib.Path, str] = None) -> None:
async def _inner() -> None:
await self._do_stop_chunk(path)
await self._channel.send("tracingStop")

await self._connection.wrap_api_call(_inner, True)
await self._do_stop_chunk(path)
await self._channel.send("tracingStop")

async def _do_stop_chunk(self, file_path: Union[pathlib.Path, str] = None) -> None:
self._reset_stack_counter()
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
InWheel = None
from wheel.bdist_wheel import bdist_wheel as BDistWheelCommand

driver_version = "1.48.0-alpha-1727434891000"
driver_version = "1.48.0-beta-1728034490000"


def extractall(zip: zipfile.ZipFile, path: str) -> None:
Expand Down
2 changes: 2 additions & 0 deletions tests/async/test_page_request_gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ async def test_should_work(page: Page, server: Server) -> None:
)
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
Loading

0 comments on commit fedfaed

Please sign in to comment.