Best Python code snippet using Airtest
component.py
Source:component.py
1"""View for single component."""2import componentstore.resources.html as load3from componentstore.functions.data import get_data, migration_needed4from componentstore.const import EXAMPLE, DEMO5async def view(component):6 """View for single component."""7 content = load.RELOADICON.format('/reloadinstalled')8 data = await component_data(component)9 meta = {}10 meta['attention'] = data.get('attention')11 meta['author'] = ''12 meta['cardbuttons'] = ''13 meta['cardcontent'] = ''14 meta['cardtitle'] = ''15 meta['name'] = component16 meta['description'] = data.get('description')17 meta['long_description'] = data.get('long_description')18 meta['image'] = ''19 meta['install_or_upgrade'] = 'install'20 meta['update'] = ''21 meta['warning'] = ''22 if data:23 buttons = {}24 buttons['1'] = ''25 buttons['2'] = ''26 buttons['3'] = ''27 buttons['4'] = ''28 buttons['5'] = ''29 buttons['6'] = ''30 if data['installed']:31 buttons['1'] = load.LINK.format(32 url='/component/'+meta['name'], target='_self',33 style='', id='1', htmlclass='', extra='',34 text='CHECK FOR UPDATE')35 buttons['6'] = load.LINK.format(36 url='/component/'+meta['name']+'/uninstall', target='_self',37 style='', id='4', htmlclass='uninstall', extra='',38 text='UNINSTALL')39 else:40 buttons['1'] = load.LINK.format(41 url='#', target='_self',42 style='', id='installbtn', htmlclass='', extra='',43 text=meta['install_or_upgrade'])44 if data['has_update']:45 meta['cardtitle'] += load.UPDATEICON46 meta['install_or_upgrade'] = 'upgrade'47 buttons['1'] = load.LINK.format(48 url='#', target='_self',49 style='', id='installbtn', htmlclass='', extra='',50 text=meta['install_or_upgrade'])51 buttons['4'] = load.LINK.format(52 url=data['changelog'], target='_blank',53 style='', id='3', htmlclass='', extra='', text='CHANGELOG')54 if data.get('author'):55 link = load.LINK.format(56 url=data['author'].get('html_url'), target='_blank',57 style='', id='3', htmlclass='', extra='',58 text='@'+data['author'].get('login'))59 meta['author'] = load.TEXT.format('Author: '+link)60 buttons['3'] = load.LINK.format(61 url=data['visit_repo'], target='_blank',62 style='', id='2', htmlclass='', extra='', text='REPOSITORY')63 meta['cardtitle'] += meta['name']64 meta['cardtitle'] += load.CARD_MENU.format(65 repo=data['visit_repo'], component=meta['name'])66 needs_migration = await migration_needed(component)67 if needs_migration:68 meta['warning'] = load.TOOLTIP.format('Migration needed')69 domain = component.split('.')[0]70 platform = component.split('.')[1]71 meta['attention'] = "You have this installed with the old format."72 meta['attention'] += load.BREAK73 meta['attention'] += "You need to move (migrate) it to an embedded platform."74 meta['attention'] += load.BREAK75 meta['attention'] += load.BREAK76 option1 = "Option 1: Change the location of the platform"77 option1 += load.BREAK78 option1 += "from: custom_components/{domain}/{platform}.py".format(79 domain=domain, platform=platform)80 option1 += load.BREAK81 option1 += "to: 'custom_components/{platform}/{domain}.py'".format(82 domain=domain, platform=platform)83 option1 += load.BREAK84 meta['attention'] += load.TEXT.format(option1)85 if data['embedded']:86 meta['attention'] += load.TEXT.format(87 "Option 2: Delete the file and reinstall with this site.")88 meta['attention'] += load.BREAK89 meta['attention'] += load.TEXT.format(90 "Option 3: Click the 'MIGRATE' button.")91 if DEMO:92 buttons['2'] = load.LINK.format(93 url='#', target='_self', style='', id='installbtn',94 htmlclass='', extra='', text='MIGRATE')95 else:96 buttons['2'] = load.LINK.format(97 url='/component/'+component+'/migrate', target='_self',98 style='', id='2', htmlclass='', extra='',99 text='MIGRATE')100 if not data['embedded']:101 meta['attention'] = "This can not be installed/used with this site yet."102 meta['attention'] += load.BREAK103 meta['attention'] += "The developer of this must first migrate "104 meta['attention'] += "it to an embedded platform."105 if meta['attention']:106 buttons['1'] = ''107 buttons['4'] = ''108 meta['attention'] = load.ATTENTION.format(meta['attention'])109 else:110 meta['attention'] = ''111 if meta['description']:112 meta['cardcontent'] += load.TEXT.format(meta['description'])113 meta['cardcontent'] += load.BREAK114 if meta['attention']:115 meta['cardcontent'] += meta['attention']116 meta['cardcontent'] += load.BREAK117 if data['image_link']:118 meta['image'] = load.IMAGE.format(data['image_link'])119 meta['cardcontent'] += meta['image']120 meta['cardcontent'] += load.BREAK121 meta['cardcontent'] += load.BREAK122 if meta['long_description']:123 meta['cardcontent'] += load.TEXT.format(meta['long_description'])124 meta['cardcontent'] += load.BREAK125 if meta['author']:126 meta['cardcontent'] += load.TEXT.format(meta['author'])127 if data['local_version']:128 text = "Installed version: {}".format(data['local_version'])129 meta['cardcontent'] += load.TEXT.format(text)130 if data['version']:131 text = "Published version: {}".format(data['version'])132 meta['cardcontent'] += load.TEXT.format(text)133 if component == 'sensor.example':134 buttons['1'] = ''135 if DEMO and data['installed']:136 buttons['6'] = load.LINK.format(137 url='#', target='_self',138 style='', id='uninstallbtn', htmlclass='uninstall', extra='',139 text='uninstall')140 meta['cardbuttons'] += buttons['1']141 meta['cardbuttons'] += buttons['2']142 meta['cardbuttons'] += buttons['3']143 meta['cardbuttons'] += buttons['4']144 meta['cardbuttons'] += buttons['5']145 meta['cardbuttons'] += buttons['6']146 content += load.BUTTON_CARD.format(147 title=meta['cardtitle'],148 content=meta['cardcontent'],149 buttons=meta['cardbuttons'])150 if DEMO:151 content += load.DEMO_MODAL152 else:153 content += load.MODAL.format(154 component=meta['name'], type=meta['install_or_upgrade'],155 text=meta['install_or_upgrade'].upper())156 content += load.MODAL_SCRIPT157 else:158 content = load.NO_TITLE_CARD.format(159 'Component '+meta['name']+' not found')160 html = load.TOP161 html += load.BASE.format(content)162 html += load.END163 return html164async def component_data(component):165 """Return component data."""166 data = {}167 if component == 'sensor.example':168 component = EXAMPLE['sensor.example']169 else:170 component = await get_data(component=component)171 try:172 data['author'] = component.get('author')173 data['attention'] = component.get('attention')174 data['embedded'] = component.get('embedded')175 data['changelog'] = component.get('changelog')176 data['description'] = component.get('description')177 data['long_description'] = component.get('long_description')178 data['has_update'] = component.get('has_update')179 data['image_link'] = component.get('image_link')180 data['installed'] = component.get('installed')181 data['local_version'] = component.get('local_version')182 data['version'] = component.get('version')183 data['visit_repo'] = component.get('visit_repo')184 except Exception: # pylint: disable=W0703185 pass...
recorder.py
Source:recorder.py
1# -*- coding: utf-8 -*-2import re3import six4from airtest.core.android.yosemite import Yosemite5from airtest.core.android.constant import YOSEMITE_PACKAGE6from airtest.core.error import AirtestError7from airtest.utils.logger import get_logger8from airtest.utils.nbsp import NonBlockingStreamReader9from airtest.utils.snippet import on_method_ready10LOGGING = get_logger(__name__)11class Recorder(Yosemite):12 """Screen recorder"""13 def __init__(self, adb):14 super(Recorder, self).__init__(adb)15 self.recording_proc = None16 self.recording_file = None17 @on_method_ready('install_or_upgrade')18 def start_recording(self, max_time=1800, bit_rate=None, vertical=None):19 """20 Start screen recording21 Args:22 max_time: maximum rate value, default is 180023 bit_rate: bit rate value, default is None24 vertical: vertical parameters, default is None25 Raises:26 RuntimeError: if any error occurs while setup the recording27 Returns:28 None if recording did not start, otherwise True29 """30 if getattr(self, "recording_proc", None):31 raise AirtestError("recording_proc has already started")32 pkg_path = self.adb.path_app(YOSEMITE_PACKAGE)33 max_time_param = "-Dduration=%d" % max_time if max_time else ""34 bit_rate_param = "-Dbitrate=%d" % bit_rate if bit_rate else ""35 if vertical is None:36 vertical_param = ""37 else:38 vertical_param = "-Dvertical=true" if vertical else "-Dvertical=false"39 p = self.adb.start_shell('CLASSPATH=%s exec app_process %s %s %s /system/bin %s.Recorder --start-record' %40 (pkg_path, max_time_param, bit_rate_param, vertical_param, YOSEMITE_PACKAGE))41 nbsp = NonBlockingStreamReader(p.stdout)42 while True:43 line = nbsp.readline(timeout=5)44 if line is None:45 raise RuntimeError("start recording error")46 if six.PY3:47 line = line.decode("utf-8")48 m = re.match("start result: Record start success! File path:(.*\.mp4)", line.strip())49 if m:50 output = m.group(1)51 self.recording_proc = p52 self.recording_file = output53 return True54 @on_method_ready('install_or_upgrade')55 def stop_recording(self, output="screen.mp4", is_interrupted=False):56 """57 Stop screen recording58 Args:59 output: default file is `screen.mp4`60 is_interrupted: True or False. Stop only, no pulling recorded file from device.61 Raises:62 AirtestError: if recording was not started before63 Returns:64 None65 """66 pkg_path = self.adb.path_app(YOSEMITE_PACKAGE)67 p = self.adb.start_shell('CLASSPATH=%s exec app_process /system/bin %s.Recorder --stop-record' % (pkg_path, YOSEMITE_PACKAGE))68 p.wait()69 self.recording_proc = None70 if is_interrupted:71 return72 for line in p.stdout.readlines():73 if line is None:74 break75 if six.PY3:76 line = line.decode("utf-8")77 m = re.match("stop result: Stop ok! File path:(.*\.mp4)", line.strip())78 if m:79 self.recording_file = m.group(1)80 self.adb.pull(self.recording_file, output)81 return True82 raise AirtestError("start_recording first")83 @on_method_ready('install_or_upgrade')84 def pull_last_recording_file(self, output='screen.mp4'):85 """86 Pull the latest recording file from device. Error raises if no recording files on device.87 Args:88 output: default file is `screen.mp4`89 """90 recording_file = 'mnt/sdcard/test.mp4'...
packagemanager.py
Source:packagemanager.py
2import logging3import json4import os5log = logging.getLogger('dlmclient')6def install_or_upgrade(package=''):7 """install the given package."""8 cmd = 'opkg install %s' %(package)9 try:10 ret = subprocess.check_call(cmd, shell=True)11 except subprocess.CalledProcessError as err:12 log.error('error installing package: "%s":%s' %(package, err))13 ret = 114 return ret15def update():16 """install the given package."""17 cmd = 'opkg update'18 try:19 ret = subprocess.check_call(cmd, shell=True)20 except subprocess.CalledProcessError as err:21 log.error('error updating package list: :%s' %(err))22 ret = 123 return ret24def run_maintenance(upgrade_packages):25 """Do package maintenance by """26 # update package list27 update()28 # install / upgrade packages from the file29 for pkg in upgrade_packages:30 install_or_upgrade(pkg)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!