How to use element_handle method in Playwright Python

Best Python code snippet using playwright-python

test_element_handle.py

Source:test_element_handle.py Github

copy

Full Screen

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 at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14import pytest15from playwright.sync_api import Error16def test_bounding_box(page, server):17 page.set_viewport_size({"width": 500, "height": 500})18 page.goto(server.PREFIX + "/grid.html")19 element_handle = page.query_selector(".box:nth-of-type(13)")20 box = element_handle.bounding_box()21 assert box == {"x": 100, "y": 50, "width": 50, "height": 50}22def test_bounding_box_handle_nested_frames(page, server):23 page.set_viewport_size({"width": 500, "height": 500})24 page.goto(server.PREFIX + "/frames/nested-frames.html")25 nested_frame = page.frame(name="dos")26 element_handle = nested_frame.query_selector("div")27 box = element_handle.bounding_box()28 assert box == {"x": 24, "y": 224, "width": 268, "height": 18}29def test_bounding_box_return_null_for_invisible_elements(page, server):30 page.set_content('<div style="display:none">hi</div>')31 element = page.query_selector("div")32 assert element.bounding_box() is None33def test_bounding_box_force_a_layout(page, server):34 page.set_viewport_size({"width": 500, "height": 500})35 page.set_content('<div style="width: 100px; height: 100px">hello</div>')36 element_handle = page.query_selector("div")37 page.evaluate('element => element.style.height = "200px"', element_handle)38 box = element_handle.bounding_box()39 assert box == {"x": 8, "y": 8, "width": 100, "height": 200}40def test_bounding_box_with_SVG_nodes(page, server):41 page.set_content(42 """<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">43 <rect id="theRect" x="30" y="50" width="200" height="300"></rect>44 </svg>"""45 )46 element = page.query_selector("#therect")47 pw_bounding_box = element.bounding_box()48 web_bounding_box = page.evaluate(49 """e => {50 rect = e.getBoundingClientRect()51 return {x: rect.x, y: rect.y, width: rect.width, height: rect.height}52 }""",53 element,54 )55 assert pw_bounding_box == web_bounding_box56def test_bounding_box_with_page_scale(browser, server):57 context = browser.new_context(58 viewport={"width": 400, "height": 400, "is_mobile": True}59 )60 page = context.new_page()61 page.goto(server.PREFIX + "/input/button.html")62 button = page.query_selector("button")63 button.evaluate(64 """button => {65 document.body.style.margin = '0'66 button.style.borderWidth = '0'67 button.style.width = '200px'68 button.style.height = '20px'69 button.style.marginLeft = '17px'70 button.style.marginTop = '23px'71 }"""72 )73 box = button.bounding_box()74 assert round(box["x"] * 100) == 17 * 10075 assert round(box["y"] * 100) == 23 * 10076 assert round(box["width"] * 100) == 200 * 10077 assert round(box["height"] * 100) == 20 * 10078 context.close()79def test_bounding_box_when_inline_box_child_is_outside_of_viewport(page, server):80 page.set_content(81 """82 <style>83 i {84 position: absolute85 top: -1000px86 }87 body {88 margin: 089 font-size: 12px90 }91 </style>92 <span><i>woof</i><b>doggo</b></span>93 """94 )95 handle = page.query_selector("span")96 box = handle.bounding_box()97 web_bounding_box = handle.evaluate(98 """e => {99 rect = e.getBoundingClientRect();100 return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};101 }"""102 )103 def roundbox(b):104 return {105 "x": round(b["x"] * 100),106 "y": round(b["y"] * 100),107 "width": round(b["width"] * 100),108 "height": round(b["height"] * 100),109 }110 assert roundbox(box) == roundbox(web_bounding_box)111def test_content_frame(page, server, utils):112 page.goto(server.EMPTY_PAGE)113 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)114 element_handle = page.query_selector("#frame1")115 frame = element_handle.content_frame()116 assert frame == page.frames[1]117def test_content_frame_for_non_iframes(page, server, utils):118 page.goto(server.EMPTY_PAGE)119 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)120 frame = page.frames[1]121 element_handle = frame.evaluate_handle("document.body")122 assert element_handle.content_frame() is None123def test_content_frame_for_document_element(page, server, utils):124 page.goto(server.EMPTY_PAGE)125 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)126 frame = page.frames[1]127 element_handle = frame.evaluate_handle("document.documentElement")128 assert element_handle.content_frame() is None129def test_owner_frame(page, server, utils):130 page.goto(server.EMPTY_PAGE)131 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)132 frame = page.frames[1]133 element_handle = frame.evaluate_handle("document.body")134 assert element_handle.owner_frame() == frame135def test_owner_frame_for_cross_process_iframes(page, server, utils):136 page.goto(server.EMPTY_PAGE)137 utils.attach_frame(page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html")138 frame = page.frames[1]139 element_handle = frame.evaluate_handle("document.body")140 assert element_handle.owner_frame() == frame141def test_owner_frame_for_document(page, server, utils):142 page.goto(server.EMPTY_PAGE)143 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)144 frame = page.frames[1]145 element_handle = frame.evaluate_handle("document")146 assert element_handle.owner_frame() == frame147def test_owner_frame_for_iframe_elements(page, server, utils):148 page.goto(server.EMPTY_PAGE)149 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)150 frame = page.main_frame151 element_handle = frame.evaluate_handle('document.querySelector("#frame1")')152 print(element_handle)153 assert element_handle.owner_frame() == frame154def test_owner_frame_for_cross_frame_evaluations(page, server, utils):155 page.goto(server.EMPTY_PAGE)156 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)157 frame = page.main_frame158 element_handle = frame.evaluate_handle(159 'document.querySelector("#frame1").contentWindow.document.body'160 )161 assert element_handle.owner_frame() == frame.child_frames[0]162def test_owner_frame_for_detached_elements(page, server):163 page.goto(server.EMPTY_PAGE)164 div_handle = page.evaluate_handle(165 """() => {166 div = document.createElement('div');167 document.body.appendChild(div);168 return div;169 }"""170 )171 assert div_handle.owner_frame() == page.main_frame172 page.evaluate(173 """() => {174 div = document.querySelector('div')175 document.body.removeChild(div)176 }"""177 )178 assert div_handle.owner_frame() == page.main_frame179def test_click(page, server):180 page.goto(server.PREFIX + "/input/button.html")181 button = page.query_selector("button")182 button.click()183 assert page.evaluate("result") == "Clicked"184def test_click_with_node_removed(page, server):185 page.goto(server.PREFIX + "/input/button.html")186 page.evaluate('delete window["Node"]')187 button = page.query_selector("button")188 button.click()189 assert page.evaluate("result") == "Clicked"190def test_click_for_shadow_dom_v1(page, server):191 page.goto(server.PREFIX + "/shadow.html")192 button_handle = page.evaluate_handle("button")193 button_handle.click()194 assert page.evaluate("clicked")195def test_click_for_TextNodes(page, server):196 page.goto(server.PREFIX + "/input/button.html")197 buttonTextNode = page.evaluate_handle('document.querySelector("button").firstChild')198 buttonTextNode.click()199 assert page.evaluate("result") == "Clicked"200def test_click_throw_for_detached_nodes(page, server):201 page.goto(server.PREFIX + "/input/button.html")202 button = page.query_selector("button")203 page.evaluate("button => button.remove()", button)204 with pytest.raises(Error) as exc_info:205 button.click()206 assert "Element is not attached to the DOM" in exc_info.value.message207def test_click_throw_for_hidden_nodes_with_force(page, server):208 page.goto(server.PREFIX + "/input/button.html")209 button = page.query_selector("button")210 page.evaluate('button => button.style.display = "none"', button)211 with pytest.raises(Error) as exc_info:212 button.click(force=True)213 assert "Element is not visible" in exc_info.value.message214def test_click_throw_for_recursively_hidden_nodes_with_force(page, server):215 page.goto(server.PREFIX + "/input/button.html")216 button = page.query_selector("button")217 page.evaluate('button => button.parentElement.style.display = "none"', button)218 with pytest.raises(Error) as exc_info:219 button.click(force=True)220 assert "Element is not visible" in exc_info.value.message221def test_click_throw_for__br__elements_with_force(page, server):222 page.set_content("hello<br>goodbye")223 br = page.query_selector("br")224 with pytest.raises(Error) as exc_info:225 br.click(force=True)226 assert "Element is outside of the viewport" in exc_info.value.message227def test_double_click_the_button(page, server):228 page.goto(server.PREFIX + "/input/button.html")229 page.evaluate(230 """() => {231 window.double = false;232 button = document.querySelector('button');233 button.addEventListener('dblclick', event => {234 window.double = true;235 });236 }"""237 )238 button = page.query_selector("button")239 button.dblclick()240 assert page.evaluate("double")241 assert page.evaluate("result") == "Clicked"242def test_hover(page, server):243 page.goto(server.PREFIX + "/input/scrollable.html")244 button = page.query_selector("#button-6")245 button.hover()246 assert page.evaluate('document.querySelector("button:hover").id') == "button-6"247def test_hover_when_node_is_removed(page, server):248 page.goto(server.PREFIX + "/input/scrollable.html")249 page.evaluate('delete window["Node"]')250 button = page.query_selector("#button-6")251 button.hover()252 assert page.evaluate('document.querySelector("button:hover").id') == "button-6"253def test_scroll(page, server):254 page.goto(server.PREFIX + "/offscreenbuttons.html")255 for i in range(11):256 button = page.query_selector(f"#btn{i}")257 before = button.evaluate(258 """button => {259 return button.getBoundingClientRect().right - window.innerWidth260 }"""261 )262 assert before == 10 * i263 button.scroll_into_view_if_needed()264 after = button.evaluate(265 """button => {266 return button.getBoundingClientRect().right - window.innerWidth267 }"""268 )269 assert after <= 0270 page.evaluate("() => window.scrollTo(0, 0)")271def test_scroll_should_throw_for_detached_element(page, server):272 page.set_content("<div>Hello</div>")273 div = page.query_selector("div")274 div.evaluate("div => div.remove()")275 with pytest.raises(Error) as exc_info:276 div.scroll_into_view_if_needed()277 assert "Element is not attached to the DOM" in exc_info.value.message278def test_should_timeout_waiting_for_visible(page):279 page.set_content('<div style="display:none">Hello</div>')280 div = page.query_selector("div")281 with pytest.raises(Error) as exc_info:282 div.scroll_into_view_if_needed(timeout=3000)283 assert "element is not visible" in exc_info.value.message284def test_fill_input(page, server):285 page.goto(server.PREFIX + "/input/textarea.html")286 handle = page.query_selector("input")287 handle.fill("some value")288 assert page.evaluate("result") == "some value"289def test_fill_input_when_Node_is_removed(page, server):290 page.goto(server.PREFIX + "/input/textarea.html")291 page.evaluate('delete window["Node"]')292 handle = page.query_selector("input")293 handle.fill("some value")294 assert page.evaluate("result") == "some value"295def test_select_textarea(page, server, is_firefox):296 page.goto(server.PREFIX + "/input/textarea.html")297 textarea = page.query_selector("textarea")298 textarea.evaluate('textarea => textarea.value = "some value"')299 textarea.select_text()300 if is_firefox:301 assert textarea.evaluate("el => el.selectionStart") == 0302 assert textarea.evaluate("el => el.selectionEnd") == 10303 else:304 assert page.evaluate("() => window.getSelection().toString()") == "some value"305def test_select_input(page, server, is_firefox):306 page.goto(server.PREFIX + "/input/textarea.html")307 input = page.query_selector("input")308 input.evaluate('input => input.value = "some value"')309 input.select_text()310 if is_firefox:311 assert input.evaluate("el => el.selectionStart") == 0312 assert input.evaluate("el => el.selectionEnd") == 10313 else:314 assert page.evaluate("() => window.getSelection().toString()") == "some value"315def test_select_text_select_plain_div(page, server):316 page.goto(server.PREFIX + "/input/textarea.html")317 div = page.query_selector("div.plain")318 div.select_text()319 assert page.evaluate("() => window.getSelection().toString()") == "Plain div"320def test_select_text_timeout_waiting_for_invisible_element(page, server):321 page.goto(server.PREFIX + "/input/textarea.html")322 textarea = page.query_selector("textarea")323 textarea.evaluate('e => e.style.display = "none"')324 with pytest.raises(Error) as exc_info:325 textarea.select_text(timeout=3000)326 assert "element is not visible" in exc_info.value.message327def test_a_nice_preview(page, server):328 page.goto(f"{server.PREFIX}/dom.html")329 outer = page.query_selector("#outer")330 inner = page.query_selector("#inner")331 check = page.query_selector("#check")332 text = inner.evaluate_handle("e => e.firstChild")333 page.evaluate("1") # Give them a chance to calculate the preview.334 assert str(outer) == 'JSHandle@<div id="outer" name="value">…</div>'335 assert str(inner) == 'JSHandle@<div id="inner">Text,↵more text</div>'336 assert str(text) == "JSHandle@#text=Text,↵more text"337 assert (338 str(check) == 'JSHandle@<input checked id="check" foo="bar"" type="checkbox"/>'339 )340def test_get_attribute(page, server):341 page.goto(f"{server.PREFIX}/dom.html")342 handle = page.query_selector("#outer")343 assert handle.get_attribute("name") == "value"344 assert page.get_attribute("#outer", "name") == "value"345def test_inner_html(page, server):346 page.goto(f"{server.PREFIX}/dom.html")347 handle = page.query_selector("#outer")348 assert handle.inner_html() == '<div id="inner">Text,\nmore text</div>'349 assert page.inner_html("#outer") == '<div id="inner">Text,\nmore text</div>'350def test_inner_text(page, server):351 page.goto(f"{server.PREFIX}/dom.html")352 handle = page.query_selector("#inner")353 assert handle.inner_text() == "Text, more text"354 assert page.inner_text("#inner") == "Text, more text"355def test_inner_text_should_throw(page, server):356 page.set_content("<svg>text</svg>")357 with pytest.raises(Error) as exc_info1:358 page.inner_text("svg")359 assert "Not an HTMLElement" in exc_info1.value.message360 handle = page.query_selector("svg")361 with pytest.raises(Error) as exc_info2:362 handle.inner_text()363 assert "Not an HTMLElement" in exc_info2.value.message364def test_text_content(page, server):365 page.goto(f"{server.PREFIX}/dom.html")366 handle = page.query_selector("#inner")367 assert handle.text_content() == "Text,\nmore text"368 assert page.text_content("#inner") == "Text,\nmore text"369def test_check_the_box(page):370 page.set_content('<input id="checkbox" type="checkbox"></input>')371 input = page.query_selector("input")372 input.check()373 assert page.evaluate("checkbox.checked")374def test_uncheck_the_box(page):375 page.set_content('<input id="checkbox" type="checkbox" checked></input>')376 input = page.query_selector("input")377 input.uncheck()378 assert page.evaluate("checkbox.checked") is False379def test_select_single_option(page, server):380 page.goto(server.PREFIX + "/input/select.html")381 select = page.query_selector("select")382 select.select_option(value="blue")383 assert page.evaluate("result.onInput") == ["blue"]384 assert page.evaluate("result.onChange") == ["blue"]385def test_focus_a_button(page, server):386 page.goto(server.PREFIX + "/input/button.html")387 button = page.query_selector("button")388 assert button.evaluate("button => document.activeElement === button") is False389 button.focus()390 assert button.evaluate("button => document.activeElement === button")391def test_is_visible_and_is_hidden_should_work(page):392 page.set_content("<div>Hi</div><span></span>")393 div = page.query_selector("div")394 assert div.is_visible()395 assert div.is_hidden() is False396 assert page.is_visible("div")397 assert page.is_hidden("div") is False398 span = page.query_selector("span")399 assert span.is_visible() is False400 assert span.is_hidden()401 assert page.is_visible("span") is False402 assert page.is_hidden("span")403def test_is_enabled_and_is_disabled_should_work(page):404 page.set_content(405 """406 <button disabled>button1</button>407 <button>button2</button>408 <div>div</div>409 """410 )411 div = page.query_selector("div")412 assert div.is_enabled()413 assert div.is_disabled() is False414 assert page.is_enabled("div")415 assert page.is_disabled("div") is False416 button1 = page.query_selector(":text('button1')")417 assert button1.is_enabled() is False418 assert button1.is_disabled()419 assert page.is_enabled(":text('button1')") is False420 assert page.is_disabled(":text('button1')")421 button2 = page.query_selector(":text('button2')")422 assert button2.is_enabled()423 assert button2.is_disabled() is False424 assert page.is_enabled(":text('button2')")425 assert page.is_disabled(":text('button2')") is False426def test_is_editable_should_work(page):427 page.set_content("<input id=input1 disabled><textarea></textarea><input id=input2>")428 page.eval_on_selector("textarea", "t => t.readOnly = true")429 input1 = page.query_selector("#input1")430 assert input1.is_editable() is False431 assert page.is_editable("#input1") is False432 input2 = page.query_selector("#input2")433 assert input2.is_editable()434 assert page.is_editable("#input2")435 textarea = page.query_selector("textarea")436 assert textarea.is_editable() is False437 assert page.is_editable("textarea") is False438def test_is_checked_should_work(page):439 page.set_content('<input type="checkbox" checked><div>Not a checkbox</div>')440 handle = page.query_selector("input")441 assert handle.is_checked()442 assert page.is_checked("input")443 handle.evaluate("input => input.checked = false")444 assert handle.is_checked() is False445 assert page.is_checked("input") is False446 with pytest.raises(Error) as exc_info:447 page.is_checked("div")...

Full Screen

Full Screen

test_shell_element.py

Source:test_shell_element.py Github

copy

Full Screen

...83 with self.subTest(transform=transform):84 for element_handle in self.elements:85 if not (element_handle in self.thermal_elements):86 with self.subTest(element=element_handle):87 element = element_handle(transform, self.con)88 fail = elements.TestElementResidual(element, self.elem_index, self.time, self.xpts,89 self.vars, self.dvars, self.ddvars, dh,90 self.print_level, self.atol, rtol)91 self.assertFalse(fail)92 def test_element_jacobian(self):93 # Loop through every combination of transform type and shell element class and test Jacobian94 for transform in self.transforms:95 with self.subTest(transform=transform):96 for element_handle in self.elements:97 with self.subTest(element=element_handle):98 element = element_handle(transform, self.con)99 fail = elements.TestElementJacobian(element, self.elem_index, self.time, self.xpts,100 self.vars, self.dvars, self.ddvars, -1, self.dh,101 self.print_level, self.atol, self.rtol)102 self.assertFalse(fail)103 def test_adj_res_product(self):104 # Loop through every combination of transform type and shell element class and test adjoint residual-dvsens product105 for transform in self.transforms:106 with self.subTest(transform=transform):107 for element_handle in self.elements:108 with self.subTest(element=element_handle):109 element = element_handle(transform, self.con)110 dvs = element.getDesignVars(self.elem_index)111 fail = elements.TestAdjResProduct(element, self.elem_index, self.time, self.xpts,112 self.vars, self.dvars, self.ddvars, dvs, self.dh,113 self.print_level, self.atol, self.rtol)114 self.assertFalse(fail)115 def test_adj_res_xpt_product(self):116 # Loop through every combination of transform type and shell element class and test adjoint residual-xptsens product117 for transform in self.transforms:118 with self.subTest(transform=transform):119 for element_handle in self.elements:120 with self.subTest(element=element_handle):121 element = element_handle(transform, self.con)122 fail = elements.TestAdjResXptProduct(element, self.elem_index, self.time, self.xpts,123 self.vars, self.dvars, self.ddvars, self.dh,124 self.print_level, self.atol, self.rtol)125 self.assertFalse(fail)126 def test_element_mat_dv_sens(self):127 # Loop through every combination of transform type and shell element class and element matrix inner product sens128 for transform in self.transforms:129 with self.subTest(transform=transform):130 for element_handle in self.elements:131 with self.subTest(element=element_handle):132 element = element_handle(transform, self.con)133 dvs = element.getDesignVars(self.elem_index)134 for matrix_type in self.matrix_types:135 with self.subTest(matrix_type=matrix_type):136 fail = elements.TestElementMatDVSens(element, matrix_type, self.elem_index,137 self.time, self.xpts, self.vars, dvs, self.dh,138 self.print_level, self.atol, self.rtol)139 self.assertFalse(fail)140 def test_element_mat_sv_sens(self):141 # Loop through every combination of model and basis class and test element matrix inner product sens142 for transform in self.transforms:143 with self.subTest(transform=transform):144 for element_handle in self.elements:145 with self.subTest(element=element_handle):146 element = element_handle(transform, self.con)147 fail = elements.TestElementMatSVSens(element, TACS.GEOMETRIC_STIFFNESS_MATRIX, self.elem_index,148 self.time, self.xpts, self.vars, self.dh,149 self.print_level, self.atol, self.rtol)...

Full Screen

Full Screen

alarms.py

Source:alarms.py Github

copy

Full Screen

1import weakref2from date_and_time import TimeSpan3import date_and_time4import elements5import services6import sims4.reload7import sims4.log8logger = sims4.log.Logger('Alarms')9with sims4.reload.protected(globals()):10 _ALARM_ELEMENT_HANDLES = {}11def add_alarm(owner,12 time_span,13 callback,14 repeating=False,15 repeating_time_span=None,16 use_sleep_time=True):17 ts = services.time_service()18 if ts.sim_timeline is None:19 logger.error('Attempting to create alarm after TimeService shutdown.')20 return21 if use_sleep_time:22 initial_time = ts.sim_timeline.now23 else:24 initial_time = ts.sim_timeline.future25 return AlarmHandle(owner,26 callback,27 ts.sim_timeline,28 initial_time + time_span,29 repeating=repeating,30 repeat_interval=repeating_time_span or time_span,31 accurate_repeat=use_sleep_time)32def add_alarm_real_time(owner,33 time_span,34 callback,35 repeating=False,36 use_sleep_time=True):37 ts = services.time_service()38 return AlarmHandle(owner,39 callback,40 ts.wall_clock_timeline,41 ts.wall_clock_timeline.now + time_span,42 repeating=repeating,43 repeat_interval=time_span,44 accurate_repeat=use_sleep_time)45def cancel_alarm(handle):46 handle.cancel()47class AlarmHandle:48 __qualname__ = 'AlarmHandle'49 __slots__ = ('_element_handle', '_owner_ref', '__weakref__')50 def __init__(self,51 owner,52 callback,53 t,54 when,55 repeating=False,56 repeat_interval=None,57 accurate_repeat=True):58 if owner is None:59 raise ValueError('Alarm created without owner')60 if not repeating:61 e = AlarmElement(callback)62 elif accurate_repeat:63 e = RepeatingAlarmElement(repeat_interval, callback)64 else:65 e = LossyRepeatingAlarmElement(repeat_interval, callback)66 self._element_handle = t.schedule(e, when)67 _register_auto_cleanup(self)68 self._owner_ref = weakref.ref(owner, self._owner_destroyed_callback)69 def _teardown(self):70 self._element_handle = None71 self._owner_ref = None72 @property73 def owner(self):74 if self._owner_ref is not None:75 return self._owner_ref()76 def _owner_destroyed_callback(self, _):77 if hasattr(self, '_element_handle'):78 self.cancel()79 def cancel(self):80 if self._element_handle is None:81 return82 _unregister_auto_cleanup(self._element_handle)83 timeline = self._element_handle.timeline84 if self._element_handle.is_active:85 self._element_handle._clear_element()86 else:87 timeline.hard_stop(self._element_handle)88 @property89 def timeline(self):90 return self._element_handle.timeline91 def get_remaining_time(self):92 timeline = self._element_handle.timeline93 when = self._element_handle.when94 if when is None:95 return TimeSpan.ZERO96 return when - timeline.now97 @property98 def finishing_time(self):99 when = self._element_handle.when100 if when is None:101 return date_and_time.DATE_AND_TIME_ZERO102 return when103class AlarmElement(elements.FunctionElement):104 __qualname__ = 'AlarmElement'105 __slots__ = ()106 @classmethod107 def shortname(cls):108 return 'Alarm'109 def __init__(self, callback):110 super().__init__(callback)111 def _run(self, t):112 result = self.callback(_lookup_alarm_handle(self._element_handle))113 _unregister_auto_cleanup(self._element_handle)114 return result115 def _teardown(self):116 alarm_handle = _lookup_alarm_handle(self._element_handle)117 if alarm_handle is not None:118 _unregister_auto_cleanup(self._element_handle)119 alarm_handle._teardown()120 super()._teardown()121class RepeatingAlarmElement(AlarmElement):122 __qualname__ = 'RepeatingAlarmElement'123 __slots__ = 'interval'124 @classmethod125 def shortname(cls):126 return 'RepeatingAlarm'127 def __init__(self, interval, callback):128 super().__init__(callback)129 self.interval = interval130 @staticmethod131 def timeline_now(t):132 return t.now133 def _run(self, t):134 element_handle = self._element_handle135 result = self.callback(_lookup_alarm_handle(element_handle))136 if not element_handle.canceled:137 when = self.timeline_now(t) + self.interval138 handle = t.schedule(self, when)139 return result140 def __str__(self):141 return '<{}; {}@{}; {}>'.format(142 self.shortname(), self.callback.__qualname__,143 self.callback.__code__.co_firstlineno, self.interval)144class LossyRepeatingAlarmElement(RepeatingAlarmElement):145 __qualname__ = 'LossyRepeatingAlarmElement'146 @staticmethod147 def timeline_now(t):148 return t.future149def _register_auto_cleanup(alarm_handle):150 element_handle = alarm_handle._element_handle151 def on_alarm_handle_collected(_):152 ehid = id(element_handle)153 if ehid in _ALARM_ELEMENT_HANDLES:154 del _ALARM_ELEMENT_HANDLES[ehid]155 timeline = element_handle.timeline156 timeline.hard_stop(element_handle)157 _ALARM_ELEMENT_HANDLES[id(element_handle)] = weakref.ref(158 alarm_handle, on_alarm_handle_collected)159def _unregister_auto_cleanup(element_handle):160 ehid = id(element_handle)161 if ehid in _ALARM_ELEMENT_HANDLES:162 del _ALARM_ELEMENT_HANDLES[ehid]163def _lookup_alarm_handle(element_handle):164 ehid = id(element_handle)165 return _ALARM_ELEMENT_HANDLES.get(ehid)()166def get_alarm_data_for_gsi():167 alarm_data = []168 for alarm_handle_ref in tuple(_ALARM_ELEMENT_HANDLES.values()):169 alarm_handle = alarm_handle_ref()170 if alarm_handle is None:171 pass172 element_handle = alarm_handle._element_handle173 element = element_handle.element174 if element is None:175 pass176 entry = {}177 entry['time'] = str(element_handle.when)178 entry['ticks'] = alarm_handle.get_remaining_time().in_ticks()179 entry['time_left'] = str(alarm_handle.get_remaining_time())180 owner = alarm_handle._owner_ref()181 if owner is None:182 owner_name = 'None Owner'183 else:184 owner_name = str(owner)185 entry['owner'] = owner_name186 entry['handle'] = id(alarm_handle)187 entry['callback'] = str(element.callback)188 alarm_data.append(entry)189 sort_key_fn = lambda data: data['ticks']190 alarm_data = sorted(alarm_data, key=sort_key_fn)...

Full Screen

Full Screen

middlewares.py

Source:middlewares.py Github

copy

Full Screen

...67 lambda req: asyncio.create_task(self._get_intercept_request_body(req, page, request, response)))68 if request.select_element:69 # {'element_selector': {'action': '', 'value': ''}70 for element_selector, instructions in request.select_element.items():71 element_handle = await self.select_element_handle(element_selector, page)72 action = instructions.get('action')73 action_value = instructions.get('value')74 await self.make_action(action, action_value, element_handle, element_selector, page)75 if request.exec_pup:76 exec(request.exec_pup)77 if request.wait_for:78 await page.waitFor(request.wait_for,79 timeout=120000)80 if request.screenshot:81 request.meta['screenshot'] = await page.screenshot()82 if request.screenshot_element:83 element_ss_selector = request.screenshot_element84 await page.waitForSelector(element_ss_selector)85 element_ss = await page.querySelector(element_ss_selector)86 request.meta['element_ss'] = await element_ss.screenshot()87 self.html_response = await self.finish_puppeteer_scrape(page, request, response)88 return self.html_response89 except Exception as e:90 spider.logger.error(e)91 await page.close()92 async def _get_intercept_request_body(self, on_request, page, request, response):93 if on_request.url == request.intercept_request:94 response_text = await on_request.response.text()95 self.intercept_response_text = response_text96 else:97 pass98 async def make_action(self, action, action_value, element_handle, element_selector, page):99 if action == 'click':100 await element_handle.focus()101 await element_handle.click({'delay': random.randrange(200)})102 elif action == 'type':103 await element_handle.focus()104 await element_handle.type(action_value)105 elif action == 'select':106 await page.select(element_selector, action_value)107 else:108 raise CloseSpider('Unkown action')109 await asyncio.sleep(2)110 async def select_element_handle(self, element_selector, page):111 if '/' in element_selector:112 await page.waitForXPath(element_selector)113 element_handle = await page.xpath(element_selector)114 element_handle = element_handle[0]115 else:116 await page.waitForSelector(element_selector)117 element_handle = await page.querySelector(element_selector)118 return element_handle119 async def finish_puppeteer_scrape(self, page, request, response):120 pyp_cookies = await page.cookies()121 request.cookies = pyp_cookies122 if request.intercept_request:123 body = str.encode(self.intercept_response_text)124 else:...

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful