我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getmoduleinfo()。
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (0, None)) if lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = (module.__doc__ or '').splitlines()[0] del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (None, None)) if lastupdate is None or lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = (module.__doc__ or '').splitlines()[0] del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (None, None)) if lastupdate is None or lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = tokenize.open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = (module.__doc__ or '').splitlines()[0] del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (None, None)) if lastupdate is None or lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = module.__doc__.splitlines()[0] if module.__doc__ else None del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result
def Data_By_GET_Method(url): # this function needs work with validating page title. We need to check if user entered any title. # if not then we don't do the validation sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: Data = requests.get(url) if(Data.status_code == 200): CommonUtil.ExecLog(sModuleInfo, "Received Proper Data your link: %s" % url, 1) return "passed" else: CommonUtil.ExecLog(sModuleInfo, "Received Wrong Data your link: %s" % url, 1) return "failed" except Exception, e: CommonUtil.ExecLog(sModuleInfo, "Exception :%s" % e, 3) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Error_Detail = ((str(exc_type).replace("type ", "Error Type: ")) + ";" + "Error Message: " + str( exc_obj) + ";" + "File Name: " + fname + ";" + "Line: " + str(exc_tb.tb_lineno)) CommonUtil.ExecLog(sModuleInfo, "Received Wrong Data your link: %s. Error:%s" % (url, Error_Detail), 3) CommonUtil.TakeScreenShot(sModuleInfo) return "failed"
def check_exist(filepath): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).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 "Failed" except Exception: errMsg = "%s file existence is not checked." % filepath return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def check_tags_exist(filepath, tag, subtag): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).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 Result_Analyzer(sTestStepReturnStatus,temp_q): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: if sTestStepReturnStatus in passed_tag_list: temp_q.put("passed") return "passed" elif sTestStepReturnStatus in failed_tag_list: temp_q.put("failed") return "failed" elif sTestStepReturnStatus in skipped_tag_list: temp_q.put("skipped") return "skipped" elif sTestStepReturnStatus.lower() == 'cancelled': # Special use to stop a scheduled run without failing it temp_q.put("cancelled") return "cancelled" else: ExecLog(sModuleInfo,"Step return type unknown: %s. The last function did not return a valid type (passed/failed/etc)" %(sTestStepReturnStatus),3) temp_q.put("failed") return "failed" except Exception, e: return Exception_Handler(sys.exc_info())
def set_screenshot_vars(shared_variables): ''' Save screen capture type and selenium/appium driver objects as global variables, so TakeScreenShot() can access them ''' # We can't import Shared Variables due to cyclic imports causing local runs to break, so this is the work around # Known issue: This function is called by Sequential_Actions(). Thus, Maindriver can't take screenshots until this is set sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name global screen_capture_driver, screen_capture_type try: if 'screen_capture' in shared_variables: # Type of screenshot (desktop/mobile) screen_capture_type = shared_variables['screen_capture'] if screen_capture_type == 'mobile': # Appium driver object if 'device_id' in shared_variables: device_id = shared_variables['device_id'] # Name of currently selected mobile device appium_details = shared_variables['appium_details'] # All device details screen_capture_driver = appium_details[device_id]['driver'] # Driver for selected device if screen_capture_type == 'web': # Selenium driver object if 'selenium_driver' in shared_variables: screen_capture_driver = shared_variables['selenium_driver'] except: ExecLog(sModuleInfo, "Error setting screenshot variables", 3)
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.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: get_target_element", 1) 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_file_tree(file_path): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: get_file_tree", 1) 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 update_action_value(file_path, doc): ''' Function the write the user provided action value in the XML file ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: update_action_value", 1) try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name #Function to write the action value in the XML file doc.write(file_path) CommonUtil.ExecLog(sModuleInfo, ">>> Writing the attribute value in the XML File...", 1) return "Passed" except Exception: errMsg = "Unable to update the action element(s)." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def get_exec_from_icon(file_name): ''' Read the Exec line from a Linux icon file ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: # Open file and read into memory with open(file_name, "r") as myfile: data = myfile.readlines() # Examine each line, looking for the Exec line for element in data: if element[:5] == "Exec=": result = element[5:].strip() # Save execution line without the Exec= part if result == '': return 'failed' return result except Exception: errMsg = "Can't get the exec of the file" return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def kill_appium_on_windows(appium_server): ''' Killing Appium server on windows involves killing off it's children ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: import psutil, signal for child in psutil.Process(appium_server.pid).children(recursive=True): # For eah child in process try: cpid = int(str(child.as_dict(attrs=['pid'])['pid']).replace("'", "")) # Get child PID CommonUtil.ExecLog(sModuleInfo,"Killing Appium child: %d" % cpid, 0) psutil.Process(cpid).send_signal(signal.SIGTERM) # Send kill to it #print h.terminate() except: pass except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error killing Appium and it's children")
def Swipe(x_start, y_start, x_end, y_end, duration = 1000, adb = False): ''' Perform single swipe gesture with provided start and end positions ''' # duration in mS - how long the gesture should take sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: CommonUtil.ExecLog(sModuleInfo, "Starting to swipe the screen...", 0) if adb: CommonUtil.ExecLog(sModuleInfo, "Using ADB swipe method", 0) adbOptions.swipe_android(x_start, y_start, x_end, y_end, duration, device_serial) # Use adb if specifically asked for it else: appium_driver.swipe(x_start, y_start, x_end, y_end, duration) # Use Appium to swipe by default CommonUtil.TakeScreenShot(sModuleInfo) # Capture screenshot, if settings allow for it return "passed" except Exception: errMsg = "Unable to swipe." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def read_screen_heirarchy(): ''' Read the XML string of the device's GUI and return it ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: data = appium_driver.page_source # Read screen and get xml formatted text CommonUtil.ExecLog(sModuleInfo,"Read screen heirarchy successfully",1) if data: return data else: return False except Exception: CommonUtil.ExecLog(sModuleInfo,"Read screen heirarchy unsuccessfully",3) return False
def tap_location(data_set): ''' Tap the provided position using x,y cooridnates ''' # positions: list containing x,y coordinates sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) # Parse data set try: positions = [] posX, posY = data_set[0][2].replace(' ','').split(',') positions.append((posX, posY)) # Put coordinates in a tuple inside of a list - must be this way for appium_driver.tap except Exception: errMsg = "Unable to parse data set" return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) try: appium_driver.tap(positions) # Tap the location (must be in list format) CommonUtil.ExecLog(sModuleInfo,"Tapped on location successfully", 0) return 'passed' except Exception: errMsg = "Tapped on location unsuccessfully" return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def get_window_size(read_type = False): ''' Read the device's LCD resolution / screen size ''' # Returns a dictionary of width and height sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: if read_type: return appium_driver.find_element_by_xpath("//*[not(*)]").size # Works well at reading height in full screen mode, but Appium may complain if you work outside the boundaries it has set else: return appium_driver.get_window_size() # Read the screen size as reported by the device - this is always the safe value to work within CommonUtil.ExecLog(sModuleInfo,"Read window size successfully", 0) except Exception: errMsg = "Read window size unsuccessfully" return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def iOS_Keystroke_Key_Mapping(keystroke): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) CommonUtil.ExecLog(sModuleInfo, "IOS key events not yet supported" % keystroke, 3) return 'failed' try: if keystroke == "return" or keystroke == 'enter': appium_driver.keyevent(13) elif keystroke == "go back" or keystroke == "back": appium_driver.back() elif keystroke == "space": appium_driver.keyevent(32) elif keystroke == "backspace": appium_driver.keyevent(8) elif keystroke == "call": appium_driver.keyevent(5) elif keystroke == "end call": appium_driver.keyevent(6) except Exception: errMsg = "Could not press enter for your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def set_device_password(data_set): ''' Saves the device password to shared variables for use in unlocking the phone ''' # Caveat: Only allows one password stored at a time sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) # Parse data set try: password = data_set[0][2].strip() # Read password from Value field if password != '': Shared_Resources.Set_Shared_Variables('device_password', password) CommonUtil.ExecLog(sModuleInfo, "Device password saved as: %s" % password, 1) return 'passed' else: CommonUtil.ExecLog(sModuleInfo, "Password cannot be blank. Expected Value field of action row to be a PIN or PASSWORD", 3) return 'failed' except Exception: return CommonUtil.Exception_Handler(sys.exc_info(), None, "Error when trying to read Field and Value for action")
def get_package_version(package, serial=''): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: if serial != '': serial = '-s %s' % serial # Prepare serial number with command line switch output = subprocess.check_output("adb %s shell pm dump %s" % (serial, package), shell=True) storageList = output.splitlines() # for lines in storageList: if 'versionName' in lines: # Find first instance of this, should be the version we need line1 = lines output1 = line1.split('=')[1] # Version is on right side of equals sign CommonUtil.ExecLog(sModuleInfo, "Read %s has version %s" % (package, output1), 0) return output1.strip() except Exception: errMsg = "Unable to get package version" return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def get_device_storage(serial=''): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).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) 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 get_devices(): ''' Retrieves a list of connected devices in the format of "SERIAL_NO STATE" and returns as a list ''' # State may be "device" if connected and we can talk to it, or "unauthorized" if we can't talk to it sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: # Get list of connected devices output = subprocess.check_output("adb devices", shell=True) # Cleanup data output = output.replace("\r", '') output = output.replace("\t", ' ') output = output.split("\n") output.pop(0) # Remove "list of..." string output = [line for line in output if line != ''] # Return as list CommonUtil.ExecLog(sModuleInfo, "Connected devices: %s" % str(output), 0) return output except Exception: CommonUtil.ExecLog(sModuleInfo, "Unable to get devices", 3) return []
def is_android_connected(serial=''): ''' Return True/False if at least one device is connected ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name devices = get_devices() if devices != []: if serial == '': return True # No device specified, and we have at least one for device in devices: if serial.lower() == device.lower().split(' ')[0]: CommonUtil.ExecLog(sModuleInfo, "Android connected", 0) return True CommonUtil.ExecLog(sModuleInfo, "Android connected, but either not authorized or provided serial number not found in list. Ensure USB debugging is enabled in developer options, and that you authorized this computer to connect to it.", 2) return False else: CommonUtil.ExecLog(sModuleInfo, "No Android connected", 0) return False
def get_ios_imei(UDID = ''): ''' Reads the device IMEI ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Started", 0) try: output = get_device_info(UDID) # Get device info in list format tmp = '' for line in output: if 'imei' in line.lower(): tmp = line output = tmp[1].strip() if len(output) != 14 and len(output) != 15: CommonUtil.ExecLog(sModuleInfo, "Could not read the IMEI from the device", 3) return 'failed' CommonUtil.ExecLog(sModuleInfo, "%s" % output, 0) return output except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def get_ios_version(UDID = ''): ''' Reads the device version ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).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 'failed' CommonUtil.ExecLog(sModuleInfo, "%s" % version, 0) return version except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def get_product_name(UDID=''): ''' Reads the phone name ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).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 'failed' CommonUtil.ExecLog(sModuleInfo, "%s" % product_name, 0) return product_name except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def Get_Element_Step_Data(step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: Get Element Step Data", 1) try: element_step_data = [] for each in step_data: if (each[1] == "action" or each[1] == "conditional action"): #CommonUtil.ExecLog(sModuleInfo, "Not a part of element step data", 2) continue else: element_step_data.append(each) return element_step_data except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) # Handles actions for the sequential logic, based on the input from the mentioned function
def Get_Response(step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: Get_Response", 1) try: fields_to_be_saved = '' for row in step_data: if row[1] == 'action': fields_to_be_saved = row[2] element_step_data = Get_Element_Step_Data(step_data) returned_step_data_list = Validate_Step_Data(element_step_data) if ((returned_step_data_list == []) or (returned_step_data_list == "failed")): return "failed" else: try: return_result = handle_rest_call(returned_step_data_list, fields_to_be_saved) return return_result except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def Step_Result(step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function: Step_Result", 1) try: if ((1 < len(step_data) >= 5)): CommonUtil.ExecLog(sModuleInfo,"The information in the data-set(s) are incorrect. Please provide accurate data set(s) information.",3) result = "failed" else: step_result = step_data[0][2] if step_result == 'pass': result = "passed" elif step_result == 'skip': result = 'skipped' elif step_result == 'fail': result = "failed" return result except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) # Performs a series of action or conditional logical action decisions based on user input
def Open_Browser_Wrapper(step_data): ''' Temporary wrapper for open_browser() until that function can be updated to use only data_set ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: global dependency # Get the dependency again in case it was missed if Shared_Resources.Test_Shared_Variables('dependency'): # Check if driver is already set in shared variables dependency = Shared_Resources.Get_Shared_Variables('dependency') # Retreive selenium driver cmd = step_data[0][2] # Expected "open" or "close" for current method. May contain other strings for old method of Field="open browser" if cmd.lower().strip() == 'close': # User issued close command try: selenium_driver.close() except: pass return 'passed' else: # User issued "open" command or used old method of "open browser" return Open_Browser(dependency) except Exception: ErrorMessage = "failed to open browser" return CommonUtil.Exception_Handler(sys.exc_info(), None, ErrorMessage)
def Enter_Text_In_Text_Box(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": for each in step_data: if each[1]=="action": text_value=each[2] break else: continue Element.click() Element.clear() Element.send_keys(text_value) Element.click() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully set the value of to text to: %s"%text_value, 1) return "passed" else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: errMsg = "Could not select/click your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg)
def Click_and_Hold_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: click_and_hold = ActionChains(selenium_driver).click_and_hold(Element) click_and_hold.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully clicked and held the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not click and hold your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to right click on element; step data passed on by the user
def Context_Click_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: context_click = ActionChains(selenium_driver).context_click(Element) context_click.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully right clicked the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not right click your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to double click on element; step data passed on by the user
def Double_Click_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: double_click = ActionChains(selenium_driver).double_click(Element) double_click.perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully double clicked the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not double click your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to move to middle of the element; step data passed on by the user
def Move_To_Element(step_data): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Element = LocateElement.Get_Element(step_data,selenium_driver) if Element != "failed": try: move = ActionChains(selenium_driver).move_to_element(Element).perform() CommonUtil.TakeScreenShot(sModuleInfo) CommonUtil.ExecLog(sModuleInfo, "Successfully moved to the middle of the element with given parameters and values", 1) return "passed" except Exception: element_attributes = Element.get_attribute('outerHTML') CommonUtil.ExecLog(sModuleInfo, "Element Attributes: %s"%(element_attributes),3) errMsg = "Could not move to your element your element." return CommonUtil.Exception_Handler(sys.exc_info(),None,errMsg) else: CommonUtil.ExecLog(sModuleInfo, "Unable to locate your element with given data.", 3) return "failed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to hover over element; step data passed on by the user
def Sleep(step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function start", 0) try: if ((1 < len(step_data) >= 2)): CommonUtil.ExecLog(sModuleInfo,"Please provide single row of data for only sleep. Consider using wait instead",3) return "failed" else: tuple = step_data[0] seconds = int(tuple[2]) CommonUtil.ExecLog(sModuleInfo,"Sleeping for %s seconds"%seconds,1) time.sleep(seconds) return "passed" #return result except Exception: return CommonUtil.Exception_Handler(sys.exc_info()) #Method to scroll down a page
def Navigate(step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Function start", 0) try: if ((1 < len(step_data) >= 2)): CommonUtil.ExecLog(sModuleInfo,"Please provide only single row of data",3) return "failed" else: navigate = step_data[0][2] if navigate == 'back': selenium_driver.back() CommonUtil.ExecLog(sModuleInfo, "Performing browser back", 1) elif navigate == 'forward': selenium_driver.forward() CommonUtil.ExecLog(sModuleInfo, "Performing browser forward", 1) elif navigate == 'refresh': selenium_driver.refresh() CommonUtil.ExecLog(sModuleInfo, "Performing browser refresh", 1) else: CommonUtil.ExecLog(sModuleInfo, "Value invalid. Only 'back', 'forward', 'refresh' allowed", 3) return "failed" return "passed" except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def step_result(data_set): ''' Returns passed/failed in the standard format, when the user specifies it in the step data ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: action_value = '' for row in data_set: if row[0] == 'step result' and row[1] == 'action': action_value = row[2] except: return CommonUtil.Exception_Handler(sys.exc_info()) if action_value in failed_tag_list: # Convert user specified pass/fail into standard result return 'failed' elif action_value in skipped_tag_list: return 'skipped' elif action_value in passed_tag_list: return 'passed' else: CommonUtil.ExecLog(sModuleInfo, "Step Result action has invalid VALUE", 3) return 'failed'
def step_exit(data_set): ''' Exits a Test Step wtih passed/failed in the standard format, when the user specifies it in the step data ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: action_value = '' for row in data_set: if row[0] == 'step exit' and row[1] == 'action': action_value = row[2] except: return CommonUtil.Exception_Handler(sys.exc_info()) if action_value in failed_tag_list: # Convert user specified pass/fail into standard result return 'failed' elif action_value in skipped_tag_list: return 'skipped' elif action_value in passed_tag_list: return 'passed' else: CommonUtil.ExecLog(sModuleInfo, "Step Result action has invalid VALUE", 3) return 'failed'
def append_list_shared_variable(data_set): ''' Delete all shared variables - Wrapper for Clean_Up_Shared_Variables() ''' # To delete only one, use the action "save variable", and set it to an empty string # Takes no inputs sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: # Parse data set tmp = data_set[0][2].replace(' ', '').strip() # Get key and value from Value field and clean them shared_var = tmp.split('=')[0].strip() # Get variable name tmp = tmp.replace(shared_var, '').strip().replace('=', '', 1) values = tmp.split(',') # Get values (could be several) # Append all values for value in values: result = sr.Append_List_Shared_Variables(shared_var, value.strip()) return result except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def sequential_actions_settings(data_set): ''' Test Step front end for modifying certain variables used by Sequential Actions ''' sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo,"Function Start", 0) try: # Parse data set tmp = data_set[0][2].replace(' ', '').strip() # Get key and value from Value field and clean them shared_var = tmp.split('=')[0].strip().lower() # Retrieve variable name value = tmp.replace(shared_var + '=', '').strip() # Retrieve value for variable # Verify this is a real variable (should be set somewhere else) if not sr.Test_Shared_Variables(shared_var): CommonUtil.ExecLog(sModuleInfo,"The variable name specified (%s) is not a valid Sequential Action variable" % str(shared_var), 3) return 'failed' # Save variable - all functions that use this variable will now use the new value CommonUtil.ExecLog(sModuleInfo,"Changing Sequential Action setting of %s from %s to %s" % (str(shared_var), str(sr.Get_Shared_Variables(shared_var)), str(value)), 1) return sr.Set_Shared_Variables(shared_var, value) except Exception: return CommonUtil.Exception_Handler(sys.exc_info())
def Set_List_Shared_Variables(list_name, key, value, protected = False): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name global shared_variables, protected_variables if key == '' or key == None or value == '' or value == None or list_name == '' or list_name == None: # if input is invalid return "failed" else: # Valid input if protected: protected_variables.append(key) # Add to list of protected variables else: # Check if user is trying to overwrite a protected variable if key in protected_variables: # If we find a match, exit with failure CommonUtil.ExecLog(sModuleInfo, "Error: You tried to overwrite protected variable '%s'. Please choose a different variable name." % key, 3) return 'failed' # Good to proceed if list_name in shared_variables: shared_variables[list_name][key] = value CommonUtil.ExecLog(sModuleInfo, "In List '%s' Variable value of '%s' is set as: %s" % (list_name, key, value), 0) return "passed" else: CommonUtil.ExecLog(sModuleInfo, "List named %s does not exist on shared variables, so cant insert new field to list" % list_name, 3) return "failed" except: CommonUtil.Exception_Handler(sys.exc_info())
def Get_Shared_Variables(key): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name global shared_variables if key == '' or key == None: # if input is invalid return "failed" else: if key in shared_variables: value = shared_variables[key] CommonUtil.ExecLog(sModuleInfo, "Variable value of '%s' is: %s" % (str(key), value), 0) return value else: CommonUtil.ExecLog(sModuleInfo, "No Such variable named '%s' found in shared variables" % key, 3) return "failed" except: CommonUtil.Exception_Handler(sys.exc_info())
def Get_List_from_Shared_Variables(list_name): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name global shared_variables if list_name == '' or list_name == None: # if input is invalid return "failed" else: if list_name in shared_variables: list = shared_variables[list_name] CommonUtil.ExecLog(sModuleInfo, "List: " + list_name + " is: " + str(list), 1) return list else: CommonUtil.ExecLog(sModuleInfo, "List named %s does not exist on shared variables" % list_name, 3) return "failed" except: CommonUtil.Exception_Handler(sys.exc_info())