Best Python code snippet using playwright-python
test_keyboard.py
Source:test_keyboard.py
...13# limitations under the License.14import pytest15from playwright._impl._api_types import Error16from playwright.async_api import Page17async def captureLastKeydown(page):18 lastEvent = await page.evaluate_handle(19 """() => {20 const lastEvent = {21 repeat: false,22 location: -1,23 code: '',24 key: '',25 metaKey: false,26 keyIdentifier: 'unsupported'27 };28 document.addEventListener('keydown', e => {29 lastEvent.repeat = e.repeat;30 lastEvent.location = e.location;31 lastEvent.key = e.key;32 lastEvent.code = e.code;33 lastEvent.metaKey = e.metaKey;34 // keyIdentifier only exists in WebKit, and isn't in TypeScript's lib.35 lastEvent.keyIdentifier = 'keyIdentifier' in e && e.keyIdentifier;36 }, true);37 return lastEvent;38 }"""39 )40 return lastEvent41async def test_keyboard_type_into_a_textarea(page):42 await page.evaluate(43 """44 const textarea = document.createElement('textarea');45 document.body.appendChild(textarea);46 textarea.focus();47 """48 )49 text = "Hello world. I am the text that was typed!"50 await page.keyboard.type(text)51 assert await page.evaluate('document.querySelector("textarea").value') == text52async def test_keyboard_move_with_the_arrow_keys(page, server):53 await page.goto(f"{server.PREFIX}/input/textarea.html")54 await page.type("textarea", "Hello World!")55 assert (56 await page.evaluate("document.querySelector('textarea').value")57 == "Hello World!"58 )59 for _ in "World!":60 await page.keyboard.press("ArrowLeft")61 await page.keyboard.type("inserted ")62 assert (63 await page.evaluate("document.querySelector('textarea').value")64 == "Hello inserted World!"65 )66 await page.keyboard.down("Shift")67 for _ in "inserted ":68 await page.keyboard.press("ArrowLeft")69 await page.keyboard.up("Shift")70 await page.keyboard.press("Backspace")71 assert (72 await page.evaluate("document.querySelector('textarea').value")73 == "Hello World!"74 )75async def test_keyboard_send_a_character_with_elementhandle_press(page, server):76 await page.goto(f"{server.PREFIX}/input/textarea.html")77 textarea = await page.query_selector("textarea")78 await textarea.press("a")79 assert await page.evaluate("document.querySelector('textarea').value") == "a"80 await page.evaluate(81 "() => window.addEventListener('keydown', e => e.preventDefault(), true)"82 )83 await textarea.press("b")84 assert await page.evaluate("document.querySelector('textarea').value") == "a"85async def test_should_send_a_character_with_send_character(page, server):86 await page.goto(server.PREFIX + "/input/textarea.html")87 await page.focus("textarea")88 await page.keyboard.insert_text("å¨")89 assert await page.evaluate('() => document.querySelector("textarea").value') == "å¨"90 await page.evaluate(91 '() => window.addEventListener("keydown", e => e.preventDefault(), true)'92 )93 await page.keyboard.insert_text("a")94 assert await page.evaluate('() => document.querySelector("textarea").value') == "å¨a"95async def test_should_only_emit_input_event(page, server):96 await page.goto(server.PREFIX + "/input/textarea.html")97 await page.focus("textarea")98 page.on("console", "m => console.log(m.text())")99 events = await page.evaluate_handle(100 """() => {101 const events = [];102 document.addEventListener('keydown', e => events.push(e.type));103 document.addEventListener('keyup', e => events.push(e.type));104 document.addEventListener('keypress', e => events.push(e.type));105 document.addEventListener('input', e => events.push(e.type));106 return events;107 }"""108 )109 await page.keyboard.insert_text("hello world")110 assert await events.json_value() == ["input"]111async def test_should_report_shiftkey(page: Page, server, is_mac, is_firefox):112 if is_firefox and is_mac:113 pytest.skip()114 await page.goto(server.PREFIX + "/input/keyboard.html")115 keyboard = page.keyboard116 codeForKey = {"Shift": 16, "Alt": 18, "Control": 17}117 for modifierKey in codeForKey.keys():118 await keyboard.down(modifierKey)119 assert (120 await page.evaluate("() => getResult()")121 == "Keydown: "122 + modifierKey123 + " "124 + modifierKey125 + "Left "126 + str(codeForKey[modifierKey])127 + " ["128 + modifierKey129 + "]"130 )131 await keyboard.down("!")132 # Shift+! will generate a keypress133 if modifierKey == "Shift":134 assert (135 await page.evaluate("() => getResult()")136 == "Keydown: ! Digit1 49 ["137 + modifierKey138 + "]\nKeypress: ! Digit1 33 33 ["139 + modifierKey140 + "]"141 )142 else:143 assert (144 await page.evaluate("() => getResult()")145 == "Keydown: ! Digit1 49 [" + modifierKey + "]"146 )147 await keyboard.up("!")148 assert (149 await page.evaluate("() => getResult()")150 == "Keyup: ! Digit1 49 [" + modifierKey + "]"151 )152 await keyboard.up(modifierKey)153 assert (154 await page.evaluate("() => getResult()")155 == "Keyup: "156 + modifierKey157 + " "158 + modifierKey159 + "Left "160 + str(codeForKey[modifierKey])161 + " []"162 )163async def test_should_report_multiple_modifiers(page: Page, server):164 await page.goto(server.PREFIX + "/input/keyboard.html")165 keyboard = page.keyboard166 await keyboard.down("Control")167 assert (168 await page.evaluate("() => getResult()")169 == "Keydown: Control ControlLeft 17 [Control]"170 )171 await keyboard.down("Alt")172 assert (173 await page.evaluate("() => getResult()")174 == "Keydown: Alt AltLeft 18 [Alt Control]"175 )176 await keyboard.down(";")177 assert (178 await page.evaluate("() => getResult()")179 == "Keydown: ; Semicolon 186 [Alt Control]"180 )181 await keyboard.up(";")182 assert (183 await page.evaluate("() => getResult()")184 == "Keyup: ; Semicolon 186 [Alt Control]"185 )186 await keyboard.up("Control")187 assert (188 await page.evaluate("() => getResult()")189 == "Keyup: Control ControlLeft 17 [Alt]"190 )191 await keyboard.up("Alt")192 assert await page.evaluate("() => getResult()") == "Keyup: Alt AltLeft 18 []"193async def test_should_send_proper_codes_while_typing(page: Page, server):194 await page.goto(server.PREFIX + "/input/keyboard.html")195 await page.keyboard.type("!")196 assert await page.evaluate("() => getResult()") == "\n".join(197 [198 "Keydown: ! Digit1 49 []",199 "Keypress: ! Digit1 33 33 []",200 "Keyup: ! Digit1 49 []",201 ]202 )203 await page.keyboard.type("^")204 assert await page.evaluate("() => getResult()") == "\n".join(205 [206 "Keydown: ^ Digit6 54 []",207 "Keypress: ^ Digit6 94 94 []",208 "Keyup: ^ Digit6 54 []",209 ]210 )211async def test_should_send_proper_codes_while_typing_with_shift(page: Page, server):212 await page.goto(server.PREFIX + "/input/keyboard.html")213 keyboard = page.keyboard214 await keyboard.down("Shift")215 await page.keyboard.type("~")216 assert await page.evaluate("() => getResult()") == "\n".join(217 [218 "Keydown: Shift ShiftLeft 16 [Shift]",219 "Keydown: ~ Backquote 192 [Shift]", # 192 is ` keyCode220 "Keypress: ~ Backquote 126 126 [Shift]", # 126 is ~ charCode221 "Keyup: ~ Backquote 192 [Shift]",222 ]223 )224 await keyboard.up("Shift")225async def test_should_not_type_canceled_events(page: Page, server):226 await page.goto(server.PREFIX + "/input/textarea.html")227 await page.focus("textarea")228 await page.evaluate(229 """() => {230 window.addEventListener('keydown', event => {231 event.stopPropagation();232 event.stopImmediatePropagation();233 if (event.key === 'l')234 event.preventDefault();235 if (event.key === 'o')236 event.preventDefault();237 }, false);238 }"""239 )240 await page.keyboard.type("Hello World!")241 assert (242 await page.eval_on_selector("textarea", "textarea => textarea.value")243 == "He Wrd!"244 )245async def test_should_press_plus(page: Page, server):246 await page.goto(server.PREFIX + "/input/keyboard.html")247 await page.keyboard.press("+")248 assert await page.evaluate("() => getResult()") == "\n".join(249 [250 "Keydown: + Equal 187 []", # 192 is ` keyCode251 "Keypress: + Equal 43 43 []", # 126 is ~ charCode252 "Keyup: + Equal 187 []",253 ]254 )255async def test_should_press_shift_plus(page: Page, server):256 await page.goto(server.PREFIX + "/input/keyboard.html")257 await page.keyboard.press("Shift++")258 assert await page.evaluate("() => getResult()") == "\n".join(259 [260 "Keydown: Shift ShiftLeft 16 [Shift]",261 "Keydown: + Equal 187 [Shift]", # 192 is ` keyCode262 "Keypress: + Equal 43 43 [Shift]", # 126 is ~ charCode263 "Keyup: + Equal 187 [Shift]",264 "Keyup: Shift ShiftLeft 16 []",265 ]266 )267async def test_should_support_plus_separated_modifiers(page: Page, server):268 await page.goto(server.PREFIX + "/input/keyboard.html")269 await page.keyboard.press("Shift+~")270 assert await page.evaluate("() => getResult()") == "\n".join(271 [272 "Keydown: Shift ShiftLeft 16 [Shift]",273 "Keydown: ~ Backquote 192 [Shift]", # 192 is ` keyCode274 "Keypress: ~ Backquote 126 126 [Shift]", # 126 is ~ charCode275 "Keyup: ~ Backquote 192 [Shift]",276 "Keyup: Shift ShiftLeft 16 []",277 ]278 )279async def test_should_suport_multiple_plus_separated_modifiers(page: Page, server):280 await page.goto(server.PREFIX + "/input/keyboard.html")281 await page.keyboard.press("Control+Shift+~")282 assert await page.evaluate("() => getResult()") == "\n".join(283 [284 "Keydown: Control ControlLeft 17 [Control]",285 "Keydown: Shift ShiftLeft 16 [Control Shift]",286 "Keydown: ~ Backquote 192 [Control Shift]", # 192 is ` keyCode287 "Keyup: ~ Backquote 192 [Control Shift]",288 "Keyup: Shift ShiftLeft 16 [Control]",289 "Keyup: Control ControlLeft 17 []",290 ]291 )292async def test_should_shift_raw_codes(page: Page, server):293 await page.goto(server.PREFIX + "/input/keyboard.html")294 await page.keyboard.press("Shift+Digit3")295 assert await page.evaluate("() => getResult()") == "\n".join(296 [297 "Keydown: Shift ShiftLeft 16 [Shift]",298 "Keydown: # Digit3 51 [Shift]", # 51 is # keyCode299 "Keypress: # Digit3 35 35 [Shift]", # 35 is # charCode300 "Keyup: # Digit3 51 [Shift]",301 "Keyup: Shift ShiftLeft 16 []",302 ]303 )304async def test_should_specify_repeat_property(page: Page, server):305 await page.goto(server.PREFIX + "/input/textarea.html")306 await page.focus("textarea")307 lastEvent = await captureLastKeydown(page)308 await page.keyboard.down("a")309 assert await lastEvent.evaluate("e => e.repeat") is False310 await page.keyboard.press("a")311 assert await lastEvent.evaluate("e => e.repeat")312 await page.keyboard.down("b")313 assert await lastEvent.evaluate("e => e.repeat") is False314 await page.keyboard.down("b")315 assert await lastEvent.evaluate("e => e.repeat")316 await page.keyboard.up("a")317 await page.keyboard.down("a")318 assert await lastEvent.evaluate("e => e.repeat") is False319async def test_should_type_all_kinds_of_characters(page: Page, server):320 await page.goto(server.PREFIX + "/input/textarea.html")321 await page.focus("textarea")322 text = "This text goes onto two lines.\nThis character is å¨."323 await page.keyboard.type(text)324 assert await page.eval_on_selector("textarea", "t => t.value") == text325async def test_should_specify_location(page: Page, server):326 await page.goto(server.PREFIX + "/input/textarea.html")327 lastEvent = await captureLastKeydown(page)328 textarea = await page.query_selector("textarea")329 assert textarea330 await textarea.press("Digit5")331 assert await lastEvent.evaluate("e => e.location") == 0332 await textarea.press("ControlLeft")333 assert await lastEvent.evaluate("e => e.location") == 1334 await textarea.press("ControlRight")335 assert await lastEvent.evaluate("e => e.location") == 2336 await textarea.press("NumpadSubtract")337 assert await lastEvent.evaluate("e => e.location") == 3338async def test_should_press_enter(page: Page, server):339 await page.set_content("<textarea></textarea>")340 await page.focus("textarea")341 lastEventHandle = await captureLastKeydown(page)342 async def testEnterKey(key, expectedKey, expectedCode):343 await page.keyboard.press(key)344 lastEvent = await lastEventHandle.json_value()345 assert lastEvent["key"] == expectedKey346 assert lastEvent["code"] == expectedCode347 value = await page.eval_on_selector("textarea", "t => t.value")348 assert value == "\n"349 await page.eval_on_selector("textarea", "t => t.value = ''")350 await testEnterKey("Enter", "Enter", "Enter")351 await testEnterKey("NumpadEnter", "Enter", "NumpadEnter")352 await testEnterKey("\n", "Enter", "Enter")353 await testEnterKey("\r", "Enter", "Enter")354async def test_should_throw_unknown_keys(page: Page, server):355 with pytest.raises(Error) as exc:356 await page.keyboard.press("NotARealKey")357 assert exc.value.message == 'Unknown key: "NotARealKey"'358 with pytest.raises(Error) as exc:359 await page.keyboard.press("Ñ")360 assert exc.value.message == 'Unknown key: "Ñ"'361 with pytest.raises(Error) as exc:362 await page.keyboard.press("ð")363 assert exc.value.message == 'Unknown key: "ð"'364async def test_should_type_emoji(page: Page, server):365 await page.goto(server.PREFIX + "/input/textarea.html")366 await page.type("textarea", "ð¹ Tokyo street Japan ð¯ðµ")367 assert (368 await page.eval_on_selector("textarea", "textarea => textarea.value")369 == "ð¹ Tokyo street Japan ð¯ðµ"370 )371async def test_should_type_emoji_into_an_iframe(page: Page, server, utils):372 await page.goto(server.EMPTY_PAGE)373 await utils.attach_frame(page, "emoji-test", server.PREFIX + "/input/textarea.html")374 frame = page.frames[1]375 textarea = await frame.query_selector("textarea")376 assert textarea377 await textarea.type("ð¹ Tokyo street Japan ð¯ðµ")378 assert (379 await frame.eval_on_selector("textarea", "textarea => textarea.value")380 == "ð¹ Tokyo street Japan ð¯ðµ"381 )382async def test_should_handle_select_all(page: Page, server, is_mac):383 await page.goto(server.PREFIX + "/input/textarea.html")384 textarea = await page.query_selector("textarea")385 assert textarea386 await textarea.type("some text")387 modifier = "Meta" if is_mac else "Control"388 await page.keyboard.down(modifier)389 await page.keyboard.press("a")390 await page.keyboard.up(modifier)391 await page.keyboard.press("Backspace")392 assert await page.eval_on_selector("textarea", "textarea => textarea.value") == ""393async def test_should_be_able_to_prevent_select_all(page, server, is_mac):394 await page.goto(server.PREFIX + "/input/textarea.html")395 textarea = await page.query_selector("textarea")396 await textarea.type("some text")397 await page.eval_on_selector(398 "textarea",399 """textarea => {400 textarea.addEventListener('keydown', event => {401 if (event.key === 'a' && (event.metaKey || event.ctrlKey))402 event.preventDefault();403 }, false);404 }""",405 )406 modifier = "Meta" if is_mac else "Control"407 await page.keyboard.down(modifier)408 await page.keyboard.press("a")409 await page.keyboard.up(modifier)410 await page.keyboard.press("Backspace")411 assert (412 await page.eval_on_selector("textarea", "textarea => textarea.value")413 == "some tex"414 )415@pytest.mark.only_platform("darwin")416async def test_should_support_macos_shortcuts(page, server, is_firefox, is_mac):417 await page.goto(server.PREFIX + "/input/textarea.html")418 textarea = await page.query_selector("textarea")419 await textarea.type("some text")420 # select one word backwards421 await page.keyboard.press("Shift+Control+Alt+KeyB")422 await page.keyboard.press("Backspace")423 assert (424 await page.eval_on_selector("textarea", "textarea => textarea.value") == "some "425 )426async def test_should_press_the_meta_key(page, server, is_firefox, is_mac):427 lastEvent = await captureLastKeydown(page)428 await page.keyboard.press("Meta")429 v = await lastEvent.json_value()430 metaKey = v["metaKey"]431 key = v["key"]432 code = v["code"]433 if is_firefox and not is_mac:434 assert key == "OS"435 else:436 assert key == "Meta"437 if is_firefox:438 assert code == "OSLeft"439 else:440 assert code == "MetaLeft"441 if is_firefox and not is_mac:442 assert metaKey is False443 else:444 assert metaKey445async def test_should_work_after_a_cross_origin_navigation(page, server):446 await page.goto(server.PREFIX + "/empty.html")447 await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")448 lastEvent = await captureLastKeydown(page)449 await page.keyboard.press("a")450 assert await lastEvent.evaluate("l => l.key") == "a"451# event.keyIdentifier has been removed from all browsers except WebKit452@pytest.mark.only_browser("webkit")453async def test_should_expose_keyIdentifier_in_webkit(page, server):454 lastEvent = await captureLastKeydown(page)455 keyMap = {456 "ArrowUp": "Up",457 "ArrowDown": "Down",458 "ArrowLeft": "Left",459 "ArrowRight": "Right",460 "Backspace": "U+0008",461 "Tab": "U+0009",462 "Delete": "U+007F",463 "a": "U+0041",464 "b": "U+0042",465 "F12": "F12",466 }467 for key, keyIdentifier in keyMap.items():468 await page.keyboard.press(key)...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!