How to use test_should_expose_keyIdentifier_in_webkit 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_keyboard.py

Source: test_keyboard.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.
14import pytest
15
16from playwright._impl._api_types import Error
17from playwright.async_api import Page
18
19
20async def captureLastKeydown(page):
21    lastEvent = await page.evaluate_handle(
22        """() => {
23        const lastEvent = {
24        repeat: false,
25        location: -1,
26        code: '',
27        key: '',
28        metaKey: false,
29        keyIdentifier: 'unsupported'
30        };
31        document.addEventListener('keydown', e => {
32        lastEvent.repeat = e.repeat;
33        lastEvent.location = e.location;
34        lastEvent.key = e.key;
35        lastEvent.code = e.code;
36        lastEvent.metaKey = e.metaKey;
37        // keyIdentifier only exists in WebKit, and isn't in TypeScript's lib.
38        lastEvent.keyIdentifier = 'keyIdentifier' in e && e.keyIdentifier;
39        }, true);
40        return lastEvent;
41    }"""
42    )
43    return lastEvent
44
45
46async def test_keyboard_type_into_a_textarea(page):
47    await page.evaluate(
48        """
49            const textarea = document.createElement('textarea');
50            document.body.appendChild(textarea);
51            textarea.focus();
52        """
53    )
54    text = "Hello world. I am the text that was typed!"
55    await page.keyboard.type(text)
56    assert await page.evaluate('document.querySelector("textarea").value') == text
57
58
59async def test_keyboard_move_with_the_arrow_keys(page, server):
60    await page.goto(f"{server.PREFIX}/input/textarea.html")
61    await page.type("textarea", "Hello World!")
62    assert (
63        await page.evaluate("document.querySelector('textarea').value")
64        == "Hello World!"
65    )
66    for _ in "World!":
67        await page.keyboard.press("ArrowLeft")
68    await page.keyboard.type("inserted ")
69    assert (
70        await page.evaluate("document.querySelector('textarea').value")
71        == "Hello inserted World!"
72    )
73    await page.keyboard.down("Shift")
74    for _ in "inserted ":
75        await page.keyboard.press("ArrowLeft")
76    await page.keyboard.up("Shift")
77    await page.keyboard.press("Backspace")
78    assert (
79        await page.evaluate("document.querySelector('textarea').value")
80        == "Hello World!"
81    )
82
83
84async def test_keyboard_send_a_character_with_elementhandle_press(page, server):
85    await page.goto(f"{server.PREFIX}/input/textarea.html")
86    textarea = await page.query_selector("textarea")
87    await textarea.press("a")
88    assert await page.evaluate("document.querySelector('textarea').value") == "a"
89    await page.evaluate(
90        "() => window.addEventListener('keydown', e => e.preventDefault(), true)"
91    )
92    await textarea.press("b")
93    assert await page.evaluate("document.querySelector('textarea').value") == "a"
94
95
96async def test_should_send_a_character_with_send_character(page, server):
97    await page.goto(server.PREFIX + "/input/textarea.html")
98    await page.focus("textarea")
99    await page.keyboard.insert_text("嗨")
100    assert await page.evaluate('() => document.querySelector("textarea").value') == "嗨"
101    await page.evaluate(
102        '() => window.addEventListener("keydown", e => e.preventDefault(), true)'
103    )
104    await page.keyboard.insert_text("a")
105    assert await page.evaluate('() => document.querySelector("textarea").value') == "嗨a"
106
107
108async def test_should_only_emit_input_event(page, server):
109    await page.goto(server.PREFIX + "/input/textarea.html")
110    await page.focus("textarea")
111    page.on("console", "m => console.log(m.text())")
112    events = await page.evaluate_handle(
113        """() => {
114    const events = [];
115    document.addEventListener('keydown', e => events.push(e.type));
116    document.addEventListener('keyup', e => events.push(e.type));
117    document.addEventListener('keypress', e => events.push(e.type));
118    document.addEventListener('input', e => events.push(e.type));
119    return events;
120  }"""
121    )
122
123    await page.keyboard.insert_text("hello world")
124    assert await events.json_value() == ["input"]
125
126
127async def test_should_report_shiftkey(page: Page, server, is_mac, is_firefox):
128    if is_firefox and is_mac:
129        pytest.skip()
130    await page.goto(server.PREFIX + "/input/keyboard.html")
131    keyboard = page.keyboard
132    codeForKey = {"Shift": 16, "Alt": 18, "Control": 17}
133    for modifierKey in codeForKey.keys():
134        await keyboard.down(modifierKey)
135        assert (
136            await page.evaluate("() => getResult()")
137            == "Keydown: "
138            + modifierKey
139            + " "
140            + modifierKey
141            + "Left "
142            + str(codeForKey[modifierKey])
143            + " ["
144            + modifierKey
145            + "]"
146        )
147        await keyboard.down("!")
148        # Shift+! will generate a keypress
149        if modifierKey == "Shift":
150            assert (
151                await page.evaluate("() => getResult()")
152                == "Keydown: ! Digit1 49 ["
153                + modifierKey
154                + "]\nKeypress: ! Digit1 33 33 ["
155                + modifierKey
156                + "]"
157            )
158        else:
159            assert (
160                await page.evaluate("() => getResult()")
161                == "Keydown: ! Digit1 49 [" + modifierKey + "]"
162            )
163
164        await keyboard.up("!")
165        assert (
166            await page.evaluate("() => getResult()")
167            == "Keyup: ! Digit1 49 [" + modifierKey + "]"
168        )
169        await keyboard.up(modifierKey)
170        assert (
171            await page.evaluate("() => getResult()")
172            == "Keyup: "
173            + modifierKey
174            + " "
175            + modifierKey
176            + "Left "
177            + str(codeForKey[modifierKey])
178            + " []"
179        )
180
181
182async def test_should_report_multiple_modifiers(page: Page, server):
183    await page.goto(server.PREFIX + "/input/keyboard.html")
184    keyboard = page.keyboard
185    await keyboard.down("Control")
186    assert (
187        await page.evaluate("() => getResult()")
188        == "Keydown: Control ControlLeft 17 [Control]"
189    )
190    await keyboard.down("Alt")
191    assert (
192        await page.evaluate("() => getResult()")
193        == "Keydown: Alt AltLeft 18 [Alt Control]"
194    )
195    await keyboard.down(";")
196    assert (
197        await page.evaluate("() => getResult()")
198        == "Keydown: ; Semicolon 186 [Alt Control]"
199    )
200    await keyboard.up(";")
201    assert (
202        await page.evaluate("() => getResult()")
203        == "Keyup: ; Semicolon 186 [Alt Control]"
204    )
205    await keyboard.up("Control")
206    assert (
207        await page.evaluate("() => getResult()")
208        == "Keyup: Control ControlLeft 17 [Alt]"
209    )
210    await keyboard.up("Alt")
211    assert await page.evaluate("() => getResult()") == "Keyup: Alt AltLeft 18 []"
212
213
214async def test_should_send_proper_codes_while_typing(page: Page, server):
215    await page.goto(server.PREFIX + "/input/keyboard.html")
216    await page.keyboard.type("!")
217    assert await page.evaluate("() => getResult()") == "\n".join(
218        [
219            "Keydown: ! Digit1 49 []",
220            "Keypress: ! Digit1 33 33 []",
221            "Keyup: ! Digit1 49 []",
222        ]
223    )
224    await page.keyboard.type("^")
225    assert await page.evaluate("() => getResult()") == "\n".join(
226        [
227            "Keydown: ^ Digit6 54 []",
228            "Keypress: ^ Digit6 94 94 []",
229            "Keyup: ^ Digit6 54 []",
230        ]
231    )
232
233
234async def test_should_send_proper_codes_while_typing_with_shift(page: Page, server):
235    await page.goto(server.PREFIX + "/input/keyboard.html")
236    keyboard = page.keyboard
237    await keyboard.down("Shift")
238    await page.keyboard.type("~")
239    assert await page.evaluate("() => getResult()") == "\n".join(
240        [
241            "Keydown: Shift ShiftLeft 16 [Shift]",
242            "Keydown: ~ Backquote 192 [Shift]",  # 192 is ` keyCode
243            "Keypress: ~ Backquote 126 126 [Shift]",  # 126 is ~ charCode
244            "Keyup: ~ Backquote 192 [Shift]",
245        ]
246    )
247    await keyboard.up("Shift")
248
249
250async def test_should_not_type_canceled_events(page: Page, server):
251    await page.goto(server.PREFIX + "/input/textarea.html")
252    await page.focus("textarea")
253    await page.evaluate(
254        """() => {
255    window.addEventListener('keydown', event => {
256      event.stopPropagation();
257      event.stopImmediatePropagation();
258      if (event.key === 'l')
259        event.preventDefault();
260      if (event.key === 'o')
261        event.preventDefault();
262    }, false);
263  }"""
264    )
265
266    await page.keyboard.type("Hello World!")
267    assert (
268        await page.eval_on_selector("textarea", "textarea => textarea.value")
269        == "He Wrd!"
270    )
271
272
273async def test_should_press_plus(page: Page, server):
274    await page.goto(server.PREFIX + "/input/keyboard.html")
275    await page.keyboard.press("+")
276    assert await page.evaluate("() => getResult()") == "\n".join(
277        [
278            "Keydown: + Equal 187 []",  # 192 is ` keyCode
279            "Keypress: + Equal 43 43 []",  # 126 is ~ charCode
280            "Keyup: + Equal 187 []",
281        ]
282    )
283
284
285async def test_should_press_shift_plus(page: Page, server):
286    await page.goto(server.PREFIX + "/input/keyboard.html")
287    await page.keyboard.press("Shift++")
288    assert await page.evaluate("() => getResult()") == "\n".join(
289        [
290            "Keydown: Shift ShiftLeft 16 [Shift]",
291            "Keydown: + Equal 187 [Shift]",  # 192 is ` keyCode
292            "Keypress: + Equal 43 43 [Shift]",  # 126 is ~ charCode
293            "Keyup: + Equal 187 [Shift]",
294            "Keyup: Shift ShiftLeft 16 []",
295        ]
296    )
297
298
299async def test_should_support_plus_separated_modifiers(page: Page, server):
300    await page.goto(server.PREFIX + "/input/keyboard.html")
301    await page.keyboard.press("Shift+~")
302    assert await page.evaluate("() => getResult()") == "\n".join(
303        [
304            "Keydown: Shift ShiftLeft 16 [Shift]",
305            "Keydown: ~ Backquote 192 [Shift]",  # 192 is ` keyCode
306            "Keypress: ~ Backquote 126 126 [Shift]",  # 126 is ~ charCode
307            "Keyup: ~ Backquote 192 [Shift]",
308            "Keyup: Shift ShiftLeft 16 []",
309        ]
310    )
311
312
313async def test_should_suport_multiple_plus_separated_modifiers(page: Page, server):
314    await page.goto(server.PREFIX + "/input/keyboard.html")
315    await page.keyboard.press("Control+Shift+~")
316    assert await page.evaluate("() => getResult()") == "\n".join(
317        [
318            "Keydown: Control ControlLeft 17 [Control]",
319            "Keydown: Shift ShiftLeft 16 [Control Shift]",
320            "Keydown: ~ Backquote 192 [Control Shift]",  # 192 is ` keyCode
321            "Keyup: ~ Backquote 192 [Control Shift]",
322            "Keyup: Shift ShiftLeft 16 [Control]",
323            "Keyup: Control ControlLeft 17 []",
324        ]
325    )
326
327
328async def test_should_shift_raw_codes(page: Page, server):
329    await page.goto(server.PREFIX + "/input/keyboard.html")
330    await page.keyboard.press("Shift+Digit3")
331    assert await page.evaluate("() => getResult()") == "\n".join(
332        [
333            "Keydown: Shift ShiftLeft 16 [Shift]",
334            "Keydown: # Digit3 51 [Shift]",  # 51 is # keyCode
335            "Keypress: # Digit3 35 35 [Shift]",  # 35 is # charCode
336            "Keyup: # Digit3 51 [Shift]",
337            "Keyup: Shift ShiftLeft 16 []",
338        ]
339    )
340
341
342async def test_should_specify_repeat_property(page: Page, server):
343    await page.goto(server.PREFIX + "/input/textarea.html")
344    await page.focus("textarea")
345    lastEvent = await captureLastKeydown(page)
346    await page.keyboard.down("a")
347    assert await lastEvent.evaluate("e => e.repeat") is False
348    await page.keyboard.press("a")
349    assert await lastEvent.evaluate("e => e.repeat")
350
351    await page.keyboard.down("b")
352    assert await lastEvent.evaluate("e => e.repeat") is False
353    await page.keyboard.down("b")
354    assert await lastEvent.evaluate("e => e.repeat")
355
356    await page.keyboard.up("a")
357    await page.keyboard.down("a")
358    assert await lastEvent.evaluate("e => e.repeat") is False
359
360
361async def test_should_type_all_kinds_of_characters(page: Page, server):
362    await page.goto(server.PREFIX + "/input/textarea.html")
363    await page.focus("textarea")
364    text = "This text goes onto two lines.\nThis character is 嗨."
365    await page.keyboard.type(text)
366    assert await page.eval_on_selector("textarea", "t => t.value") == text
367
368
369async def test_should_specify_location(page: Page, server):
370    await page.goto(server.PREFIX + "/input/textarea.html")
371    lastEvent = await captureLastKeydown(page)
372    textarea = await page.query_selector("textarea")
373    assert textarea
374
375    await textarea.press("Digit5")
376    assert await lastEvent.evaluate("e => e.location") == 0
377
378    await textarea.press("ControlLeft")
379    assert await lastEvent.evaluate("e => e.location") == 1
380
381    await textarea.press("ControlRight")
382    assert await lastEvent.evaluate("e => e.location") == 2
383
384    await textarea.press("NumpadSubtract")
385    assert await lastEvent.evaluate("e => e.location") == 3
386
387
388async def test_should_press_enter(page: Page, server):
389    await page.set_content("<textarea></textarea>")
390    await page.focus("textarea")
391    lastEventHandle = await captureLastKeydown(page)
392
393    async def testEnterKey(key, expectedKey, expectedCode):
394        await page.keyboard.press(key)
395        lastEvent = await lastEventHandle.json_value()
396        assert lastEvent["key"] == expectedKey
397        assert lastEvent["code"] == expectedCode
398        value = await page.eval_on_selector("textarea", "t => t.value")
399        assert value == "\n"
400        await page.eval_on_selector("textarea", "t => t.value = ''")
401
402    await testEnterKey("Enter", "Enter", "Enter")
403    await testEnterKey("NumpadEnter", "Enter", "NumpadEnter")
404    await testEnterKey("\n", "Enter", "Enter")
405    await testEnterKey("\r", "Enter", "Enter")
406
407
408async def test_should_throw_unknown_keys(page: Page, server):
409    with pytest.raises(Error) as exc:
410        await page.keyboard.press("NotARealKey")
411    assert exc.value.message == 'Unknown key: "NotARealKey"'
412
413    with pytest.raises(Error) as exc:
414        await page.keyboard.press("ё")
415    assert exc.value.message == 'Unknown key: "ё"'
416
417    with pytest.raises(Error) as exc:
418        await page.keyboard.press("😊")
419    assert exc.value.message == 'Unknown key: "😊"'
420
421
422async def test_should_type_emoji(page: Page, server):
423    await page.goto(server.PREFIX + "/input/textarea.html")
424    await page.type("textarea", "👹 Tokyo street Japan 🇯🇵")
425    assert (
426        await page.eval_on_selector("textarea", "textarea => textarea.value")
427        == "👹 Tokyo street Japan 🇯🇵"
428    )
429
430
431async def test_should_type_emoji_into_an_iframe(page: Page, server, utils):
432    await page.goto(server.EMPTY_PAGE)
433    await utils.attach_frame(page, "emoji-test", server.PREFIX + "/input/textarea.html")
434    frame = page.frames[1]
435    textarea = await frame.query_selector("textarea")
436    assert textarea
437    await textarea.type("👹 Tokyo street Japan 🇯🇵")
438    assert (
439        await frame.eval_on_selector("textarea", "textarea => textarea.value")
440        == "👹 Tokyo street Japan 🇯🇵"
441    )
442
443
444async def test_should_handle_select_all(page: Page, server, is_mac):
445    await page.goto(server.PREFIX + "/input/textarea.html")
446    textarea = await page.query_selector("textarea")
447    assert textarea
448    await textarea.type("some text")
449    modifier = "Meta" if is_mac else "Control"
450    await page.keyboard.down(modifier)
451    await page.keyboard.press("a")
452    await page.keyboard.up(modifier)
453    await page.keyboard.press("Backspace")
454    assert await page.eval_on_selector("textarea", "textarea => textarea.value") == ""
455
456
457async def test_should_be_able_to_prevent_select_all(page, server, is_mac):
458    await page.goto(server.PREFIX + "/input/textarea.html")
459    textarea = await page.query_selector("textarea")
460    await textarea.type("some text")
461    await page.eval_on_selector(
462        "textarea",
463        """textarea => {
464    textarea.addEventListener('keydown', event => {
465      if (event.key === 'a' && (event.metaKey || event.ctrlKey))
466        event.preventDefault();
467    }, false);
468  }""",
469    )
470
471    modifier = "Meta" if is_mac else "Control"
472    await page.keyboard.down(modifier)
473    await page.keyboard.press("a")
474    await page.keyboard.up(modifier)
475    await page.keyboard.press("Backspace")
476    assert (
477        await page.eval_on_selector("textarea", "textarea => textarea.value")
478        == "some tex"
479    )
480
481
482@pytest.mark.only_platform("darwin")
483async def test_should_support_macos_shortcuts(page, server, is_firefox, is_mac):
484    await page.goto(server.PREFIX + "/input/textarea.html")
485    textarea = await page.query_selector("textarea")
486    await textarea.type("some text")
487    # select one word backwards
488    await page.keyboard.press("Shift+Control+Alt+KeyB")
489    await page.keyboard.press("Backspace")
490    assert (
491        await page.eval_on_selector("textarea", "textarea => textarea.value") == "some "
492    )
493
494
495async def test_should_press_the_meta_key(page, server, is_firefox, is_mac):
496    lastEvent = await captureLastKeydown(page)
497    await page.keyboard.press("Meta")
498    v = await lastEvent.json_value()
499    metaKey = v["metaKey"]
500    key = v["key"]
501    code = v["code"]
502    if is_firefox and not is_mac:
503        assert key == "OS"
504    else:
505        assert key == "Meta"
506
507    if is_firefox:
508        assert code == "OSLeft"
509    else:
510        assert code == "MetaLeft"
511
512    if is_firefox and not is_mac:
513        assert metaKey is False
514    else:
515        assert metaKey
516
517
518async def test_should_work_after_a_cross_origin_navigation(page, server):
519    await page.goto(server.PREFIX + "/empty.html")
520    await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
521    lastEvent = await captureLastKeydown(page)
522    await page.keyboard.press("a")
523    assert await lastEvent.evaluate("l => l.key") == "a"
524
525
526# event.keyIdentifier has been removed from all browsers except WebKit
527@pytest.mark.only_browser("webkit")
528async def test_should_expose_keyIdentifier_in_webkit(page, server):
529    lastEvent = await captureLastKeydown(page)
530    keyMap = {
531        "ArrowUp": "Up",
532        "ArrowDown": "Down",
533        "ArrowLeft": "Left",
534        "ArrowRight": "Right",
535        "Backspace": "U+0008",
536        "Tab": "U+0009",
537        "Delete": "U+007F",
538        "a": "U+0041",
539        "b": "U+0042",
540        "F12": "F12",
541    }
542    for key, keyIdentifier in keyMap.items():
543        await page.keyboard.press(key)
544        assert await lastEvent.evaluate("e => e.keyIdentifier") == keyIdentifier
545
546
547async def test_should_scroll_with_pagedown(page: Page, server):
548    await page.goto(server.PREFIX + "/input/scrollable.html")
549    # A click is required for WebKit to send the event into the body.
550    await page.click("body")
551    await page.keyboard.press("PageDown")
552    # We can't wait for the scroll to finish, so just wait for it to start.
553    await page.wait_for_function("() => scrollY > 0")
554
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)