How to use _page_closed method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

_video.py

Source: _video.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import pathlib
16from typing import TYPE_CHECKING, Union
17
18from playwright._impl._artifact import Artifact
19from playwright._impl._helper import Error
20
21if TYPE_CHECKING:  # pragma: no cover
22    from playwright._impl._page import Page
23
24
25class Video:
26    def __init__(self, page: "Page") -> None:
27        self._loop = page._loop
28        self._dispatcher_fiber = page._dispatcher_fiber
29        self._page = page
30        self._artifact_future = page._loop.create_future()
31        if page.is_closed():
32            self._page_closed()
33        else:
34            page.on("close", lambda page: self._page_closed())
35
36    def __repr__(self) -> str:
37        return f"<Video page={self._page}>"
38
39    def _page_closed(self) -> None:
40        if not self._artifact_future.done():
41            self._artifact_future.set_exception(Error("Page closed"))
42
43    def _artifact_ready(self, artifact: Artifact) -> None:
44        if not self._artifact_future.done():
45            self._artifact_future.set_result(artifact)
46
47    async def path(self) -> pathlib.Path:
48        if self._page._connection.is_remote:
49            raise Error(
50                "Path is not available when using browserType.connect(). Use save_as() to save a local copy."
51            )
52        artifact = await self._artifact_future
53        if not artifact:
54            raise Error("Page did not produce any video frames")
55        return artifact.absolute_path
56
57    async def save_as(self, path: Union[str, pathlib.Path]) -> None:
58        artifact = await self._artifact_future
59        if not artifact:
60            raise Error("Page did not produce any video frames")
61        await artifact.save_as(path)
62
63    async def delete(self) -> None:
64        artifact = await self._artifact_future
65        if not artifact:
66            raise Error("Page did not produce any video frames")
67        await artifact.delete()
68
Full Screen

io_controller.py

Source: io_controller.py Github

copy
1import enum
2from typing import NamedTuple, Callable
3
4from PyQt5 import QtWidgets
5
6from .page_controller import PageController
7
8from esolang_IDE.editor_page import EditorPage
9from esolang_IDE.notebook import Notebook
10from esolang_IDE.file_info import FileInfo
11from esolang_IDE.main_window import IDE
12
13
14class _PageInfo(NamedTuple):
15    controller: PageController
16    fileinfo: FileInfo
17
18
19class _FileOperation(enum.Enum):
20    new = enum.auto()
21    save = enum.auto()
22    open = enum.auto()
23    saveas = enum.auto()
24
25
26class _RunOperation(enum.Enum):
27    run = enum.auto()
28    visualiser = enum.auto()
29
30
31class _OperationHandler:
32
33    _op2fn: dict[enum.Enum, Callable]
34
35    def __init__(self, notebook: Notebook, pages: dict[EditorPage, _PageInfo]):
36        self.notebook = notebook
37        self.pages = pages
38
39    def handle(self, operation: enum.Enum):
40        return self._op2fn[operation]()
41
42
43class _FileOperationHandler(_OperationHandler):
44    def __init__(self, notebook: Notebook, pages: dict[EditorPage, _PageInfo]):
45        self.notebook = notebook
46        self.pages = pages
47
48        self._op2fn = {
49            _FileOperation.new: self._new,
50            _FileOperation.save: self._save,
51            _FileOperation.open: self._open,
52            _FileOperation.saveas: self._saveas,
53        }
54
55        self._file_dialog_filter = 'All Files (*);;Text Files (*.txt);;Brainfuck (*.b)'
56
57    def _new(self):
58        self._create_new_page(FileInfo.from_empty())
59
60    def _open(self):
61        filepath, extension = QtWidgets.QFileDialog.getOpenFileName(
62            filter=self._file_dialog_filter
63        )
64        if not filepath:
65            return
66
67        fileinfo = FileInfo.from_filepath(filepath)
68        self._create_new_page(fileinfo, fileinfo.read())
69
70    def _save(self):
71        current_page = self.notebook.current_page()
72        if current_page is None:
73            return
74
75        page_controller, fileinfo = self.pages[current_page]
76        if fileinfo.is_empty():
77            self._saveas()
78        else:
79            fileinfo.write(page_controller.get_text())
80            self._update_pagename(current_page)
81
82    def _saveas(self):
83        current_page = self.notebook.current_page()
84        if current_page is None:
85            return
86
87        filepath, extension = QtWidgets.QFileDialog.getSaveFileName(
88            filter=self._file_dialog_filter
89        )
90
91        if not filepath:
92            return
93
94        page_controller, fileinfo = self.pages[current_page]
95        fileinfo.update_from_filepath(filepath)
96        page_controller.set_filetype(fileinfo.filetype)
97        self._save()
98
99    def _create_new_page(self, fileinfo: FileInfo, text=''):
100        page = EditorPage()
101        self.notebook.add_tab_to_current(page, fileinfo.filename or 'Untitled')
102
103        page_controller = PageController(editor_page=page, text=text)
104        page_controller.set_filetype(fileinfo.filetype)
105        page_controller.text_changed.connect(self._page_text_changed)
106
107        self.pages[page] = _PageInfo(page_controller, fileinfo)
108
109    def _page_text_changed(self, page):
110        fileinfo = self.pages[page].fileinfo
111        if not fileinfo.changed:
112            fileinfo.changed = True
113            self._update_pagename(page)
114
115    def _update_pagename(self, page):
116        fileinfo = self.pages[page].fileinfo
117        self.notebook.set_page_tab_text(
118            page, f'{"*. " if fileinfo.changed else ""}{fileinfo.filename or "Untitled"}'
119        )
120
121
122class _RunOperationHandler(_OperationHandler):
123    def __init__(self, notebook: Notebook, pages: dict[EditorPage, _PageInfo]):
124        super().__init__(notebook, pages)
125
126        self._op2fn = {
127            _RunOperation.run: self._run_code,
128            _RunOperation.visualiser: self._open_visualier,
129        }
130
131    def _run_code(self):
132        page = self.notebook.current_page()
133        if page is None:
134            return
135
136        self.pages[page].controller.run_code()
137
138    def _open_visualier(self):
139        page = self.notebook.current_page()
140        if page is None:
141            return
142
143        self.pages[page].controller.open_visualiser()
144
145
146class IOController:
147    def __init__(self):
148
149        self.notebook = Notebook()
150        self.notebook.page_closed.connect(self._page_closed)
151
152        self.pages: dict[EditorPage, _PageInfo] = {}
153
154        self.file_handler = _FileOperationHandler(self.notebook, self.pages)
155        self.run_handler = _RunOperationHandler(self.notebook, self.pages)
156
157        self.init_mainwindow()
158
159    def init_mainwindow(self):
160        file_handle = lambda op: (lambda: self.file_handler.handle(op))
161        run_handle = lambda op: (lambda: self.run_handler.handle(op))
162
163        self.ide = IDE(
164            menu_layout={
165                'File': (
166                    ('New', 'Ctrl+N', 'New file', file_handle(_FileOperation.new)),
167                    ('Open', 'Ctrl+O', 'Open file', file_handle(_FileOperation.open)),
168                    ('Save', 'Ctrl+S', 'Save file', file_handle(_FileOperation.save)),
169                    (
170                        'Save As',
171                        'Ctrl+Shift+S',
172                        'Save as',
173                        file_handle(_FileOperation.saveas),
174                    ),
175                ),
176                'Run': (
177                    ('Run code', 'Ctrl+B', 'Run code', run_handle(_RunOperation.run)),
178                    (
179                        'Open visualiser',
180                        'Ctrl+Shift+B',
181                        'Visualise execution',
182                        run_handle(_RunOperation.visualiser),
183                    ),
184                ),
185            }
186        )
187        self.ide.setGeometry(200, 100, 1600, 900)
188        self.ide.setCentralWidget(self.notebook)
189
190    def _page_closed(self, page):
191        # Clean up reference
192        self.pages.pop(page)
193
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)