How to use test_console_repr 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.

test_console.py

Source: test_console.py Github

copy
1import pickle
2from pathlib import Path
3
4import numpy as np
5import pytest
6from numpy import array
7
8import tcod
9
10
11@pytest.mark.filterwarnings("ignore:Directly access a consoles")
12@pytest.mark.filterwarnings("ignore:This function may be deprecated in the fu")
13def test_array_read_write() -> None:
14    console = tcod.console.Console(width=12, height=10)
15    FG = (255, 254, 253)
16    BG = (1, 2, 3)
17    CH = ord("&")
18    tcod.console_put_char_ex(console, 0, 0, CH, FG, BG)
19    assert console.ch[0, 0] == CH
20    assert tuple(console.fg[0, 0]) == FG
21    assert tuple(console.bg[0, 0]) == BG
22
23    tcod.console_put_char_ex(console, 1, 2, CH, FG, BG)
24    assert console.ch[2, 1] == CH
25    assert tuple(console.fg[2, 1]) == FG
26    assert tuple(console.bg[2, 1]) == BG
27
28    console.clear()
29    assert console.ch[1, 1] == ord(" ")
30    assert tuple(console.fg[1, 1]) == (255, 255, 255)
31    assert tuple(console.bg[1, 1]) == (0, 0, 0)
32
33    ch_slice = console.ch[1, :]
34    ch_slice[2] = CH
35    console.fg[1, ::2] = FG
36    console.bg[...] = BG
37
38    assert tcod.console_get_char(console, 2, 1) == CH
39    assert tuple(tcod.console_get_char_foreground(console, 2, 1)) == FG
40    assert tuple(tcod.console_get_char_background(console, 2, 1)) == BG
41
42
43@pytest.mark.filterwarnings("ignore")
44def test_console_defaults() -> None:
45    console = tcod.console.Console(width=12, height=10)
46
47    console.default_bg = [2, 3, 4]  # type: ignore
48    assert console.default_bg == (2, 3, 4)
49
50    console.default_fg = (4, 5, 6)  # type: ignore
51    assert console.default_fg == (4, 5, 6)
52
53    console.default_bg_blend = tcod.BKGND_ADD  # type: ignore
54    assert console.default_bg_blend == tcod.BKGND_ADD
55
56    console.default_alignment = tcod.RIGHT  # type: ignore
57    assert console.default_alignment == tcod.RIGHT
58
59
60@pytest.mark.filterwarnings("ignore:Parameter names have been moved around,")
61@pytest.mark.filterwarnings("ignore:Pass the key color to Console.blit instea")
62@pytest.mark.filterwarnings("ignore:.*default values have been deprecated")
63def test_console_methods() -> None:
64    console = tcod.console.Console(width=12, height=10)
65    console.put_char(0, 0, ord("@"))
66    console.print_(0, 0, "Test")
67    console.print_rect(0, 0, 2, 8, "a b c d e f")
68    console.get_height_rect(0, 0, 2, 8, "a b c d e f")
69    console.rect(0, 0, 2, 2, True)
70    console.hline(0, 1, 10)
71    console.vline(1, 0, 10)
72    console.print_frame(0, 0, 8, 8, "Frame")
73    console.blit(0, 0, 0, 0, console, 0, 0)  # type: ignore
74    console.blit(0, 0, 0, 0, console, 0, 0, key_color=(0, 0, 0))  # type: ignore
75    console.set_key_color((254, 0, 254))
76
77
78def test_console_pickle() -> None:
79    console = tcod.console.Console(width=12, height=10)
80    console.ch[...] = ord(".")
81    console.fg[...] = (10, 20, 30)
82    console.bg[...] = (1, 2, 3)
83    console2 = pickle.loads(pickle.dumps(console))
84    assert (console.ch == console2.ch).all()
85    assert (console.fg == console2.fg).all()
86    assert (console.bg == console2.bg).all()
87
88
89def test_console_pickle_fortran() -> None:
90    console = tcod.console.Console(2, 3, order="F")
91    console2 = pickle.loads(pickle.dumps(console))
92    assert console.ch.strides == console2.ch.strides
93    assert console.fg.strides == console2.fg.strides
94    assert console.bg.strides == console2.bg.strides
95
96
97def test_console_repr() -> None:
98    array  # Needed for eval.
99    eval(repr(tcod.console.Console(10, 2)))
100
101
102@pytest.mark.filterwarnings("ignore")
103def test_console_str() -> None:
104    console = tcod.console.Console(10, 2)
105    console.ch[:] = ord(".")
106    console.print_(0, 0, "Test")
107    assert str(console) == ("<Test......\n" " ..........>")
108
109
110def test_console_fortran_buffer() -> None:
111    tcod.console.Console(
112        width=1,
113        height=2,
114        order="F",
115        buffer=np.zeros((1, 2), order="F", dtype=tcod.console.Console.DTYPE),
116    )
117
118
119def test_console_clear() -> None:
120    console = tcod.console.Console(1, 1)
121    assert console.fg[0, 0].tolist() == [255, 255, 255]
122    assert console.bg[0, 0].tolist() == [0, 0, 0]
123    console.clear(fg=(7, 8, 9), bg=(10, 11, 12))
124    assert console.fg[0, 0].tolist() == [7, 8, 9]
125    assert console.bg[0, 0].tolist() == [10, 11, 12]
126
127
128def test_console_semigraphics() -> None:
129    console = tcod.console.Console(1, 1)
130    console.draw_semigraphics(
131        [[[255, 255, 255], [255, 255, 255]], [[255, 255, 255], [0, 0, 0]]],
132    )
133
134
135def test_rexpaint(tmp_path: Path) -> None:
136    xp_path = tmp_path / "test.xp"
137    consoles = tcod.Console(80, 24, order="F"), tcod.Console(8, 8, order="F")
138    tcod.console.save_xp(xp_path, consoles, compress_level=0)
139    loaded = tcod.console.load_xp(xp_path, order="F")
140    assert len(consoles) == len(loaded)
141    assert loaded[0].rgba.flags["F_CONTIGUOUS"]
142    assert consoles[0].rgb.shape == loaded[0].rgb.shape
143    assert consoles[1].rgb.shape == loaded[1].rgb.shape
144    with pytest.raises(FileNotFoundError):
145        tcod.console.load_xp(tmp_path / "non_existant")
146
147
148def test_draw_frame() -> None:
149    console = tcod.Console(3, 3, order="C")
150    with pytest.raises(TypeError):
151        console.draw_frame(0, 0, 3, 3, title="test", decoration="123456789")
152    with pytest.raises(TypeError):
153        console.draw_frame(0, 0, 3, 3, decoration="0123456789")
154
155    console.draw_frame(0, 0, 3, 3, decoration=(49, 50, 51, 52, 53, 54, 55, 56, 57))
156    assert console.ch.tolist() == [[49, 50, 51], [52, 53, 54], [55, 56, 57]]
157    console.draw_frame(0, 0, 3, 3, title="T")
158
Full Screen

test_sync.py

Source: test_sync.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 os
16
17import pytest
18
19from playwright.sync_api import (
20    Browser,
21    BrowserContext,
22    Dialog,
23    Error,
24    Page,
25    TimeoutError,
26    sync_playwright,
27)
28from tests.server import Server
29
30
31def test_sync_query_selector(page: Page) -> None:
32    page.set_content(
33        """
34    <h1 id="foo">Bar</h1>
35    """
36    )
37    e1 = page.query_selector("#foo")
38    assert e1
39    e2 = page.query_selector("h1")
40    assert e2
41    assert e1.inner_text() == e2.inner_text()
42
43
44def test_page_repr(page: Page, server: Server) -> None:
45    page.goto(server.EMPTY_PAGE)
46    assert repr(page) == f"<Page url={page.url!r}>"
47
48
49def test_frame_repr(page: Page, server: Server) -> None:
50    page.goto(server.EMPTY_PAGE)
51    assert (
52        repr(page.main_frame)
53        == f"<Frame name={page.main_frame.name} url={page.main_frame.url!r}>"
54    )
55
56
57def test_browser_context_repr(context: BrowserContext) -> None:
58    assert repr(context) == f"<BrowserContext browser={context.browser}>"
59
60
61def test_browser_repr(browser: Browser) -> None:
62    assert (
63        repr(browser)
64        == f"<Browser type={browser._impl_obj._browser_type} version={browser.version}>"
65    )
66
67
68def test_browser_type_repr(browser: Browser) -> None:
69    browser_type = browser._impl_obj._browser_type
70    assert (
71        repr(browser_type)
72        == f"<BrowserType name={browser_type.name} executable_path={browser_type.executable_path}>"
73    )
74
75
76def test_dialog_repr(page: Page) -> None:
77    def on_dialog(dialog: Dialog) -> None:
78        dialog.accept()
79        assert (
80            repr(dialog)
81            == f"<Dialog type={dialog.type} message={dialog.message} default_value={dialog.default_value}>"
82        )
83
84    page.on("dialog", on_dialog)
85    page.evaluate("alert('yo')")
86
87
88def test_console_repr(page: Page) -> None:
89    messages = []
90    page.on("console", lambda m: messages.append(m))
91    page.evaluate('() => console.log("Hello world")')
92    message = messages[0]
93    assert repr(message) == f"<ConsoleMessage type={message.type} text={message.text}>"
94
95
96def test_sync_click(page: Page) -> None:
97    page.set_content(
98        """
99    <button onclick="window.clicked=true">Bar</button>
100    """
101    )
102    page.click("text=Bar")
103    assert page.evaluate("()=>window.clicked")
104
105
106def test_sync_nested_query_selector(page: Page) -> None:
107    page.set_content(
108        """
109    <div id="one">
110        <span class="two">
111            <label>
112                MyValue
113            </label>
114        </span>
115    </div>
116    """
117    )
118    e1 = page.query_selector("#one")
119    assert e1
120    e2 = e1.query_selector(".two")
121    assert e2
122    e3 = e2.query_selector("label")
123    assert e3
124    assert e3.inner_text() == "MyValue"
125
126
127def test_sync_handle_multiple_pages(context: BrowserContext) -> None:
128    page1 = context.new_page()
129    page2 = context.new_page()
130    assert len(context.pages) == 2
131    page1.set_content("one")
132    page2.set_content("two")
133    assert "one" in page1.content()
134    assert "two" in page2.content()
135    page1.close()
136    assert len(context.pages) == 1
137    page2.close()
138    assert len(context.pages) == 0
139    for page in [page1, page2]:
140        with pytest.raises(Error):
141            page.content()
142
143
144def test_sync_wait_for_event(page: Page, server: Server) -> None:
145    with page.expect_event("popup", timeout=10000) as popup:
146        page.evaluate("(url) => window.open(url)", server.EMPTY_PAGE)
147    assert popup.value
148
149
150def test_sync_wait_for_event_raise(page: Page) -> None:
151    with pytest.raises(Error):
152        with page.expect_event("popup", timeout=500) as popup:
153            assert False
154        assert popup.value is None
155
156
157def test_sync_make_existing_page_sync(page: Page) -> None:
158    page = page
159    assert page.evaluate("() => ({'playwright': true})") == {"playwright": True}
160    page.set_content("<h1>myElement</h1>")
161    page.wait_for_selector("text=myElement")
162
163
164def test_sync_network_events(page: Page, server: Server) -> None:
165    server.set_route(
166        "/hello-world",
167        lambda request: (
168            request.setHeader("Content-Type", "text/plain"),
169            request.write(b"Hello world"),
170            request.finish(),
171        ),
172    )
173    page.goto(server.EMPTY_PAGE)
174    messages = []
175    page.on(
176        "request", lambda request: messages.append(f">>{request.method}{request.url}")
177    )
178    page.on(
179        "response",
180        lambda response: messages.append(f"<<{response.status}{response.url}"),
181    )
182    response = page.evaluate("""async ()=> (await fetch("/hello-world")).text()""")
183    assert response == "Hello world"
184    assert messages == [
185        f">>GET{server.PREFIX}/hello-world",
186        f"<<200{server.PREFIX}/hello-world",
187    ]
188
189
190def test_console_should_work(page: Page, browser_name: str) -> None:
191    messages = []
192    page.once("console", lambda m: messages.append(m))
193    page.evaluate('() => console.log("hello", 5, {foo: "bar"})'),
194    assert len(messages) == 1
195    message = messages[0]
196    if browser_name != "firefox":
197        assert message.text == "hello 5 {foo: bar}"
198        assert str(message) == "hello 5 {foo: bar}"
199    else:
200        assert message.text == "hello 5 [email protected]"
201        assert str(message) == "hello 5 [email protected]"
202    assert message.type == "log"
203    assert message.args[0].json_value() == "hello"
204    assert message.args[1].json_value() == 5
205    assert message.args[2].json_value() == {"foo": "bar"}
206
207
208def test_sync_download(browser: Browser, server: Server) -> None:
209    server.set_route(
210        "/downloadWithFilename",
211        lambda request: (
212            request.setHeader("Content-Type", "application/octet-stream"),
213            request.setHeader("Content-Disposition", "attachment; filename=file.txt"),
214            request.write(b"Hello world"),
215            request.finish(),
216        ),
217    )
218    page = browser.new_page(accept_downloads=True)
219    page.set_content(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')
220
221    with page.expect_event("download") as download:
222        page.click("a")
223    assert download.value
224    assert download.value.suggested_filename == "file.txt"
225    path = download.value.path()
226    assert os.path.isfile(path)
227    with open(path, "r") as fd:
228        assert fd.read() == "Hello world"
229    page.close()
230
231
232def test_sync_workers_page_workers(page: Page, server: Server) -> None:
233    with page.expect_event("worker") as event_worker:
234        page.goto(server.PREFIX + "/worker/worker.html")
235    assert event_worker.value
236    worker = page.workers[0]
237    assert "worker.js" in worker.url
238
239    assert worker.evaluate('() => self["workerFunction"]()') == "worker function result"
240
241    page.goto(server.EMPTY_PAGE)
242    assert len(page.workers) == 0
243
244
245def test_sync_playwright_multiple_times() -> None:
246    with pytest.raises(Error) as exc:
247        with sync_playwright() as pw:
248            assert pw.chromium
249    assert (
250        "It looks like you are using Playwright Sync API inside the asyncio loop."
251        in exc.value.message
252    )
253
254
255def test_sync_set_default_timeout(page: Page) -> None:
256    page.set_default_timeout(1)
257    with pytest.raises(TimeoutError) as exc:
258        page.wait_for_function("false")
259    assert "Timeout 1ms exceeded." in exc.value.message
260
261
262def test_close_should_reject_all_promises(context: BrowserContext) -> None:
263    new_page = context.new_page()
264    with pytest.raises(Error) as exc_info:
265        new_page._gather(
266            lambda: new_page.evaluate("() => new Promise(r => {})"),
267            lambda: new_page.close(),
268        )
269    assert "Target closed" in exc_info.value.message
270
271
272def test_expect_response_should_work(page: Page, server: Server) -> None:
273    with page.expect_response("**/*") as resp:
274        page.goto(server.EMPTY_PAGE)
275    assert resp.value
276    assert resp.value.url == server.EMPTY_PAGE
277    assert resp.value.status == 200
278    assert resp.value.ok
279    assert resp.value.request
280
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)