How to use print_events method in Playwright Python

Best Python code snippet using playwright-python

selectbinder.py

Source:selectbinder.py Github

copy

Full Screen

1from functools import reduce2from select import select3from threading import Thread4import approxeng.input.sys as sys5from approxeng.input.controllers import *6EV_KEY = 17EV_REL = 28EV_ABS = 39class ControllerResource:10 """11 General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.12 """13 def __init__(self, *requirements, print_events=False, **kwargs):14 """15 Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this16 will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided17 as a list of ControllerRequirement18 :param ControllerRequirement requirements:19 ControllerRequirement instances used, in order, to find and bind controllers. If empty this will20 be equivalent to supplying a single unfiltered requirement and will match the first specified controller.21 :param bool print_events:22 Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use23 this when you're trying to figure out what events correspond to what axes and buttons!24 :param kwargs:25 Any addition keyword arguments are passed to the constructors for the controller classes. This is useful26 particularly to specify e.g. dead and hot zone ranges on discovery.27 :raises ControllerNotFoundError:28 If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.29 """30 self.discoveries = find_matching_controllers(*requirements, **kwargs)31 self.unbind = None32 self.print_events = print_events33 def __enter__(self):34 """35 Called on entering the resource block, returns the controller passed into the constructor.36 """37 self.unbind = bind_controllers(*self.discoveries, print_events=self.print_events)38 if len(self.discoveries) == 1:39 return self.discoveries[0].controller40 else:41 return tuple(discovery.controller for discovery in self.discoveries)42 def __exit__(self, exc_type, exc_value, traceback):43 """44 Called on resource exit, unbinds the controller, removing the listening thread.45 """46 self.unbind()47def bind_controllers(*discoveries, print_events=False):48 """49 Bind a controller or controllers to a set of evdev InputDevice instances, starting a thread to keep those50 controllers in sync with the state of the hardware.51 52 :param ControllerDiscovery discoveries:53 ControllerDiscovery instances specifying the controllers and their associated input devices54 :param bool print_events:55 Defaults to False, if set to True then all events picked up by this binder will be printed to stdout56 :return: 57 A function which can be used to stop the event reading thread and unbind from the device58 """59 discoveries = list(discoveries)60 class SelectThread(Thread):61 def __init__(self):62 Thread.__init__(self, name='evdev select thread')63 self.daemon = True64 self.running = True65 self.device_to_controller_discovery = {}66 for discovery in discoveries:67 for d in discovery.devices:68 self.device_to_controller_discovery[d.fn] = discovery69 self.all_devices = reduce(lambda x, y: x + y, [discovery.devices for discovery in discoveries])70 def run(self):71 for discovery in discoveries:72 discovery.controller.device_unique_name = discovery.name73 while self.running:74 try:75 r, w, x = select(self.all_devices, [], [], 0.5)76 for fd in r:77 active_device = fd78 controller_discovery = self.device_to_controller_discovery[active_device.fn]79 controller = controller_discovery.controller80 controller_devices = controller_discovery.devices81 prefix = None82 if controller.node_mappings is not None and len(controller_devices) > 1:83 try:84 prefix = controller.node_mappings[active_device.name]85 except KeyError:86 pass87 for event in active_device.read():88 if print_events:89 print(event)90 if event.type == EV_ABS or event.type == EV_REL:91 controller.axes.axis_updated(event, prefix=prefix)92 elif event.type == EV_KEY:93 # Button event94 if event.value == 1:95 # Button down96 controller.buttons.button_pressed(event.code, prefix=prefix)97 elif event.value == 0:98 # Button up99 controller.buttons.button_released(event.code, prefix=prefix)100 except Exception as e:101 self.stop(e)102 def stop(self, exception=None):103 for discovery in discoveries:104 discovery.controller.device_unique_name = None105 discovery.controller.exception = exception106 self.running = False107 polling_thread = SelectThread()108 # Force an update of the LED and battery system cache109 sys.scan_cache(force_update=True)110 for device in polling_thread.all_devices:111 device.grab()112 def unbind():113 polling_thread.stop()114 for dev in polling_thread.all_devices:115 try:116 dev.ungrab()117 except IOError:118 pass119 polling_thread.start()...

Full Screen

Full Screen

sysviewtrace_proc.py

Source:sysviewtrace_proc.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright 2019 Espressif Systems (Shanghai) PTE LTD4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17# This is python script to process various types trace data streams in SystemView format.18# Trace data can be provided in multiple trace files (one per CPU). After processing phase19# script prints report for every type of trace data stream which was found.20#21import argparse22import sys23import os.path24import signal25import traceback26import espytrace.apptrace as apptrace27import espytrace.sysview as sysview28def main():29 parser = argparse.ArgumentParser(description='ESP32 SEGGER SystemView Trace Parsing Tool')30 parser.add_argument('trace_sources', help='Trace data sources. Format: [file://]/path/to/file.', nargs='+', type=str)31 parser.add_argument('elf_file', help='Path to program ELF file.', type=str)32 parser.add_argument('--tmo', '-w', help='Data wait timeout in sec. -1: infinite, 0: no wait', type=int, default=0)33 parser.add_argument('--dump-events', '-d', help='Dump all events.', action='store_true')34 parser.add_argument('--print-events', '-p', help='Print events of selected types. By default only reports are printed', action='store_true')35 parser.add_argument('--include-events', '-i', help='Events types to be included into report.', type=str, choices=['heap', 'log', 'all'], default='all')36 parser.add_argument('--toolchain', '-t', help='Toolchain prefix.', type=str, default='xtensa-esp32-elf-')37 parser.add_argument('--events-map', '-e', help='Events map file.', type=str, default=os.path.join(os.path.dirname(__file__), 'SYSVIEW_FreeRTOS.txt'))38 args = parser.parse_args()39 def sig_int_handler(signum, frame):40 reader.cleanup()41 signal.signal(signal.SIGINT, sig_int_handler)42 include_events = {'heap': False, 'log': False}43 if args.include_events == 'all':44 for k in include_events:45 include_events[k] = True46 elif args.include_events == 'heap':47 include_events['heap'] = True48 elif args.include_events == 'log':49 include_events['log'] = True50 # parse trace files51 parsers = []52 for i, trace_source in enumerate(args.trace_sources):53 try:54 parser = sysview.SysViewMultiTraceDataParser(print_events=False, core_id=i)55 if include_events['heap']:56 parser.add_stream_parser(sysview.SysViewTraceDataParser.STREAMID_HEAP,57 sysview.SysViewHeapTraceDataParser(print_events=False, core_id=i))58 if include_events['log']:59 parser.add_stream_parser(sysview.SysViewTraceDataParser.STREAMID_LOG,60 sysview.SysViewLogTraceDataParser(print_events=False, core_id=i))61 parsers.append(parser)62 except Exception as e:63 print("Failed to create data parser ({})!".format(e))64 traceback.print_exc()65 sys.exit(2)66 reader = apptrace.reader_create(trace_source, args.tmo)67 if not reader:68 print("Failed to create trace reader!")69 sys.exit(2)70 try:71 print("Parse trace from '{}'...".format(trace_source))72 sysview.parse_trace(reader, parser, args.events_map)73 print("Parsing completed.")74 except (apptrace.ReaderTimeoutError, apptrace.ReaderShutdownRequest) as e:75 print("Stop parsing trace. ({})".format(e))76 except Exception as e:77 print("Failed to parse trace ({})!".format(e))78 parser.cleanup()79 traceback.print_exc()80 sys.exit(2)81 finally:82 reader.cleanup()83 # merge and process traces84 try:85 proc = sysview.SysViewMultiTraceDataProcessor(traces=parsers, print_events=args.dump_events)86 if include_events['heap']:87 proc.add_stream_processor(sysview.SysViewTraceDataParser.STREAMID_HEAP,88 sysview.SysViewHeapTraceDataProcessor(args.toolchain, args.elf_file, print_heap_events=args.print_events))89 if include_events['log']:90 proc.add_stream_processor(sysview.SysViewTraceDataParser.STREAMID_LOG,91 sysview.SysViewLogTraceDataProcessor(print_log_events=args.print_events))92 except Exception as e:93 print("Failed to create data processor ({})!".format(e))94 traceback.print_exc()95 sys.exit(2)96 try:97 print("Process events from '{}'...".format(args.trace_sources))98 proc.merge_and_process()99 print("Processing completed.")100 except Exception as e:101 print("Failed to process trace ({})!".format(e))102 traceback.print_exc()103 sys.exit(2)104 finally:105 proc.print_report()106if __name__ == '__main__':...

Full Screen

Full Screen

analyzer.py

Source:analyzer.py Github

copy

Full Screen

1#!/usr/bin/env python2import sys3import json4import requests5import argparse6import config7from waf import Waf8def getParser():9 parser = argparse.ArgumentParser(description = 'Process WAF events.')10 parser.add_argument('-u', '--user', metavar = 'user', dest = 'user',11 type = str, help = 'The user account')12 parser.add_argument('-k', '--key', metavar = 'key', dest = 'key',13 type = str, help = 'The API key')14 parser.add_argument('-z', '--zone', metavar = 'zone', dest = 'zone',15 type = str, help = 'The zone ID')16 parser.add_argument('-o', '--org', metavar = 'org', dest = 'org',17 type = str, help = 'The organization ID')18 parser.add_argument('-t', '--host', metavar = 'host', dest = 'host',19 type = str, help = 'The hostname')20 parser.add_argument('-p', '--print_events', metavar = 'print_events', dest = 'print_events',21 type = str, help = 'Print events')22 parser.add_argument('-a', '--all', action = 'store_true', dest = 'all', 23 help = 'All zones (overwrites zone ID)', default = False)24 parser.add_argument('-s', '--separate', action = 'store_true',25 dest = 'separate', help = 'Separate reports', default = False),26 parser.add_argument('-r', '--ray', metavar = 'ray', dest = 'ray',27 type = str, help = 'The ray ID')28 return parser29def getZoneInteractive(waf):30 print "\nThe following zones are available:\n"31 for i, zone in enumerate(waf.zones):32 print "%s. ID: %s - %s" % (i + 1, zone[0], zone[1])33 while True:34 try:35 s = int(raw_input("\nPlease enter the list number:")) - 136 zone = waf.zones[s][0]37 break38 except (ValueError, IndexError):39 print "Error: Invalid input. Try again."40 return zone41def printEvents(waf):42 waf.printEvents()43def printTopEvents(waf):44 print "Total events checked: " + str(len(waf.events)) + "\n"45 waf.printTopEvents("Top Country Threats:", 'country')46 waf.printTopEvents("Top IP Threats:", 'ip')47 waf.printTopEvents("Top URL Threats:", ('host', 'uri'))48 waf.printTopEvents("Top User Agent Threats:", 'user_agent')49 waf.printTopRules("Top Rule Hits:")50def printRayEvent(waf, ray):51 waf.printRay(ray)52def commandLineRunner():53 parser = getParser()54 args = parser.parse_args()55 # Favor command line over config56 USER = args.user if args.user is not None else config.USER57 KEY = args.key if args.key is not None else config.KEY58 ZONE = args.zone if args.zone is not None else config.ZONE59 ORG = args.org if args.org is not None else config.ORG60 HOST = args.host if args.host is not None else config.HOST61 PRINT_EVENTS = args.print_events if args.print_events is not None else config.PRINT_EVENTS62 PAGES = config.MAXP if config.MAXP is not None else 1063 ALL = args.all64 SEP = args.separate65 # If nothing specified default to interactive66 USER = USER if USER else raw_input("Enter your username:")67 KEY = KEY if KEY else raw_input("Enter your API key:")68 # Create WAF object69 waf = Waf(USER, KEY, PAGES, HOST)70 if not ZONE and not ORG and not ALL:71 ZONE = [getZoneInteractive(waf)]72 elif ORG and not ALL:73 ZONE = [zone[0] for zone in waf.zones if zone[2] == ORG]74 elif ZONE:75 ZONE = [ZONE]76 else: 77 ZONE = [zone[0] for zone in waf.zones]78 # Perform relevant action and fetch data79 waf.zone = ZONE80 # Looking for specific ray81 if args.ray:82 printRayEvent(waf, args.ray)83 # We want individual reports per zone84 elif SEP and len(ZONE) > 1:85 for id in ZONE:86 for zone in waf.zones:87 if zone[0] == id:88 print "\nStarted grabbing WAF data for " + \89 zone[1] + " - ZoneID: " + id90 waf2 = Waf(USER, KEY, PAGES, HOST)91 waf2.zone = [id]92 if len(waf2.events) == 0: 93 print "No data for this zone.\n"94 if PRINT_EVENTS:95 printEvents(waf2)96 printTopEvents(waf2)97 # Aggregate reports98 else:99 if len(waf.events) == 0: 100 print "No data for this zone.\n"101 if PRINT_EVENTS:102 printEvents(waf)103 printTopEvents(waf)104if __name__ == '__main__':...

Full Screen

Full Screen

filter.py

Source:filter.py Github

copy

Full Screen

...14 if activeID == id:15 print(id," : ",s, "diff: ", b)16 lastN = n17@asyncio.coroutine18def print_events(device,path):19 while True:20 try:21 events = yield from device.async_read()22 for event in events:23 #print(device.path, evdev.categorize(event), sep=': ')24 scanFilter(device.path,evdev.categorize(event))25 except OSError:26 global listDevices27 listDevices.remove(path)28 break29listDevices = []30async def CheckDevices(interval):31 global listDevices32 while True:33 print("CheckDevice",listDevices)34 for dev in evdev.list_devices():35 if not (dev in listDevices):36 listDevices.append(dev)37 devices = evdev.InputDevice(dev)38 asyncio.ensure_future(print_events(devices,dev))39 await asyncio.sleep(interval)40loop = asyncio.get_event_loop()41try:42 asyncio.ensure_future(CheckDevices(2))43# devices = [evdev.InputDevice(path) for path in evdev.list_devices()]44# for device in devices:45# asyncio.async(print_events(device))46 loop = asyncio.get_event_loop()47 loop.run_forever()48except KeyboardInterrupt:49 pass50finally:51 print("Closing Loop")52 loop.close()53print("END Script")54import asyncio, evdev55import asyncio56import time57lastN = 058activeID = ""59def scanFilter(id,s):60 n = time.time()61 global lastN62 global activeID63 d = n - lastN64 b = d > 0.265 if b:66 activeID = id67 if activeID == id:68 print(id," : ",s, "diff: ", b)69 lastN = n70@asyncio.coroutine71def print_events(device,path):72 while True:73 try:74 events = yield from device.async_read()75 for event in events:76 #print(device.path, evdev.categorize(event), sep=': ')77 scanFilter(device.path,evdev.categorize(event))78 except OSError:79 global listDevices80 listDevices.remove(path)81 break82listDevices = []83async def CheckDevices(interval):84 global listDevices85 while True:86 print("CheckDevice",listDevices)87 for dev in evdev.list_devices():88 if not (dev in listDevices):89 listDevices.append(dev)90 devices = evdev.InputDevice(dev)91 asyncio.ensure_future(print_events(devices,dev))92 await asyncio.sleep(interval)93loop = asyncio.get_event_loop()94try:95 asyncio.ensure_future(CheckDevices(2))96# devices = [evdev.InputDevice(path) for path in evdev.list_devices()]97# for device in devices:98# asyncio.async(print_events(device))99 loop = asyncio.get_event_loop()100 loop.run_forever()101except KeyboardInterrupt:102 pass103finally:104 print("Closing Loop")105 loop.close()...

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