Best Python code snippet using playwright-python
test_frames.py
Source:test_frames.py
...47 error = e48 assert error.message == "Frame has been detached."49async def test_evaluate_throw_for_detached_frames(page, server, utils):50 frame1 = await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)51 await utils.detach_frame(page, "frame1")52 error = None53 try:54 await frame1.evaluate("7 * 8")55 except Error as e:56 error = e57 assert "Execution Context is not available in detached frame" in error.message58async def test_evaluate_isolated_between_frames(page, server, utils):59 await page.goto(server.EMPTY_PAGE)60 await utils.attach_frame(page, "frame1", server.EMPTY_PAGE)61 assert len(page.frames) == 262 [frame1, frame2] = page.frames63 assert frame1 != frame264 await asyncio.gather(65 frame1.evaluate("window.a = 1"), frame2.evaluate("window.a = 2")66 )67 [a1, a2] = await asyncio.gather(68 frame1.evaluate("window.a"), frame2.evaluate("window.a")69 )70 assert a1 == 171 assert a2 == 272async def test_should_handle_nested_frames(page, server, utils):73 await page.goto(server.PREFIX + "/frames/nested-frames.html")74 assert utils.dump_frames(page.main_frame) == [75 "http://localhost:<PORT>/frames/nested-frames.html",76 " http://localhost:<PORT>/frames/frame.html (aframe)",77 " http://localhost:<PORT>/frames/two-frames.html (2frames)",78 " http://localhost:<PORT>/frames/frame.html (dos)",79 " http://localhost:<PORT>/frames/frame.html (uno)",80 ]81async def test_should_send_events_when_frames_are_manipulated_dynamically(82 page, server, utils83):84 await page.goto(server.EMPTY_PAGE)85 # validate frameattached events86 attached_frames = []87 page.on("frameattached", lambda frame: attached_frames.append(frame))88 await utils.attach_frame(page, "frame1", "./assets/frame.html")89 assert len(attached_frames) == 190 assert "/assets/frame.html" in attached_frames[0].url91 # validate framenavigated events92 navigated_frames = []93 page.on("framenavigated", lambda frame: navigated_frames.append(frame))94 await page.evaluate(95 """() => {96 frame = document.getElementById('frame1')97 frame.src = './empty.html'98 return new Promise(x => frame.onload = x)99 }"""100 )101 assert len(navigated_frames) == 1102 assert navigated_frames[0].url == server.EMPTY_PAGE103 # validate framedetached events104 detached_frames = list()105 page.on("framedetached", lambda frame: detached_frames.append(frame))106 await utils.detach_frame(page, "frame1")107 assert len(detached_frames) == 1108 assert detached_frames[0].is_detached()109async def test_framenavigated_when_navigating_on_anchor_urls(page, server):110 await page.goto(server.EMPTY_PAGE)111 async with page.expect_event("framenavigated"):112 await page.goto(server.EMPTY_PAGE + "#foo")113 assert page.url == server.EMPTY_PAGE + "#foo"114async def test_persist_main_frame_on_cross_process_navigation(page, server):115 await page.goto(server.EMPTY_PAGE)116 main_frame = page.main_frame117 await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")118 assert page.main_frame == main_frame119async def test_should_not_send_attach_detach_events_for_main_frame(page, server):120 has_events = list()...
framing.py
Source:framing.py
...32 byte = self.fd.read() # Lendo 1 octeto da porta serial33 result = self.FSM(byte) # FSM retorna True para recepção bem sucedida34 if (result):35 frame_teste = Frame()36 frame_teste.detach_frame(bytes(self.buffer))37 self.upperLayer.receive(frame_teste)38 self.buffer.clear()39 def handle_timeout(self):40 '''Trata um timeout associado a este callback'''41 self.buffer.clear()42 self.current_state = IDLE43 self.disable_timeout()44 print('TIMEOUT!')45 def FSM(self, byte):46 switch = {47 IDLE: self.idle,48 INIT: self.init,49 READ: self.read,50 ESCAPE: self.escape...
visualization_predict.py
Source:visualization_predict.py
1import os2import glob3import numpy as np4import torch5import PIL.Image6from options import Options7from model import Model8import cv29import pickle as pkl10from torchvision.transforms import functional as F11Experiement_object_based_all_behaviors = {12 # 'baseline': '/home/golf/code/models/Experiement_object_based_all_behaviors/weight_baseline/net_epoch_29.pth',13 # 'weight_use_haptic': '/home/golf/code/models/Experiement_object_based_all_behaviors/weight_use_haptic/net_epoch_29.pth',14 # 'weight_use_haptic_audio': '/home/golf/code/models/Experiement_object_based_all_behaviors/weight_use_haptic_audio/net_epoch_29.pth',15 'weight_use_haptic_audio_vibro': '/cluster/tufts/sinapovlab/ncimin01/output_a100/net_epoch_29.pth',16}17filelist = [18 # {'vision': '/home/golf/code/data/CY101/vision_data_part1/basket_funnel/trial_1/exec_1/push',19 # 'others': '/home/golf/code/data/CY101/rc_data/basket_funnel/trial_1/exec_1/push'},20 {'vision': '/cluster/tufts/sinapovlab/zkrato01/raw_data/vision_data_part2/egg_rough_styrofoam/trial_1/exec_2/lift_slow',21 'others': '/cluster/tufts/sinapovlab/zkrato01/raw_data/rc_data/egg_rough_styrofoam/trial_1/exec_2/lift_slow'},22 # {'vision': '/home/golf/code/data/CY101/vision_data_part4/timber_square/trial_1/exec_3/shake',23 # 'others': '/home/golf/code/data/CY101/rc_data/timber_square/trial_1/exec_3/shake'},24]25def predict_baseline(weight, filelist):26 opt = Options().parse()27 opt.data_dir = '/cluster/tufts/sinapovlab/zkrato01/processed_data2'28 opt.out_dir = '/cluster/tufts/sinapovlab/ncimin01/output_a100'29 opt.pretrained_model = '/cluster/tufts/sinapovlab/ncimin01/output_a100/net_epoch_29.pth'30 #opt.baseline = True31 #opt.sequence_length = 2032 print("Model Config: ", opt)33 model = Model(opt)34 model.load_weight()35 resultlist, _ = model.predict(filelist)36 with open("test.npy","wb") as file:37 pkl.dump(resultlist,file)38 outputlist = []39 for result in resultlist: 40 for something in result:41 for frame in something:42 squeeze_frame = frame.squeeze()43 permute_frame = squeeze_frame.permute([1,2,0])44 cpu_frame = permute_frame.cpu()45 detach_frame = cpu_frame.detach()46 outputlist.append(np.asarray(detach_frame.numpy()*255,"uint8"))47 48 return outputlist49def predict_proposed(weight, use_haptic, use_audio, use_virbo, filelist):50 opt = Options().parse()51 opt.out_dir = '/cluster/tufts/sinapovlab/ncimin01/output_a100'52 opt.data_dir = '/cluster/tufts/sinapovlab/zkrato01/processed_data2'53 opt.pretrained_model = '/cluster/tufts/sinapovlab/ncimin01/output_a100/net_epoch_29.pth'54 opt.use_behavior = True55 opt.use_haptic = use_haptic56 opt.use_audio = use_audio57 opt.use_vibro = use_virbo58 opt.aux = True59 opt.sequence_length = 2060 print("Model Config: ", opt)61 model = Model(opt)62 model.load_weight()63 resultlist, gt = model.predict(filelist)64 gen_audios = [np.vstack([hp.cpu().numpy().squeeze()[-3:] for hp in haptic]) for _, haptic, _, _ in resultlist]65 gt_audios = [np.vstack([hp.cpu().numpy().squeeze()[:,-3:] for hp in haptic]) for _, haptic, _, _ in gt]66 pass67if __name__ == '__main__':68 resultlist = predict_baseline(None, filelist) #Experiement_object_based_all_behaviors['baseline'], filelist)69 for idx, result in enumerate(resultlist):70 os.mkdir("baseline_{}".format(idx))71 for id, frame in enumerate(result):72 cv2.imwrite("baseline_{}/{}.png".format(idx, id), cv2.cvtColor(cv2.resize(frame,(128,128)), cv2.COLOR_BGR2RGB))73 '''74 resultlist, gtlist = predict_proposed(Experiement_object_based_all_behaviors['weight_use_haptic_audio_vibro'], True, True, True, filelist)75 for idx, result in enumerate(resultlist):76 os.mkdir("haptic_{}".format(idx))77 for id, frame in enumerate(result):78 cv2.imwrite("haptic_{}/{}.png".format(idx, id), cv2.cvtColor(cv2.resize(frame,(128,128)), cv2.COLOR_BGR2RGB))79 '''80 # for idx, result in enumerate(gtlist):81 # os.mkdir("groundtruth_{}".format(idx))82 # for id, frame in enumerate(result):...
utils.py
Source:utils.py
...34 }""",35 {"frame_id": frame_id, "url": url},36 )37 return cast(ElementHandle, handle.as_element()).content_frame()38 def detach_frame(self, page: Page, frame_id: str):39 page.evaluate(40 "frame_id => document.getElementById(frame_id).remove()", frame_id41 )42 def dump_frames(self, frame: Frame, indentation: str = "") -> List[str]:43 indentation = indentation or ""44 description = re.sub(r":\d+/", ":<PORT>/", frame.url)45 if frame.name:46 description += " (" + frame.name + ")"47 result = [indentation + description]48 sorted_frames = sorted(49 frame.child_frames, key=lambda frame: frame.url + frame.name50 )51 for child in sorted_frames:52 result = result + utils.dump_frames(child, " " + indentation)...
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!!