How to use adb_device method in ATX

Best Python code snippet using ATX

adb.py

Source:adb.py Github

copy

Full Screen

1#!/usr/bin/env python2# ! -*- coding: utf-8 -*-3import subprocess4from aaf import utils5def checkAdb(path):6 kw = {"stdin": subprocess.PIPE, "stdout": subprocess.PIPE}7 kw = utils.processWindows(**kw)8 cmd = [path, "version"]9 try:10 p = subprocess.Popen(cmd, **kw)11 out = p.communicate()[0]12 if p.returncode != 0:13 return False14 return "version" in out15 except:16 return False17class Device(object):18 def __init__(self, serial, model):19 self.serial = serial20 self.model = model21 self.pkgs = None22 def __str__(self):23 return self.model24 def getApkPath(self, packageName):25 return self.pkgs[packageName]26 def getPackageNames(self):27 return self.pkgs.keys()28 def setPackages(self, pkgs):29 self.pkgs = pkgs30class AdbWrapper(object):31 def __init__(self, adb_path):32 self.adb_path = None33 self.adb_device = None34 if checkAdb("adb"):35 self.adb_path = "adb"36 return37 if adb_path and checkAdb(adb_path):38 self.adb_path = adb_path39 return40 try:41 import psutil42 for process in psutil.process_iter():43 try:44 cmdline = process.cmdline()45 if len(cmdline) > 0 and cmdline[0] == "adb" and "fork-server" in cmdline:46 adb_path = process.exe()47 if checkAdb(adb_path):48 self.adb_path = adb_path49 return50 except:51 pass52 except:53 pass54 raise StandardError("Can't execute adb: " + str(adb_path))55 def call(self, args, **kw):56 kw = utils.processWindows(**kw)57 cmd = [self.adb_path]58 device = self.adb_device59 if device:60 cmd.extend(["-s", device.serial])61 cmd.extend(args)62 async = False63 if 'async' in kw:64 async = kw['async']65 del kw['async']66 if 'stdin' not in kw:67 kw['stdin'] = subprocess.PIPE68 if 'stdout' not in kw:69 kw['stdout'] = subprocess.PIPE70 try:71 adb = subprocess.Popen(cmd, **kw)72 if async:73 return adb74 out = adb.communicate()[0]75 except:76 raise77 if adb.returncode != 0:78 raise StandardError('adb returned exit code ' + str(adb.returncode) + ' for arguments ' + str(args))79 return out80 def getDevices(self):81 devices = {}82 for line in self.call(['devices', '-l']).splitlines():83 try:84 import re85 pattern = re.compile(r"(\S+)\s+device.+model:(.+)\s+device")86 parts = pattern.findall(line)87 if len(parts) != 1:88 continue89 serial, model = parts[0]90 devices[serial] = serial + '[' + model + ']'91 except:92 pass93 return devices94 def chooseDevice(self, cache):95 # identify device96 devices = self.getDevices()97 if not devices:98 raise StandardError(' ADB: no device')99 if self.adb_device is not None and self.adb_device.serial not in devices:100 print 'Device (%s) is not connected' % self.adb_device101 serial = None102 # use only device103 if len(devices) == 1:104 serial = devices.keys()[0]105 # otherwise, let user decide106 while not serial in devices:107 serial, _ = utils.ChooserForm("Choose device", devices.values(), values=devices.keys()).choose()108 if cache is not None and serial == cache.serial:109 self.adb_device = cache110 else:111 self.adb_device = Device(serial, devices[serial])112 self.adb_device.setPackages(self._getPackageApk())113 return self.adb_device114 def _getPackageApk(self):115 ret = {}116 devicePackages = self.call(['shell', 'pm', 'list', 'packages', '-f', "-3"])117 if not devicePackages.strip():118 return ret119 for devicePackage in (l.strip() for l in devicePackages.splitlines()):120 if not devicePackage:121 continue122 # devicePackage has the format 'package:/data/app/pkg.apk=pkg'123 devicePackage = devicePackage.partition('=')124 ret[devicePackage[2]] = devicePackage[0].partition(':')[2]125 return ret126 def pull(self, src, dest):127 params = ['pull']128 if isinstance(src, list):129 params.extend(src)130 else:131 params.append(str(src))132 params.append(dest)133 self.call(params, stderr=subprocess.PIPE)134 def push(self, src, dest):135 params = ['push']136 if isinstance(src, list):137 params.extend(src)138 else:139 params.append(str(src))140 params.append(dest)141 self.call(params, stderr=subprocess.PIPE)142 def pathExists(self, path):143 # adb shell doesn't seem to return error codes144 out = self.call(['shell', 'ls "' + path + '" echo $?'], stderr=subprocess.PIPE)145 return int(out.splitlines()[-1]) == 0146 def forward(self, from_port, to_port):...

Full Screen

Full Screen

run_android_test.py

Source:run_android_test.py Github

copy

Full Screen

1# coding: utf82"""3RUN ANDROID TEST4"""5import os6from adb_prototype import simple_wait, get_adb_client, AdbDevice7from common.config_lib import prepare_directory, get_files_in_dir8from common.logger import log_new, logg9def adb_run_android_test(config, parameters):10 log_new('adb_run_android_test')11 [12 device_name,13 desktop_screens_dir,14 desktop_logs_dir,15 app_src,16 scenario_name,17 scenario_src,18 sh_script_src,19 device_config_src,20 device_config_name,21 log_name,22 dynamic_layout,23 ] = parameters24 logg('device_name', device_name)25 logg('desktop_screens_dir', desktop_screens_dir)26 logg('desktop_logs_dir', desktop_logs_dir)27 logg('app_src', app_src)28 logg('scenario_name', scenario_name)29 logg('scenario_src', scenario_src)30 logg('sh_script_src', sh_script_src)31 logg('device_config_src', device_config_src)32 logg('device_config_name', device_config_name)33 logg('log_name', log_name)34 logg('dynamic_layout', dynamic_layout)35 dynamic_layout_name = os.path.basename(dynamic_layout)36 prepare_directory(desktop_screens_dir)37 prepare_directory(desktop_logs_dir)38 adb_client = get_adb_client()39 adb_device = AdbDevice(device_name, config, adb_client)40 adb_device.echo('Running test on Android device: {}'.format(device_name))41 adb_device.set_awake()42 adb_device.echo('Rebooting device {}'.format(device_name))43 adb_device.reboot_device()44 simple_wait(config.WAIT_REBOOT_SEC)45 if adb_device.check_app_installed(config.APP_NAME_INSTALL):46 adb_device.echo('Uninstalling app {}'.format(config.APP_NAME_INSTALL))47 adb_device.uninstall_app(config.APP_NAME_INSTALL)48 simple_wait(config.WAIT_INSTALL_SEC)49 adb_device.echo('Installing apk {}'.format(app_src))50 adb_device.install_apk(app_src)51 simple_wait(config.WAIT_INSTALL_SEC)52 if not adb_device.check_app_installed(config.APP_NAME_INSTALL):53 adb_device.echo('Installing apk {} 2nd time'.format(app_src))54 adb_device.install_apk(app_src)55 simple_wait(config.WAIT_INSTALL_SEC)56 adb_device.echo('Creating work dir structure')57 adb_device.create_dir_on_android(config.ANDROID_TEMP_DIR)58 adb_device.create_dir_on_android(config.ANDROID_SCREENS_DIR)59 adb_device.create_dir_on_android(config.ANDROID_DYNAMIC_MODELS_DIR)60 adb_device.create_dir_on_android(config.ANDROID_MODELS_DIR)61 adb_device.echo('Loading test data')62 adb_device.copy_file_to_android(scenario_src, '{}/{}'.format(config.ANDROID_WORK_DIR, scenario_name))63 adb_device.copy_file_to_android(sh_script_src, '{}/{}'.format(64 config.ANDROID_WORK_DIR, config.ANDROID_SIDE_RUN_SCRIPT_NAME))65 adb_device.copy_file_to_android(device_config_src, '{}/{}'.format(config.ANDROID_WORK_DIR, device_config_name))66 adb_device.copy_file_to_android(dynamic_layout, '{}/{}'.format(config.ANDROID_WORK_DIR, dynamic_layout_name))67 dynamic_models = get_files_in_dir(config.DYNAMIC_MODELS)68 for dynamic_model in dynamic_models:69 adb_device.copy_file_to_android('{}/{}'.format(dynamic_models, dynamic_model),70 '{}/{}'.format(config.ANDROID_DYNAMIC_MODELS_DIR, dynamic_model))71 models = get_files_in_dir(config.MODELS)72 for model in models:73 adb_device.copy_file_to_android('{}/{}'.format(models, model),74 '{}/{}'.format(config.ANDROID_MODELS_DIR, model))75 adb_device.echo('ANDROID_WORK_DIR content before test:')76 adb_device.list_dir_content_on_android(config.ANDROID_WORK_DIR)77 adb_device.echo('Running app {}'.format(config.APP_NAME_INSTALL))78 sh_script_args = ' '.join((str(config.ANDROID_SIDE_PERIOD_SEC), str(config.ANDROID_SIDE_TIMEOUT_SEC),79 config.ANDROID_WORK_DIR, scenario_name, config.APP_NAME_RUN, device_config_name,80 scenario_name, log_name))81 logg('sh_script_args', sh_script_args)82 adb_device.run_sh_script('{}/{}'.format(83 config.ANDROID_WORK_DIR, config.ANDROID_SIDE_RUN_SCRIPT_NAME), sh_script_args)84 adb_device.echo('ANDROID_WORK_DIR content after test:')85 adb_device.list_dir_content_on_android(config.ANDROID_WORK_DIR)86 simple_wait(config.WAIT_SHORT_SEC)87 adb_device.echo('Saving results and logs')88 screens = adb_device.get_files_list_on_android(config.ANDROID_SCREENS_DIR, 'png')89 logg('screens', screens)90 for screen in screens:91 adb_device.copy_file_to_desktop('{}/{}'.format(config.ANDROID_SCREENS_DIR, screen),92 '{}/{}'.format(desktop_screens_dir, screen))93 adb_device.copy_file_to_desktop('{}/{}'.format(config.ANDROID_WORK_DIR, log_name),94 '{}/{}'.format(desktop_logs_dir, log_name))95 simple_wait(config.WAIT_SHORT_SEC)96 adb_device.echo('Test finished')...

Full Screen

Full Screen

adb_script_example.py

Source:adb_script_example.py Github

copy

Full Screen

1# coding: utf82"""3ADB PROTOTYPE SCRIPT EXAMPLE4"""5from adb_prototype import simple_wait, kill_adb, start_adb, reconnect_offline, get_adb_client, AdbDevice6from common.configurator import Config7from common.logger import log_new8class PrototypeConfig(Config):9 """10 Prototype test configuration11 """12 DATA_DIR = 'D:/Autotests/temp/proto_test_data'13 RESULT_DIR = 'D:/Autotests/temp/proto_test_data/result'14 APK_PATH = '{}/ZenithCartoScriptingTestApp-debug.apk'.format(DATA_DIR)15 SH_SCRIPT = 'run.sh'16 TEST_DATA = ['moscow_mobile.2gis',17 'OfflineDynamic.2gis',18 'regression.json',19 'Samsung_Galaxy_S4.config',20 'run.sh',21 'test.txt']22 ANDROID_WORK_DIR = '{}/{}'.format(Config.ANDROID_MAIN_DIR, 'proto')23 ANDROID_SCREENS_DIR = '{}/{}'.format(ANDROID_WORK_DIR, 'screens')24 ANDROID_TEMP_DIR = '{}/{}'.format(ANDROID_WORK_DIR, 'temp')25 WAIT_REBOOT_SEC = 12026 WAIT_INSTALL_SEC = 12027 WAIT_LOG = 3028 SH_ARGS = ['5',29 '600',30 ANDROID_WORK_DIR,31 'regression.json',32 Config.APP_NAME_RUN,33 'Samsung_Galaxy_S4.config',34 'regression.json',35 'ZenithNewTestApp.log']36def get_input_parameters():37 """38 Prototype test parameters39 """40 parameters = {41 'device_name': 'Samsung_Galaxy_S4'42 }43 return parameters44def adb_script(device_name, parameters, config):45 """46 Python adb script example47 """48 log_new('adb_script')49 restart_key = False50 # use only at global start51 if restart_key:52 kill_adb(config)53 start_adb(config)54 reconnect_offline(config)55 adb_client = get_adb_client()56 adb_device = AdbDevice(device_name, config, adb_client)57 adb_device.echo('Running test on Android device: {}'.format(parameters['device_name']))58 adb_device.clear_logcat()59 adb_device.reboot_device()60 simple_wait(config.WAIT_REBOOT_SEC)61 reconnect_offline(config)62 adb_device.delete_path_on_android(config.ANDROID_WORK_DIR)63 adb_device.create_dir_on_android(config.ANDROID_WORK_DIR)64 adb_device.create_dir_on_android(config.ANDROID_SCREENS_DIR)65 adb_device.create_dir_on_android(config.ANDROID_TEMP_DIR)66 for data_file in config.TEST_DATA:67 adb_device.copy_file_to_android('{}/{}'.format(config.DATA_DIR, data_file),68 '{}/{}'.format(config.ANDROID_WORK_DIR, data_file))69 adb_device.list_dir_content_on_android(config.ANDROID_WORK_DIR)70 if adb_device.check_app_installed(config.APP_NAME_INSTALL):71 adb_device.uninstall_app(config.APP_NAME_INSTALL)72 adb_device.install_apk(config.APK_PATH)73 simple_wait(config.WAIT_INSTALL_SEC)74 adb_device.run_sh_script('{}/{}'.format(config.ANDROID_WORK_DIR, config.SH_SCRIPT), ' '.join(config.SH_ARGS))75 for data_file in config.TEST_DATA:76 adb_device.copy_file_to_desktop('{}/{}'.format(config.ANDROID_WORK_DIR, data_file),77 '{}/{}'.format('{}_{}'.format(config.RESULT_DIR, parameters['device_name']),78 data_file))79 for data_file in config.TEST_DATA:80 adb_device.delete_path_on_android('{}/{}'.format(config.ANDROID_WORK_DIR, data_file))81 adb_device.list_dir_content_on_android(config.ANDROID_WORK_DIR)82 adb_device.get_logcat()83 adb_device.get_logcat()84 simple_wait(config.WAIT_LOG)85 adb_device.echo('Test finished')86def main():87 log_new('main')88 config = PrototypeConfig()89 parameters = get_input_parameters()90 adb_script(parameters['device_name'], parameters, config)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ATX 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