diff --git a/playwright/_impl/tracing.py b/playwright/_impl/tracing.py index 8453bedf9..6783dfca2 100644 --- a/playwright/_impl/tracing.py +++ b/playwright/_impl/tracing.py @@ -22,6 +22,7 @@ """ import asyncio +import os import re from pathlib import Path from typing import ( @@ -220,8 +221,9 @@ async def _record_into_har( update_mode: Optional[Literal["minimal", "full"]], ) -> str: # Not ported: the resourcesDir option; it is JavaScript only. - # Python: the path can be a pathlib.Path. - har = str(har) + # Python: accept pathlib.Path and resolve against the Python cwd, which + # can change independently of the driver's cwd. + har = os.path.abspath(har) is_zip = bool(re.search(r"\.zip$", har, re.IGNORECASE)) options: Dict[str, Any] = { "content": update_content if update_content is not None else "attach", @@ -344,6 +346,9 @@ async def _save_chunk( if not local_utils: raise Error("Cannot save trace in thin clients") + # Python: accept pathlib.Path and resolve against the Python cwd before + # the driver writes the trace. + file_path = os.path.abspath(file_path) is_local = not self._connection.is_remote() if is_local: @@ -352,8 +357,7 @@ async def _save_chunk( ) await local_utils.zip( { - # Python: the path can be a pathlib.Path. - "zipFile": str(file_path), + "zipFile": file_path, "entries": result["entries"], "mode": "write", "stacksId": stacks_id, @@ -388,8 +392,7 @@ async def _save_chunk( await local_utils.zip( { - # Python: the path can be a pathlib.Path. - "zipFile": str(file_path), + "zipFile": file_path, "entries": [], "mode": "append", "stacksId": stacks_id, diff --git a/tests/sync/python/test_tracing.py b/tests/sync/python/test_tracing.py index d4dfe1687..642f3443c 100644 --- a/tests/sync/python/test_tracing.py +++ b/tests/sync/python/test_tracing.py @@ -19,6 +19,8 @@ from pathlib import Path from typing import Callable, ContextManager +import pytest + from playwright.sync_api import BrowserContext, Page, Response, expect from tests.server import Server @@ -26,12 +28,16 @@ def test_should_collect_sources( - context: BrowserContext, - page: Page, + context_factory: Callable[..., BrowserContext], server: Server, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, show_trace_viewer: Callable[[Path], ContextManager[TraceViewerPage]], ) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3361. + monkeypatch.chdir(tmp_path) + context = context_factory(record_har_path="log.har") + page = context.new_page() context.tracing.start(sources=True) page.goto(server.EMPTY_PAGE) page.set_content("") @@ -44,7 +50,10 @@ def my_method_inner() -> None: my_method_outer() path = tmp_path / "trace.zip" - context.tracing.stop(path=path) + context.tracing.stop(path=Path("trace.zip")) + context.close() + assert path.is_file() + assert (tmp_path / "log.har").is_file() with show_trace_viewer(path) as trace_viewer: expect(trace_viewer.action_titles).to_have_text(