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
python类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, (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 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 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 = 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 = 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)
BuiltInFunctions_XML.py 文件源码
项目:Zeuz_Python_Node
作者: AutomationSolutionz
项目源码
文件源码
阅读 43
收藏 0
点赞 0
评论 0
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())
BuiltInFunctions_XML.py 文件源码
项目:Zeuz_Python_Node
作者: AutomationSolutionz
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
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)
BuiltInFunctions_XML.py 文件源码
项目:Zeuz_Python_Node
作者: AutomationSolutionz
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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())