Best Python code snippet using robotframework-androidlibrary_python
generate.py
Source:generate.py
1'''2 ----------------------------------------------------------------------------------------3 "Copyright 2014-2015 Intel Corporation.4 The source code, information and material ("Material") contained herein is owned by Intel Corporation5 or its suppliers or licensors, and title to such Material remains with Intel Corporation or its suppliers6 or licensors. The Material contains proprietary information of Intel or its suppliers and licensors. 7 The Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may 8 be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed or disclosed9 in any way without Intel's prior express written permission. No license under any patent, copyright or 10 other intellectual property rights in the Material is granted to or conferred upon you, either expressly, 11 by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights 12 must be express and approved by Intel in writing.13 Unless otherwise agreed by Intel in writing, you may not remove or alter this notice or any other notice 14 embedded in Materials by Intel or Intel's suppliers or licensors in any way."15 -----------------------------------------------------------------------------------------16'''17from __future__ import division18import sys19import os20import re21from common import *22import shutil23import stat24from xml.etree import ElementTree25from dvcutility import Enviroment26reload(sys)27sys.setdefaultencoding('utf-8')28def generateOneQS(relaunch_number, apkName, packageName, actionNum, waitTime, videoRecording, apkFolder, workFolder,29 install_application, uninstall_application, back_action, data_info, record_video_failed_app,30 each_seed_value, each_abi):31 apkPath = ""32 if apkFolder <> "":33 apkPath = apkName34 #If apk path is for a APK name list (not path). path. APK folder shall be combined into the whole apk path.35 if apkPath.find("\\") < 0:36 apkPath = apkFolder + "\\" + apkName37 data_source = ""38 data_dest = ""39 for dinfo in data_info:40 data_paths = dinfo.split(',')41 if (len(data_paths) < 3):42 continue43 if (data_paths[0] == packageName):44 data_source = data_paths[1].strip()45 data_dest = data_paths[2].strip()46 qsLines = ""47 qsLines += "[Configuration]\n"48 qsLines += "CapturedImageHeight=787\n"49 qsLines += "CapturedImageWidth=447\n"50 qsLines += "CameraPresetting=HIGH_RES\n"51 qsLines += "PackageName=" + packageName + "\n"52 qsLines += "ActivityName=\n"53 # qsLines += "APKName=" + apkName.encode("utf-8") +"\n"54 qsLines += "APKName=" + apkPath +"\n"55 if (data_source <> "" and data_dest <> ""):56 qsLines += "PushData=" + data_source + " " + data_dest + "\n"57 else:58 qsLines += "PushData=\n"59 if (videoRecording.lower().strip() == "yes" or record_video_failed_app.lower().strip() == "yes"):60 qsLines += "VideoRecording=true\n"61 else:62 qsLines += "VideoRecording=false\n"63 lineNum = 164 qsLines += "[Events and Actions]\n"65 qsLines += str(lineNum) + " 0: OPCODE_CRASH_OFF\n"66 lineNum = lineNum + 167 qsLines += str(lineNum) + " 0: OPCODE_HOME\n"68 lineNum = lineNum + 169 if install_application.lower().strip() == "yes":70 if each_abi == 'java':71 qsLines += str(lineNum) + " 0: OPCODE_INSTALL_APP\n"72 else:73 qsLines += str(lineNum) + ' 0: OPCODE_INSTALL_APP 0 options="--abi {}"\n'.format(each_abi)74 lineNum = lineNum + 175 if (data_source <> "" and data_dest <> ""):76 qsLines += str(lineNum) + " 0: OPCODE_PUSH_DATA\n"77 lineNum = lineNum + 178 qsLines += str(lineNum) + " 0: OPCODE_START_APP\n"79 lineNum = lineNum + 180 i = 081 timeStamp = 082 while (i < relaunch_number):83 timeStamp = timeStamp + waitTime84 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_STOP_APP\n"85 lineNum = lineNum + 186 timeStamp = timeStamp+300087 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_START_APP\n"88 lineNum = lineNum + 189 i = i + 190 timeStamp = timeStamp + waitTime91 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_SET_VARIABLE n " + str(actionNum) + "\n"92 lineNum = lineNum + 193 loopNum = lineNum94 timeStamp = timeStamp + 100095 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_EXPLORATORY_TEST " + "bias_{}.xml\n".format(each_seed_value)96 lineNum = lineNum + 197 timeStamp = timeStamp + 100098 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_LOOP n " + str(loopNum) + "\n"99 lineNum = lineNum + 1100 if back_action.lower().strip() == "yes":101 timeStamp = timeStamp + 3000102 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_BACK\n"103 lineNum = lineNum + 1104 if uninstall_application.lower().strip() == "yes":105 timeStamp = timeStamp+3000106 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_STOP_APP\n"107 lineNum = lineNum + 1108 timeStamp = timeStamp+3000109 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_CLEAR_DATA\n"110 lineNum = lineNum + 1111 timeStamp = timeStamp+3000112 qsLines += str(lineNum) + " " + str(timeStamp) + ": OPCODE_UNINSTALL_APP\n"113 qs_src = workFolder + "\\" + packageName + "_seed_{}.qs".format(each_seed_value)114 writeFile(qs_src, qsLines)115 return qs_src116def MatchRnR(rnr_configinfo, rnr_folder, app_ver, device_info_dict, priority_items):117 # If there is rnr config suite information118 rnr_xml = ''119 dep_list = []120 # schedule the xml script.121 dependencies_list = []122 rnr_xml, dependencies_list = scheduleRnR(app_ver, device_info_dict, rnr_configinfo, priority_items)123 if not os.path.isabs(rnr_xml):124 # For relative path, combine the full path.125 rnr_xml = r'%s\%s' % (rnr_folder , rnr_xml)126 return rnr_xml, dependencies_list127def anyRnRTest(package_name, apk_folder, rnrpath, priority_items):128 try:129 rnr_folder = apk_folder + "\\" + package_name130 if rnrpath <> "" and os.path.exists(rnrpath):131 rnr_folder = rnrpath + "\\" + package_name132 from dvcutility import RnRConfigInfo133 # Check if RnR folder is there.134 rnr_config_suite_found = False135 rnr_configinfo_suite_list =[]136 des_list = []137 if os.path.exists(rnr_folder) and os.path.isdir(rnr_folder):138 # Get all rnr config info for this package139 rnr_config_file = r'%s\RnR_Scripts_Config.xml' % (rnr_folder)140 if os.path.exists(rnr_config_file):141 rnr_config = RnRConfigInfo(rnr_config_file)142 rnr_configinfo_suite_list, des_list = rnr_config.GetRnRConfigsInfo(priority_items)143 else:144 # Search for the .xml script145 for list in os.listdir(rnr_folder):146 #When RnR script replaying, coverage file xxx_cov.xml and xxx_all_cov.xml will be created, so filter these two _cov.xml147 if os.path.splitext(list)[1].strip() == '.xml' and not list.endswith('_cov.xml') and list <> 'RnR_Scripts_config.xml': 148 rnr_xml = r'%s\%s' % (rnr_folder, list)149 rnr_configinfo_suite_list.append(rnr_xml)150 break 151 else:152 rnr_folder = ''153 except Exception, e:154 s = sys.exc_info()155 print("[Error@%s]:%s" % (str(s[2].tb_lineno), s[1],))156 sys.exit(-1)157 return rnr_configinfo_suite_list, des_list, rnr_folder158 159 160def generateRnRQS(apk_name, rnr_folder, work_folder, ondevice_download, install_application,uninstall_application):161 try:162 for list in os.listdir(rnr_folder):163 if os.path.splitext(list)[1].strip() == '.qs':164 rnrfile = work_folder + "\\" + list165 package_name = ""166 if os.path.exists(rnrfile):167 lines = open(rnrfile, 'r')168 qsLines = ""169 account = ""170 password = ""171 script_path = os.path.dirname(os.path.abspath(sys.argv[0]))172 smartlogin = ""173 for line in lines:174 if line.find(" LOGIN_START") > 0 and account <> "" and password <> "":175 smartlogin = "start"176 if line.find(" LOGIN_END") > 0 and smartlogin == "start":177 smartlogin = ""178 if smartlogin == "start" and line.find("OPCODE_SET_TEXT ") > 0:179 smartlogin = "account"180 tmp_lines = line.split(":")181 qsLines += tmp_lines[0] + ' OPCODE_SET_TEXT "' + account + '"\n'182 continue183 if smartlogin == "account" and line.find("OPCODE_SET_TEXT ") > 0:184 smartlogin = ""185 tmp_lines = line.split(":")186 qsLines += tmp_lines[0] + ' OPCODE_SET_TEXT "' + password + '"\n'187 continue188 if line.startswith("PackageName="):189 qsLines += line190 package_name = line.split("=")[1].strip()191 config_file_name = script_path + "\\SmokeConfig.csv"192 config_content = readConfigFile(config_file_name)193 account_info = config_content['account_info']194 for account in account_info:195 package_account_password = account.split(',')196 if (len(package_account_password) < 3):197 continue198 if (package_account_password[0] == package_name):199 account = package_account_password[1]200 password = package_account_password[2]201 break202 elif line.startswith("APKName="):203 qsLines += "APKName=" + apk_name + "\n"204 elif "OPCODE_INSTALL_APP" in line:205 if ondevice_download:206 continue207 if install_application.lower().strip() == "yes":208 end_index = line.index("OPCODE_INSTALL_APP") + len("OPCODE_INSTALL_APP")209 qsLines += line[0:end_index] + "\n"210 elif "OPCODE_UNINSTALL_APP" in line:211 if ondevice_download:212 continue213 if uninstall_application.lower().strip() == "yes":214 end_index = line.index("OPCODE_UNINSTALL_APP") + len("OPCODE_UNINSTALL_APP")215 qsLines += line[0:end_index] + "\n"216 else:217 qsLines += line218 writeFile(rnrfile, qsLines)219 lines.close()220 except Exception, e:221 s = sys.exc_info()222 print("[Error@%s]:%s" % (str(s[2].tb_lineno), s[1],))223 sys.exit(-1)224def normalize_values(rnr_config_dict_list, device_info_dict):225 try:226 base_resolution_large = int(device_info_dict['Resolution'].strip().split('x')[1])227 base_resolution_small = int(device_info_dict['Resolution'].strip().split('x')[0])228 base_DPI = int(device_info_dict['DPI'])229 for rnr_config_dict in rnr_config_dict_list:230 # If resolution is *, do not need to normalize231 if rnr_config_dict['Resolution'].strip() == '*':232 rnr_config_dict['normalized_score'] = '0'233 continue234 resolution_large = int(rnr_config_dict['Resolution'].strip().split('x')[1])235 resolution_small = int(rnr_config_dict['Resolution'].strip().split('x')[0])236 if resolution_large == base_resolution_large and base_resolution_small == resolution_small:237 rnr_config_dict['normalized_score'] = '1'238 continue239 rnr_config_dict['normalized_score'] = '0'240 normalized_resolution_large = 0241 normalized_resolution_small = 0242 normalized_DPI = 0243 if base_resolution_large > resolution_large:244 factor = base_resolution_large / resolution_large245 normalized_resolution_large = int(round(resolution_large * factor))246 normalized_resolution_small = int(round(resolution_small * factor))247 if rnr_config_dict['DPI'].strip() <> '*':248 normalized_DPI = int(round(int(rnr_config_dict['DPI']) * factor, 0))249 else:250 factor = resolution_large / base_resolution_large251 normalized_resolution_large = int(round(resolution_large / factor))252 normalized_resolution_small = int(round(resolution_small / factor))253 if rnr_config_dict['DPI'].strip() <> '*':254 normalized_DPI = int(round(int(rnr_config_dict['DPI']) / factor, 0))255 else:256 normalized_DPI = -1257 # After normalization, if the value is base_value+-1, will consider they are the same.258 if normalized_resolution_large == base_resolution_large + 1 or normalized_resolution_large == base_resolution_large - 1:259 normalized_resolution_large = base_resolution_large260 if normalized_resolution_small == base_resolution_small + 1 or normalized_resolution_small == base_resolution_small - 1:261 normalized_resolution_small = base_resolution_small262 if normalized_DPI == base_DPI + 1 or normalized_DPI == base_DPI - 1:263 normalized_DPI = base_DPI264 if normalized_DPI <> -1:265 rnr_config_dict['DPI'] = str(normalized_DPI)266 rnr_config_dict['Resolution'] = '%sx%s' % (str(normalized_resolution_small), str(normalized_resolution_large))267 except Exception, e:268 s = sys.exc_info()269 print("[Error@%s]:%s" % (str(s[2].tb_lineno), s[1],))270 sys.exit(-1)271def scheduleRnR(app_ver, device_info_dict, rnr_configinfo_list, config_priority_list):272 try:273 max_score = -1274 cur_mode_score = -1275 cur_xml = ''276 dependencies = ''277 cur_normalized_score = -1278 # Copy the rnr_configinfo_list and use the copy to normalize279 rnr_configinfo_list_normalized = []280 normalized_score = []281 for rnr_configinfo in rnr_configinfo_list:282 rnr_configinfo_list_normalized.append(dict.copy(rnr_configinfo))283 normalize_values(rnr_configinfo_list_normalized, device_info_dict)284 # Schedule according to the normalized values285 for rnr_configinfo in rnr_configinfo_list_normalized:286 device_info_dict_tmp = device_info_dict287 matched_score = 0288 mode_score = 0289 # Calculate the match score and mode socre according to config priority290 for config in config_priority_list:291 # AppVer is provided by parameter292 if config.lower() == 'appver':293 device_value = app_ver.strip()294 else:295 if device_info_dict_tmp.has_key(config):296 device_value = device_info_dict_tmp[config].strip()297 if rnr_configinfo.has_key(config):298 config_value = rnr_configinfo[config].strip()299 #For resolution, 00: no matching. 01: match with *. 10: match with normalized value. 11: accurate matching.300 if config.lower() == 'resolution':301 if config_value == '*':302 # 01: match with *303 matched_score = matched_score << 1304 matched_score += 1305 elif device_value <> config_value:306 # 00: no matching307 matched_score = matched_score << 1308 else:309 if rnr_configinfo['normalized_score'] == '0':310 # 10: match with normalized value.311 matched_score += 1312 matched_score = matched_score << 1313 else:314 # 11: accurate matching.315 matched_score += 1316 matched_score = matched_score << 1317 matched_score += 1318 else:319 # If config is *, it means vague matching, mode score is 0;320 if config_value == '*':321 matched_score += 1322 # Other wise, if it is accurate match, mode score is 1.323 else:324 if device_value == config_value:325 matched_score += 1326 mode_score += 1327 # Left shift score 1 bit.328 matched_score = matched_score << 1329 mode_score = mode_score << 1330 # Find the max score. If the match score is the same with max score, check mode score.331 # That is to say, to check the priority of the matched item.332 if ( matched_score > max_score ) or ( matched_score == max_score and mode_score > cur_mode_score ):333 max_score = matched_score334 cur_mode_score = mode_score335 cur_xml = rnr_configinfo['path']336 if rnr_configinfo.has_key('dependencies'):337 dependencies = rnr_configinfo['dependencies']338 dependencies_list = []339 if dependencies.strip() <> '':340 dependencies_list = dependencies.split(',')341 return cur_xml, dependencies_list342 except Exception, e:343 s = sys.exc_info()344 print("[Error@%s]:%s" % (str(s[2].tb_lineno), s[1],))345 sys.exit(-1)346def generateQSfile(davinci_folder, script_path, apk_folder, apk_name, work_folder, seed_value, abi_value,347 ondevice_download, needInstall='yes',needUninstall='yes'):348 # Only one case that apk_name is not a .apk file: on-device download, but failed to fetch. In this case, apk_name's value is package name.349 if os.path.splitext(apk_name)[1] <> '.apk':350 package_name = apk_name351 apk_name = ""352 else:353 package_name = getApkPackageName(davinci_folder, work_folder, apk_name)354 QSfile = ""355 rnrfile = ""356 configContent = {}357 config_file_name = script_path + "\\SmokeConfig.csv"358## file_path = work_folder + "\\DaVinciEmptyPackageName.txt"359 if not os.path.exists(config_file_name):360 print "Smoke test config file %s does not exist." % config_file_name361 sys.exit(-1)362 config_content = readConfigFile(config_file_name)363 # seed_value = config_content['seed_value']364 total_action_number = config_content['total_action_number']365 wait_time = config_content['wait_time']366 relaunch_number = config_content['relaunch_number']367 back_action = config_content['back_action']368 record_video = config_content['record_video']369 record_video_failed_app = config_content['record_video_failed_app']370 click_percentage = config_content['click_percentage']371 swipe_percentage = config_content['swipe_percentage']372 dispatch_keyword_pos = config_content['dispatch_keyword_pos']373 dispatch_ads_pos = config_content['dispatch_ads_pos']374 test_login = config_content['test_login']375 account_info = config_content['account_info']376 data_info = config_content['data_info']377 logcat_package_name = ""378 if ('logcat_package_name' in config_content.keys()):379 logcat_package_name = config_content['logcat_package_name']380 # If the apk is ondevice downloaded, run_qs.py set install or not. 381 # For local apk, SmokeConfig.csv set install or not.382 if (ondevice_download):383 install_application = needInstall384 uninstall_application = needUninstall385 else:386 install_application = config_content['install_application']387 uninstall_application = config_content['uninstall_application']388 try:389 # generate smoke script390 if apk_name <> "" or package_name <> "":391 generateOneBias(script_path, package_name, logcat_package_name, click_percentage, swipe_percentage,392 account_info, work_folder, test_login, seed_value, dispatch_keyword_pos, dispatch_ads_pos)393 QSfile = generateOneQS(int(relaunch_number), apk_name, package_name, total_action_number, int(wait_time),394 record_video, apk_folder, work_folder, install_application, uninstall_application,395 back_action, data_info, record_video_failed_app, seed_value, abi_value)396 return QSfile397 398 except Exception as ex:399 print("Failed to create qsfile: %s" % str(ex))400 return "" 401def generateOneBias(script_path, package_name, logcat_package_name, click_percentage, swipe_percentage, account_info,402 work_folder, test_login, seed_value, dispatch_keyword_pos, dispatch_ads_pos):403 testLogin = False404 account = ""405 password = ""406 configContent = {}407 config_file_name = script_path + "\\SmokeConfig.csv"408 if not os.path.exists(config_file_name):409 print "Smoke test config file %s does not exist." % config_file_name410 sys.exit(-1)411 if test_login.lower().startswith("y"):412 for account in account_info:413 package_account_password = account.split(',')414 if (len(package_account_password) < 3):415 continue416 if (package_account_password[0] == package_name):417 account = package_account_password[1]418 password = package_account_password[2]419 testLogin = True420 break421 biasLines = ""422 biasLines += "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n"423 biasLines += "<DaVinci>\n"424 biasLines += "<Seed value=\""+ str(seed_value) +"\"/>\n"425 biasLines += "<Test type=\"SMOKE\" mode=\"OBJECT\" silent=\"NO\" coverage=\"YES\">\n"426 biasLines += "<Action type=\"CLICK\" value=\"" + click_percentage + "%\">\n"427 biasLines += "<Click type=\"PLAIN\" value=\"100%\"/>\n"428 biasLines += "</Action>" + "\n"429 biasLines += "<Action type=\"SWIPE\" value=\"" + swipe_percentage + "%\"/>\n"430 if testLogin == True:431 biasLines += "<Action type=\"ACCOUNT\" value=\"YES\">\n"432 biasLines += "<Account name=\"" + account + "\" password=\"" + password + "\" misc=\"\"/>\n"433 biasLines += "</Action>\n"434 if len(logcat_package_name) > 0:435 for pname in logcat_package_name.split(';'):436 if len(pname.strip()) > 0:437 biasLines += "<Action type=\"Log\">\n"438 biasLines += "<Package name=\"" + pname.strip() + "\"/>\n"439 biasLines += "</Action>\n"440 biasLines += "</Test>\n"441 biasLines += "<ActionPossibility>\n"442 biasLines += "<CommonKeywordPossibility value=\"" + dispatch_keyword_pos + "%\"/>\n"443 biasLines += "<AdsPossibility value=\"" + dispatch_ads_pos + "%\"/>\n"444 biasLines += "</ActionPossibility>\n"445 biasLines += "</DaVinci>"446 writeFile(work_folder + "\\" + "bias_{}.xml".format(seed_value), biasLines)447def isWritable(src):448 fileAtt = os.stat(src)[0]449 if (not fileAtt & stat.S_IWRITE):450 return False451 return True452def copyFile(src, dest):453 try:454 shutil.copy(src, dest)455 except Exception as ex:456 print('')457def copyFolder(sourceDir, targetDir, file_filter = [], folder_filter = [], ondevice_download = False):458 try:459 for f in os.listdir(sourceDir):460 sourceF = os.path.join(sourceDir, f)461 targetF = os.path.join(targetDir, f)462 if os.path.isfile(sourceF):463 # In on-device download mode, if APK is fetched already, we shall not overwrite it.464 if ondevice_download and os.path.splitext(f)[1] == '.apk' and os.path.exists(targetF):465 continue466 467 if f in file_filter:468 continue 469 if os.path.splitext(f)[1] in file_filter:470 continue471 # create folder472 if not os.path.exists(targetDir):473 os.makedirs(targetDir)474 # file is not exist or size is different, replace it475 if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):476 open(targetF, "wb").write(open(sourceF, "rb").read())477 if os.path.isdir(sourceF):478 if f in folder_filter:479 continue480 copyFolder(sourceF, targetF, file_filter, folder_filter, ondevice_download)481 except Exception,e:482 s = sys.exc_info()483 print("[Error@%s]:%s" % (str(s[2].tb_lineno), s[1],))484def ContainNoneASCII(apkName):485 for ch in apkName:486 if ch > u'\u007f':487 return True488 return False489def CallAPKInfo(davinciFolder, apkFolder, apkName, info):490 infoValue=""491 apkPath = apkName492 if (apkPath.find("\\") < 0):493 apkPath = r'%s\%s' %(apkFolder, apkName)494 cmd = davinciFolder + "\\platform-tools\\aapt.exe dump badging \"" + apkPath + "\""495 #cmd = cmd.encode("utf-8")496 packageInfo = os.popen(cmd).readlines()497 for pInfo in packageInfo:498 if pInfo.startswith(info):499 infoValue = pInfo[len(info):]500 infoValue = (infoValue.split('\''))[0]501 break502 return infoValue503def getApkInfo(davinci_folder, apk_folder, apk_name, info):504 apk_name = apk_name.decode('utf-8')505 info_value = ""506 if apk_folder == "":507 apk_folder = ".\\"508 apk_folder = apk_folder.replace("/","\\")509 if apk_folder[-1]!="\\":510 apk_folder = apk_folder + "\\"511 dest_folder = apk_folder512 if apk_name[-4:] == ".apk":513 if ContainNoneASCII(apk_name):514 # check if the apk is writeable, since we need to copy and delete file515 srcPath = apk_name516 if srcPath.find("\\") < 0:517 srcPath = apk_folder + apk_name518 if apk_folder.startswith("\\\\"): # if apk_folder is a sharefolder, copy the apk to local host machine519 dest_folder = os.getcwd()520 if os.path.exists(srcPath):521 if isWritable(srcPath) == True:522 copyFile(srcPath, os.path.join(dest_folder,"testapk"))523 info_value = CallAPKInfo(davinci_folder, dest_folder, "testapk", info)524 Enviroment.remove_item(os.path.join(dest_folder,"testapk"), False)525 else:526 print "Couldn't find the apk file for testing!"527 #sys.exit(-1)528 else:529 info_value = CallAPKInfo(davinci_folder, apk_folder, apk_name, info)530 return info_value531def getApkPackageName(davinci_folder, apk_folder, apk_name):532 apk_name = apk_name.decode('utf-8')533 package_name = getApkInfo(davinci_folder, apk_folder, apk_name,"package: name='")534 return package_name535def initConfigKeyValue():536 configKeyValue = {}537 configKeyValue['seed_value'] = "seed value"538 configKeyValue['total_action_number'] = "total action number"539 configKeyValue['click_percentage'] = "click percentage"540 configKeyValue['swipe_percentage'] = "swipe percentage"541 configKeyValue['wait_time'] = "time to wait"542 configKeyValue['relaunch_number'] = "relaunch application"543 configKeyValue['install_application'] = "install application"544 configKeyValue['back_action'] = "perform back action"545 configKeyValue['uninstall_application'] = "uninstall application"546 configKeyValue['record_video'] = "record video or not"547 configKeyValue['record_video_failed_app'] = "record video for failed app"548 configKeyValue['test_login'] = "test login"549 configKeyValue['logcat_package_name'] = "specific package name"550 configKeyValue['dispatch_keyword_pos'] = "dispatch common keyword action percentage"551 configKeyValue['dispatch_ads_pos'] = "dispatch advertisement action percentage"552 return configKeyValue553def readConfigFile(config_file_name):554 configContent = {}555 accountInfo = []556 dataInfo = []557 inputmethodApps = []558 launcherApps = []559 accounts_line = False560 data_line = False561 inputmethod_line = False562 launcher_line = False563 configKeyValue = initConfigKeyValue()564 config_file = open(config_file_name, "r")565 for line in config_file:566 if line.strip() == "":567 continue568 content = line.split(',')569 # skip bad line570 if len(content) < 2:571 continue572 if (accounts_line == False and data_line == False):573 for (k,v) in configKeyValue.items():574 if (content[0].lower().strip().startswith(v)):575 configContent[k] = content[1].strip()576 if (accounts_line == True and data_line == False):577 accountInfo.append(line.strip())578 if (data_line == True and inputmethod_line == False):579 dataInfo.append(line.strip())580 if (inputmethod_line == True and launcher_line == False):581 inputmethodApps.append(content[1].strip())582 if (launcher_line == True):583 launcherApps.append(content[1].strip())584 if (content[1].lower().strip() == "account name"):585 accounts_line = True586 if (content[1].lower().strip() == "source path"):587 data_line = True588 if (content[1].lower().strip() == "input method apps"):589 inputmethod_line = True590 if (content[1].lower().strip() == "launcher apps"):591 launcher_line = True592 accountInfo.pop() # should pop up the last item, the last item is the header of push data:'Package Name,Source Path,Dest Path'593 dataInfo.pop()594 inputmethodApps.pop()595 configContent['account_info'] = accountInfo596 configContent['data_info'] = dataInfo597 configContent['inputmethod_apps'] = inputmethodApps598 configContent['launcher_apps'] = launcherApps599 config_file.close()600 return configContent601def ReadDaVinciApplistXML(applist_xml):602 inputmethod_apps = []603 launcher_apps = []604 root = ElementTree.parse(applist_xml).getroot()605 for child in root:606 if (child.attrib['type'] == "InputMethodApps"):607 for item in child.findall('AppName'):608 inputmethod_apps.append(item.get('value'))609 if (child.attrib['type'] == "LauncherApps"):610 for item in child.findall('AppName'):611 launcher_apps.append(item.get('value'))612 return inputmethod_apps, launcher_apps613def WriteDaVinciApplistXML(applist_xml, new_inputmethod, new_launcher):614 tree = ElementTree.parse(applist_xml)615 root = tree.getroot()616 for child in root:617 if (child.attrib['type'] == "InputMethodApps"):618 for item in new_inputmethod:619 new_node = ElementTree.Element("AppName")620 new_node.set("value", item)621 child.insert(0, new_node) # insert new input method app which comes from SmokeConfig.csv622 if (child.attrib['type'] == "LauncherApps"):623 for item in new_launcher:624 new_node = ElementTree.Element("AppName")625 new_node.set("value", item)626 child.insert(0, new_node) # insert new launcher app which comes from SmokeConfig.csv627 tree.write(applist_xml)628 return 0629def CompareAndMergeApplistXML(script_folder, davinci_folder):630 config_file_name = script_folder + "\\SmokeConfig.csv"631 if not os.path.exists(config_file_name):632 print "Smoke test config file %s does not exist." % config_file_name633 sys.exit(-1)634 applist_xml = davinci_folder + "\\DaVinci_Applist.xml"635 if not os.path.exists(applist_xml):636 print "DaVinci app list file %s does not exist." % applist_xml637 sys.exit(-1)638 # read input method and launcher apps from SmokeConfig.csv639 config_content = readConfigFile(config_file_name)640 config_inputmethod = config_content['inputmethod_apps']641 config_launcher = config_content['launcher_apps']642 # read input method and launcher app from DaVinci_Applist.xml643 init_inputmethod, init_launcher = ReadDaVinciApplistXML(applist_xml)644 # compare two kinds of input method and launcher apps645 new_inputmethod = []646 new_launcher = []647 for app in config_inputmethod:648 if app not in init_inputmethod:649 new_inputmethod.append(app)650 for app in config_launcher:651 if app not in init_launcher:652 new_launcher.append(app)653 # merge new input method app and launcher app into DaVinci_Applist.xml654 if (len(new_inputmethod) != 0 or len(new_launcher) != 0):655 WriteDaVinciApplistXML(applist_xml, new_inputmethod, new_launcher)...
__init__.py
Source:__init__.py
1# -*- coding: utf-8 -*-2#3# Copyright 2010-2012 Canonical Ltd.4#5# This program is free software: you can redistribute it and/or modify it6# under the terms of the GNU General Public License version 3, as published7# by the Free Software Foundation.8#9# This program is distributed in the hope that it will be useful, but10# WITHOUT ANY WARRANTY; without even the implied warranties of11# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR12# PURPOSE. See the GNU General Public License for more details.13#14# You should have received a copy of the GNU General Public License along15# with this program. If not, see <http://www.gnu.org/licenses/>.16"""Miscellaneous utilities."""17import os18import sys19from ubuntuone.controlpanel.logger import setup_logging20logger = setup_logging('utils')21DATA_SUFFIX = 'data'22ERROR_TYPE = 'error_type'23ERROR_MESSAGE = 'error_msg'24# ignore issues with the name of the method25# pylint: disable=C010326no_op = lambda *args, **kwargs: None27# import the platform dependent code.28if sys.platform == 'win32':29 from ubuntuone.controlpanel.utils import windows30 add_to_autostart = windows.add_to_autostart31 are_updates_present = windows.are_updates_present32 default_folders = windows.default_folders33 perform_update = windows.perform_update34 uninstall_application = windows.uninstall_application35else:36 from ubuntuone.controlpanel.utils import linux37 add_to_autostart = no_op38 are_updates_present = no_op39 default_folders = linux.default_folders40 perform_update = no_op41 uninstall_application = no_op42# pylint: enable=C010343def get_project_dir():44 """Return the absolute path to this project's data/ dir.45 Support symlinks, and priorize local (relative) data/ dir.46 """47 module = os.path.dirname(__file__)48 result = os.path.abspath(os.path.join(module, os.path.pardir,49 os.path.pardir, os.path.pardir,50 DATA_SUFFIX))51 logger.debug('get_project_dir: trying use data dir at %r (exists? %s)',52 result, os.path.exists(result))53 if os.path.exists(result):54 logger.info('get_project_dir: returning dir located at %r.', result)55 return result56 # otherwise, try to load PROJECT_DIR from installation path57 try:58 # pylint: disable=F0401, E0611, W040459 from ubuntuone.controlpanel.constants import PROJECT_DIR60 return PROJECT_DIR61 except ImportError:62 msg = 'get_project_dir: can not build a valid path. Giving up. ' \63 '__file__ is %r, constants module not available.'64 logger.error(msg, __file__)65def get_data_file(filename):66 """Return the absolute path to 'filename' within data/ dir."""67 return os.path.join(get_project_dir(), filename)68def exception_to_error_dict(exc):69 """Transform a regular Exception into a dictionary."""70 result = {ERROR_TYPE: exc.__class__.__name__, ERROR_MESSAGE: unicode(exc)}71 return result72def failure_to_error_dict(failure):73 """Transform a twisted Failure into a dictionary."""...
app.py
Source:app.py
...82 default=False,83 help='Delete application without confirmation'84)85@click.argument('appkey')86def uninstall_application(force, appkey):87 """Uninstall workflow with the given key."""88 if not force: # pragma: no cover89 click.echo('This will erase all workflow files and run results.')90 click.confirm('Continue?', default=True, abort=True)91 Flowserv(open_access=True).uninstall(identifier=appkey)92# -- Command group ------------------------------------------------------------93@click.group()94def cli_app():95 """Install and uninstall applications."""96 pass97cli_app.add_command(install_application, name='install')...
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!!