def validate_xml(filepath): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: f = StringIO("""\ <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="a" type="AType"/> <xsd:complexType name="AType"> <xsd:sequence> <xsd:element name="b" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:schema> """) xmlschema_doc = etree.parse(f) xmlschema = etree.XMLSchema(xmlschema_doc) f = open(filepath) xml = f.read() f.close() valid = StringIO(xml) doc = etree.parse(valid) try: xmlschema.validate(doc) CommonUtil.ExecLog(sModuleInfo, "%s file is validated." % filepath, 1) except Exception: errMsg = "%s file is not validated." % filepath return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg) except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def sequential_actions( dependency, run_time_params, step_data, test_action_info, file_attachment, temp_q, screen_capture, device_info, debug_actions=None, ): try: sTestStepReturnStatus = sa.Sequential_Actions( step_data, test_action_info, dependency, run_time_params, temp_q, screen_capture, device_info, debug_actions, ) return CommonUtil.Result_Analyzer(sTestStepReturnStatus, temp_q) except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), temp_q)
def check_tags_exist(filepath, tag, subtag): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: doc = ET.parse(filepath).getroot() for event in doc.findall(tag): if event is None: CommonUtil.ExecLog(sModuleInfo, "%s tag is not found." % tag, 3) else: CommonUtil.ExecLog(sModuleInfo, "%s tag is found." % tag, 1) for host in event.findall(subtag): if host is None: CommonUtil.ExecLog(sModuleInfo, "%s tag is not found." % subtag, 3) else: CommonUtil.ExecLog( sModuleInfo, "%s tag is found in %s." % (subtag, tag), 1) except Exception: errMsg = "%s - %s tag existence is not checked. " % (filepath, tag) return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_product_name(UDID=""): """ Reads the phone name """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME CommonUtil.ExecLog(sModuleInfo, "Started", 0) try: output = get_device_info(UDID) # Get device info in list format tmp = "" product_name = "" for line in output: if "productname" in line.lower(): tmp = line if tmp != "": tmp = tmp.split(":") product_name = tmp[1].strip() if product_name == "": CommonUtil.ExecLog( sModuleInfo, "Could not read the iOS product name the device", 3 ) return "zeuz_failed" CommonUtil.ExecLog(sModuleInfo, "%s" % product_name, 0) return product_name except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def get_target_element(file_path, target_parameter, target_value, action_name, action_value, step_data): """ Function to get the target element(s) as per 'action' """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: file_tree = [] # Function to get the XML file tree file_tree = get_file_tree(file_path) driver = None driver = file_tree[0] # Function to get the elements from the XML file matching_elements = LE.Get_Element(step_data, driver) CommonUtil.ExecLog( sModuleInfo, ">>> The expected attribute value is: '%s'" % action_value, 1) # Function to update the target element returned_target_element = update_target_element( file_path, file_tree[1], matching_elements, target_parameter, target_value, action_name, action_value, ) return returned_target_element except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def get_ios_version(UDID=""): """ Reads the device version """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME CommonUtil.ExecLog(sModuleInfo, "Started", 0) try: output = get_device_info(UDID) # Get device info in list format tmp = "" version = "" for line in output: if "productversion" in line.lower(): tmp = line if tmp != "": tmp = tmp.split(":") version = tmp[1].strip() if version == "": CommonUtil.ExecLog( sModuleInfo, "Could not read the iOS version from the device", 3 ) return "zeuz_failed" CommonUtil.ExecLog(sModuleInfo, "%s" % version, 0) return version except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def check_if_device_is_unlocked(serial=""): # if device is locked, current focused window always shows "StatusBar" only sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: if serial != "": serial = "-s %s" % serial # Prepare serial number with command line switch subprocess.check_output( "adb %s shell input keyevent 82" % (serial), shell=True, encoding="utf-8") # Wakeup device and bring it unlock window time.sleep(1) output = subprocess.check_output( "adb %s exec-out uiautomator dump /dev/tty" % serial, shell=True, encoding="utf-8", ) if "EMERGENCY" in output or "emergency_call_button" in output: CommonUtil.ExecLog( sModuleInfo, "Device is currently locked. We will proceed with unlock ", 2, ) return False else: CommonUtil.ExecLog(sModuleInfo, "Device is currently unlocked ", 1) return True except Exception: errMsg = "Unable to determine if device is locked or not" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_device_storage(serial=""): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: if serial != "": serial = "-s %s" % serial # Prepare serial number with command line switch output = subprocess.check_output("adb %s shell df /data" % serial, shell=True, encoding="utf-8") CommonUtil.ExecLog(sModuleInfo, "%s" % output, 0) storageList = " ".join(output.split()) storageList = storageList.split(" ") storage = storageList[6] storage = storage.replace("G", "") storage = float(storage) final_storage = 0 exp = 2 while True: gb = math.pow(2, exp) if storage < gb: final_storage = gb break exp += 1 final_storage = int(final_storage) return final_storage except Exception: errMsg = "Unableto get device storage" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def view_info_about_colligo( dependency, run_time_params, step_data, file_attachment, temp_q, screen_capture ): try: sTestStepReturnStatus = NETAutomation.view_info_about_colligo(step_data) return CommonUtil.Result_Analyzer(sTestStepReturnStatus, temp_q) except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), temp_q)
def check_for_element(data_set): """ Tests whether or not an element is visible on screen """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME # Parse data set try: file_name = "" for row in data_set: if row[1] == "element parameter": file_name = row[2] if file_name == "": CommonUtil.ExecLog( sModuleInfo, "Valid element not found. Expected Sub-Field to be 'element parameter', and Value to be a filename", 3, ) return "zeuz_failed" except Exception: errMsg = "Error parsing data set" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg) # Perform action try: CommonUtil.ExecLog(sModuleInfo, "Performing check action on file %s" % (file_name), 0) element = LocateElement.Get_Element(data_set, gui) # (x, y, w, h) # CommonUtil.TakeScreenShot( # sModuleInfo # ) # Capture screenshot, if settings allow for it if element in failed_tag_list: CommonUtil.ExecLog(sModuleInfo, "Element not found", 3) return "zeuz_failed" else: CommonUtil.ExecLog(sModuleInfo, "Found element", 1) return "passed" except Exception: errMsg = "Error parsing data set" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def playback_recorded_events(data_set): """Plays back the recorded events from a given file.""" sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME # Parse data set try: filepath = "" speed_factor = 1.0 for left, _, right in data_set: left = left.lower().strip() if "file path" in left: filepath = right.strip() filepath = CommonUtil.path_parser(filepath) elif "speed factor" in left: speed_factor = float(right.strip()) if filepath == "": CommonUtil.ExecLog( sModuleInfo, "A valid path to the recorded event file must be provided. If you've uploaded it into attachments with name `recording_1.zvt`," " you can use it by providing the path as `%|recording_1.zvt|%`", 3, ) return "zeuz_failed" except Exception: errMsg = "Error parsing data set" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg) # Perform action try: CommonUtil.ExecLog(sModuleInfo, "Playing the events recorded in - %s" % filepath, 1) playback_chooser = ChoosePlaybackModule(filepath) playback_chooser.play(speed_factor=speed_factor) CommonUtil.ExecLog(sModuleInfo, "DONE playing back events.", 1) return "passed" except Exception: errMsg = "Failed to playback recorded events from file: %s" % filepath return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def check_form(filepath): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: x = ET.fromstring(filepath) CommonUtil.ExecLog(sModuleInfo, "%s file is well-formed. %s" % filepath, 1) except Exception: errMsg = "%s file is not well-formed." % filepath return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def run_program(cmd): """ Executes a command line program """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: output = subprocess.check_output( imobiledevice_path + cmd, shell=True, encoding="utf-8" ) # Execute command line program, and return STDOUT return output except: # If command produced a non-zero return code, return failed return CommonUtil.Exception_Handler(sys.exc_info())
def add_an_item_to_cart_on_amazon_using_selenium( dependency, run_time_params, step_data, file_attachment, temp_q, screen_capture, device_info, ): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: CommonUtil.ExecLog( sModuleInfo, "Enter: Step - Add an Item to Cart on Amazon Using Selenium", 1) sTestStepReturnStatus = Amazon.Add_to_Cart_Using_Selenium( step_data, file_attachment) if sTestStepReturnStatus in passed_tag_list: CommonUtil.ExecLog(sModuleInfo, "Successfully Added an Item to Cart on Amazon", 1) temp_q.put(sTestStepReturnStatus) CommonUtil.ExecLog( sModuleInfo, "Exit: Step - Add an Item to Cart on Amazon Using Selenium", 1, ) return sTestStepReturnStatus elif sTestStepReturnStatus in failed_tag_list: CommonUtil.ExecLog(sModuleInfo, "Unable to add an item on Amazon", 3) temp_q.put(sTestStepReturnStatus) CommonUtil.ExecLog( sModuleInfo, "Exit: Step - Add an Item to Cart on Amazon using selenium", 1, ) return sTestStepReturnStatus else: CommonUtil.ExecLog( sModuleInfo, "Step return type unknown: %s" % (sTestStepReturnStatus), 3) temp_q.put("zeuz_failed") CommonUtil.ExecLog( sModuleInfo, "Exit: Step - Add an item to cart on Amazon using selenium", 1, ) return sTestStepReturnStatus except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def kill_adb_server(): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: output = subprocess.check_output("adb kill-server", shell=True, encoding="utf-8") CommonUtil.ExecLog(sModuleInfo, "Killing adb server", 0) return output except Exception: errMsg = "Unable to kill adb server" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def check_wellformed(filename): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME # filename = "/home/asci/AssetScience/recell_dse-in-test/Launcher/resource/configurations/desktop-fail-codes.xml" try: parser = make_parser() parser.setContentHandler(ContentHandler()) parser.parse(filename) CommonUtil.ExecLog(sModuleInfo, "%s is well-formed. %s" % filename, 1) except Exception: errMsg = "%s is NOT well-formed! " % filename return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_device_complete_info(): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: output = subprocess.check_output("adb devices -l", shell=True, encoding="utf-8") CommonUtil.ExecLog(sModuleInfo, "%s" % output, 0) return output except Exception: errMsg = "Unable to get device complete info" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_element_step_data(step_data): """ Function to collect user provided target and action elements from step data """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: file_path = False target_parameter = False target_value = False action_parameter = False action_value = False if len(step_data) >= 1: for each in step_data: if each[1] == "path": file_path = each[2] elif ((each[1] == "parent parameter") or (each[1] == "child parameter") or (each[1] == "element parameter")): continue elif each[1] == "target parameter": target_parameter = each[0] target_value = each[2] elif each[1] == "action": action_parameter = each[0] action_value = each[2] else: CommonUtil.ExecLog(sModuleInfo, "Unable to find elements requested.", 3) else: CommonUtil.ExecLog( sModuleInfo, "Data set incorrect. Please provide accurate data set(s) information.", 3, ) return "zeuz_failed" returned_data = ( file_path, target_parameter, target_value, action_parameter, action_value, ) return returned_data except Exception: errMsg = "Could not get element step data." return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def connect_to_db(data_set): """ This action just stores the different database specific configs into shared variables for use by other actions. NOTE: The actual db connection does not happen here, connection to db is made inside the actions which require it. db_type input parameter <type of db, ex: postgres, mysql> db_name input parameter <name of db, ex: zeuz_db> db_user_id input parameter <user id of the os who have access to the db, ex: postgres> db_password input parameter <password of db, ex: mydbpass-mY1-t23z> db_host input parameter <host of db, ex: localhost, 127.0.0.1> db_port input parameter <port of db, ex: 5432 for postgres by default> sid optional parameter <sid of db, ex: 15321 for oracle by default> service_name optional parameter <service_name of db, ex: 'somename' for oracle by default> odbc_driver optional parameter <specify the odbc driver, optional, can be found from pyodbc.drivers()> connect to db database action Connect to a database :param data_set: Action data set :return: string: "passed" or "zeuz_failed" depending on the outcome """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: for left, _, right in data_set: if left == DB_TYPE: sr.Set_Shared_Variables(DB_TYPE, right) if left == DB_NAME: sr.Set_Shared_Variables(DB_NAME, right) if left == DB_USER_ID: sr.Set_Shared_Variables(DB_USER_ID, right) if left == DB_PASSWORD: sr.Set_Shared_Variables(DB_PASSWORD, right) if left == DB_HOST: sr.Set_Shared_Variables(DB_HOST, right) if left == DB_PORT: sr.Set_Shared_Variables(DB_PORT, right) if left == DB_SID: sr.Set_Shared_Variables(DB_SID, right) if left == DB_SERVICE_NAME: sr.Set_Shared_Variables(DB_SERVICE_NAME, right) if left == DB_ODBC_DRIVER: sr.Set_Shared_Variables(DB_ODBC_DRIVER, right) CommonUtil.ExecLog(sModuleInfo, "Trying to establish connection to the database.", 1) db_get_connection() return "passed" except Exception: traceback.print_exc() return CommonUtil.Exception_Handler(sys.exc_info())
def click_on_coordinates(data_set): """ This action executes a Left Click on the location of a given X,Y coordinates. Example: Field Sub Field Value click on coordinates desktop action 271,1051 """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: data = "" for left, _, right in data_set: if "click on coordinates" in left.lower(): data = right try: x, y = data.replace(" ", "").split(",") x = int(x) y = int(y) except: errMsg = "Coordinate values were not set according to the correct format" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg) gui.click(x, y) max_x, max_y = gui.size() x = max_x if x > max_x else x x = 0 if x < 0 else x y = max_y if y > max_y else y y = 0 if y < 0 else y Msg = "Clicked on " + str(x) + ", " + str(y) + " successfully" CommonUtil.ExecLog(sModuleInfo, Msg, 1) return "passed" except: errMsg = "Failed to click on coordinates" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def reset_all_android(): """ Resets all connected devices """ try: # Get list of all connected devices devices = get_devices() # For each device, reset it for serial in devices: reset_android(str(serial.split(" ")[0]).strip()) # Send reset except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error while resetting devices")
def getCoordinates(element, position): """ Return coordinates of attachment's centre """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME # Parse input try: x = element[0] y = element[1] w = element[2] h = element[3] position = position.lower().strip() if position not in positions: CommonUtil.ExecLog(sModuleInfo, "Position must be one of: %s" % positions, 3) return "zeuz_failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error parsing coordinates") # Perform calculations try: if position in ("center", "centre"): result_x, result_y = gui.center(element) elif position == "left": result_x = x + (w * 0.01) result_y = y + (h / 2) elif position == "right": result_x = x + (w * 0.99) result_y = y + (h / 2) if result_x in failed_tag_list or result_x == "" or result_x == None: return "zeuz_failed", "" return int(result_x), int(result_y) except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error calculating coordinates")
def get_list_udid(): """ Returns a list of UDID's for connected IOS devices """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME CommonUtil.ExecLog(sModuleInfo, "Started", 0) try: cmd = "idevice_id -l" output = run_program(cmd) if output == None: return "" output = output.strip().split("\n") return output except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def Enter_Password_UIAutomator(password, serial=""): """ This function can evolve a lot more. For time being we are just looking for button with text and clicking for UNLOCKING only""" sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: # click buttons if serial != "": # Prepare serial number with command line switch from uiautomator import ( Device, ) # putting it here for now as this module was missing before. We can move it at the top after some time d = Device(serial) serial_with_id = "-s %s" % serial else: from uiautomator import device as d serial_with_id = "" button_list = list(password) subprocess.check_output( "adb %s shell input keyevent 82" % (serial_with_id), shell=True, encoding="utf-8", ) # Wakeup device time.sleep(0.5) subprocess.check_output( "adb %s shell input keyevent 82" % (serial_with_id), shell=True, encoding="utf-8", ) # Get to Unlock window time.sleep(0.5) for each_button in button_list: d(text=each_button).click() subprocess.check_output( "adb %s shell input keyevent KEYCODE_ENTER" % serial_with_id, shell=True, encoding="utf-8", ) # Press ENTER key. Note all phones do not require CommonUtil.ExecLog(sModuleInfo, "Successfully entered your password", 1) return "passed" except Exception: errMsg = "Unable to unlock device" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_device_wifi_info(serial=""): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: if serial != "": serial = "-s %s" % serial # Prepare serial number with command line switch output = subprocess.check_output("adb %s shell dumpsys wifi" % serial, shell=True, encoding="utf-8") CommonUtil.ExecLog(sModuleInfo, "%s" % output, 0) return output except Exception: errMsg = "Unable to get device wifi info" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def move_mouse_cursor(data_set) -> str: """Moves the mouse cursor to the given coordinate from the current position. The movement can be either absolute or relative from current mouse position, as specified by the "relative" optional parameter. An optional "duration" can also be set which will simulate mouse movement from one place to another as if someone was using it. Args: data_set: move mouse cursor desktop action 100, 100 (x, y - int, int) relative optional parameter true (bool) duration optional parameter 2.5 (float) Returns: "passed" if successful. "zeuz_failed" otherwise. """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: relative = False duration = 0.0 x = 0 y = 0 for left, _, right in data_set: left = left.lower() right = right.lower() if "move mouse cursor" in left: x, y = right.split(",") x = int(x.strip()) y = int(y.strip()) if "relative" in left: relative = right in ["true", "1"] if "duration" in left: duration = float(right) if relative: gui.moveRel(x, y, duration) else: gui.moveTo(x, y, duration) return "passed" except: errMsg = "Failed to move cursor to given position" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_file_tree(file_path): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: # Function to get the file parse doc = ET.parse(file_path) # Function to get the file tree tree = doc.getroot() # CommonUtil.ExecLog(sModuleInfo, "%s" % ET.tostring(tree), 1) return (tree, doc) except Exception: errMsg = "Unable to get the file tree." return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def execute_program(package_name, serial=""): """ Executes an Android program """ try: if serial != "": serial = "-s %s" % serial # Prepare serial number with command line switch cmd = "adb %s shell monkey -p %s -c android.intent.category.LAUNCHER 1" % ( serial, package_name, ) subprocess.check_output(cmd, shell=True, encoding="utf-8") return "passed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error executing Android program")
def check_exist(filepath): sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: if os.path.isfile(filepath): CommonUtil.ExecLog(sModuleInfo, "%s file is found." % filepath, 1) return "Passed" else: CommonUtil.ExecLog(sModuleInfo, "%s file is not found." % filepath, 3) return "zeuz_failed" except Exception: errMsg = "%s file existence is not checked." % filepath return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def reset_android(serial=""): """ Resets the specified device, or the only device connected """ sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME try: CommonUtil.ExecLog(sModuleInfo, "Resetting device %s" % serial, 0) if serial != "": serial = ( "-s %s" % serial ) # Prepend the command line switch to add the serial number subprocess.check_output("adb %s reboot" % serial, shell=True, encoding="utf-8") # Send reset except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error while resetting device")