diff options
author | nags <nags@nags-desktop.(none)> | 2009-08-12 23:50:50 -0700 |
---|---|---|
committer | nags <nags@nags-desktop.(none)> | 2009-08-12 23:50:50 -0700 |
commit | db19a8e25b911effe78630ad016a3bf44fe0b117 (patch) | |
tree | d0cd7dbfdaabf961ca0c8cb86595f753097283b4 | |
parent | 6a62fb5d0206b522616fd9126f73013299f1bc83 (diff) |
2009-08-12 Arvind Patil <apatil@vmware.com>
* ldtputils.py (activatewindow, minimizewindow, maximizewindow)
(closewindow): Added new functions based on wnck python library.
-rw-r--r-- | python/ChangeLog | 5 | ||||
-rw-r--r-- | python/ldtp.py | 6 | ||||
-rwxr-xr-x | python/ldtpcodegen | 2 | ||||
-rwxr-xr-x | python/ldtpeditor | 2 | ||||
-rw-r--r-- | python/ldtplib/ldtprecorder.py | 2 | ||||
-rw-r--r-- | python/ldtputils.py | 419 |
6 files changed, 256 insertions, 180 deletions
diff --git a/python/ChangeLog b/python/ChangeLog index fb889ba..7119457 100644 --- a/python/ChangeLog +++ b/python/ChangeLog @@ -1,3 +1,8 @@ +2009-08-12 Arvind Patil <apatil@vmware.com> + + * ldtputils.py (activatewindow, minimizewindow, maximizewindow) + (closewindow): Added new functions based on wnck python library. + 2009-08-11 Nagappan Alagappan <nagappan@gmail.com> * ldtp.py (windowuptime): Fixes bug 587614, Method to measure how diff --git a/python/ldtp.py b/python/ldtp.py index 8ea24d5..6829b06 100644 --- a/python/ldtp.py +++ b/python/ldtp.py @@ -32,7 +32,7 @@ __author__ = "Nagappan Alagappan <nagappan@gmail.com>, "\ "Veerapuram Varadhan <v.varadhan@gmail.com>, "\ "Prashanth Mohan <prashmohan@gmail.com>, Venkateswaran S <wenkat.s@gmail.com>" # __maintainer__ = "Nagappan Alagappan <nagappan@gmail.com>" -__version__ = "1.6.0" +__version__ = "1.7.0" import os import re @@ -350,9 +350,9 @@ def invokecallback (windowTitle): # Get the callback function callback = _callbackFunctions.get (_responseData [1])[0] # Check whether its callable - if (callable (callback)): + if callable(callback): # If callable then call the function - callback () + callback() else: if _ldtpDebug: print 'callback function is not callable, ignoring' diff --git a/python/ldtpcodegen b/python/ldtpcodegen index eeba2ed..162e300 100755 --- a/python/ldtpcodegen +++ b/python/ldtpcodegen @@ -29,7 +29,7 @@ __author__ = "Nagappan Alagappan <nagappan@gmail.com>" # __maintainer__ = "Nagappan Alagappan <nagappan@gmail.com>" -__version__ = "1.5.0" +__version__ = "1.7.0" import os import re diff --git a/python/ldtpeditor b/python/ldtpeditor index 5ac6c7a..181d54b 100755 --- a/python/ldtpeditor +++ b/python/ldtpeditor @@ -29,7 +29,7 @@ __author__ = "Nagappan Alagappan <nagappan@gmail.com>, Thanumalayan <madthanu@gmail.com>, Vinod Kumar <vinod.gre@gmail.com>" # __maintainer__ = "Nagappan Alagappan <nagappan@gmail.com>" -__version__ = "1.6.0" +__version__ = "1.7.0" import os import re diff --git a/python/ldtplib/ldtprecorder.py b/python/ldtplib/ldtprecorder.py index 8272517..dce4d53 100644 --- a/python/ldtplib/ldtprecorder.py +++ b/python/ldtplib/ldtprecorder.py @@ -27,7 +27,7 @@ __author__ = "Nagappan A" # __maintainer__ = "Nagappan A" -__version__ = "1.6.0" +__version__ = "1.7.0" import re import os diff --git a/python/ldtputils.py b/python/ldtputils.py index 2b66897..2a521fb 100644 --- a/python/ldtputils.py +++ b/python/ldtputils.py @@ -34,6 +34,7 @@ import sys import time import string import thread +import fnmatch import commands import tempfile import traceback @@ -45,7 +46,7 @@ os.environ ['GTK_MODULES'] = '' import ldtp -_ldtpDebug = os.getenv ('LDTP_DEBUG') +_ldtpDebug = os.getenv('LDTP_DEBUG') statGrabMsg = None try: @@ -53,59 +54,58 @@ try: except ImportError: statGrabMsg = 'pystatgrab package not installed' -def tuplelist2list (lst): +def tuplelist2list(lst): d = [] - for x in range (1, len (lst) + 1): - for y in range (1, len (lst[x-1]) + 1): - d.append (lst[x-1][y-1]) + for x in range(1, len(lst) + 1): + for y in range(1, len(lst[x-1]) + 1): + d.append(lst[x-1][y-1]) return d -def getFullPath (path): +def getFullPath(path): if path [0] == "~": - path = os.path.expanduser (path) + path = os.path.expanduser(path) elif path [0] == ".": - path = os.path.abspath (path) + path = os.path.abspath(path) return path -def imagecompare (imgfile1, imgfile2): +def imagecompare(imgfile1, imgfile2): try: import ImageChops, Image except ImportError: - ldtp.log ('Python-Imaging package not installed', 'error') - raise ldtp.LdtpExecutionError ('Python-Imaging package not installed') + ldtp.log('Python-Imaging package not installed', 'error') + raise ldtp.LdtpExecutionError('Python-Imaging package not installed') try: diffcount = 0.0 - im1 = Image.open (imgfile1) - im2 = Image.open (imgfile2) + im1 = Image.open(imgfile1) + im2 = Image.open(imgfile2) - imgcompdiff = ImageChops.difference (im1, im2) - diffboundrect = imgcompdiff.getbbox () - imgdiffcrop = imgcompdiff.crop (diffboundrect) + imgcompdiff = ImageChops.difference(im1, im2) + diffboundrect = imgcompdiff.getbbox() + imgdiffcrop = imgcompdiff.crop(diffboundrect) - seq = list (imgdiffcrop.getdata ()) - seq = tuplelist2list (seq) + seq = list(imgdiffcrop.getdata()) + seq = tuplelist2list(seq) #print seq - for i in range (0, imgdiffcrop.size[0] * imgdiffcrop.size[1] * 3, 3): + for i in range(0, imgdiffcrop.size[0] * imgdiffcrop.size[1] * 3, 3): if seq[i] != 0 or seq[i+1] != 0 or seq[i+2] != 0: diffcount = diffcount + 1.0 diffImgLen = imgcompdiff.size[0] * imgcompdiff.size[1] * 1.0 diffpercent = (diffcount * 100) / diffImgLen - ldtp.log ('length ' + str (diffImgLen)) - ldtp.log ('diffcount ' + str (diffcount)) - ldtp.log ('diff percent ' + str (diffpercent)) + ldtp.log('length ' + str(diffImgLen)) + ldtp.log('diffcount ' + str(diffcount)) + ldtp.log('diff percent ' + str(diffpercent)) return diffpercent except IOError: - ldtp.log ('Input file does not exist', 'error') - raise ldtp.LdtpExecutionError ('Input file does not exist') + ldtp.log('Input file does not exist', 'error') + raise ldtp.LdtpExecutionError('Input file does not exist') -def imagecapture (winName = None, outFile = None, width = None, +def imagecapture(winName = None, outFile = None, width = None, height = None, x = 0, y = 0): # winname == None, let us capture the entire screen # if output file name is not passed, then a random file name will be generated in # /tmp and it will be returned - global tmpFile gtkImport = False tmpFile = None try: @@ -125,151 +125,222 @@ def imagecapture (winName = None, outFile = None, width = None, if _ldtpDebug: print 'wnck python package not installed' - def getWinId(winName): - if not wnckImport: - ldtp.log ('wnck package not installed, screen capture disabled ' \ - 'based on window name', - 'warning') - return None - - screen = wnck.screen_get_default() - winid = None - for window in screen.get_windows(): - if re.search(winName, window.get_name()): - winid = window.get_xid() - # Activate the window - # http://faq.pygtk.org/index.py?req=show&file=faq10.027.htp - window.activate(gtk.get_current_event_time()) - break - return winid - - def setTmpFile(fileName): - global tmpFile - tmpFile = fileName - - def generateTmpFile(): - global tmpFile - if outFile == None: - fp = tempfile.NamedTemporaryFile () - tmpFile = fp.name + '.png' - fp.close () - else: - tmpFile = outFile - return tmpFile - - def capturescreenshot(): - winid = None - if winName: - count = 0 - while count < 3: - winid = getWinId(winName) - count += 1 - time.sleep(1) - if winid: + class ImageCapture: + def __init__(self): + self.count = 0 + self.tmpFile = None + + def getWinId(self, winName): + if not wnckImport: + ldtp.log('wnck package not installed, screen capture ' \ + 'disabled based on window name', + 'warning') + return False + + screen = wnck.screen_get_default() + winid = None + for window in screen.get_windows(): + if re.search(winName, window.get_name()): + winid = window.get_xid() + # Activate the window + # http://faq.pygtk.org/index.py?req=show&file=faq10.027.htp + window.activate(gtk.get_current_event_time()) break - pb = None - if gtkImport: - if winid is None: - # Based on http://ubuntuforums.org/showthread.php?t=448160 - window = gtk.gdk.get_default_root_window () - size = window.get_size () - pb = gtk.gdk.Pixbuf (gtk.gdk.COLORSPACE_RGB, False, 8, - width or size [0], - height or size [1]) - pb = pb.get_from_drawable (window, window.get_colormap (), - x, y, 0, 0, - width or size [0], - height or size [1]) - tmpFile = generateTmpFile() - setTmpFile(tmpFile) - if pb: - pb.save(tmpFile, "png") - # based on http://faq.pygtk.org/index.py?req=show&file=faq08.004.htp - del pb - gc.collect() - else: - if winid == None: - winid = 'root' - cmd = "import -window %s" % winid - if width and height: - cmd = "%s -crop %dx%d+%d+%d" % (cmd, width, - height, x, y) - cmd = "%s %s" % (cmd, tmpFile) - status = commands.getstatusoutput (cmd) - if status [0] != 0: - ldtp.log ('Unable to capture screenshot: %s' % status [1], 'error') - setTmpFile(None) - if gtkImport: + return winid + + def generateTmpFile(self): + if not outFile: + fp = tempfile.NamedTemporaryFile() + self.tmpFile = fp.name + '.png' + fp.close() + else: + self.tmpFile = outFile + + def capturescreenshot(self): + winid = None + if self.count > 3: + gtk.main_quit() + self.count += 1 + if winName: + winid = self.getWinId(winName) + if not winid: + return True + + pb = None + if gtkImport: + if not winid: + # Based on http://ubuntuforums.org/showthread.php?t=448160 + window = gtk.gdk.get_default_root_window() + size = window.get_size() + pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, + width or size [0], + height or size [1]) + pb = pb.get_from_drawable(window, window.get_colormap(), + x, y, 0, 0, + width or size [0], + height or size [1]) + self.generateTmpFile() + if pb: + pb.save(self.tmpFile, "png") + # based on http://faq.pygtk.org/index.py?req=show&file=faq08.004.htp + del pb + gc.collect() + else: + if winid == None: + winid = 'root' + cmd = "import -window %s" % winid + if width and height: + cmd = "%s -crop %dx%d+%d+%d" % (cmd, width, + height, x, y) + cmd = "%s %s" % (cmd, self.tmpFile) + status = commands.getstatusoutput(cmd) + if status [0] != 0: + ldtp.log('Unable to capture screenshot: %s' % status [1], 'error') + self.tmpFile = None gtk.main_quit() + + + screenshot = ImageCapture() if gtkImport: - gobject.idle_add(capturescreenshot) - gobject.idle_add(gtk.main_quit) + gobject.idle_add(screenshot.capturescreenshot) + #gobject.idle_add(gtk.main_quit) gtk.main() - return tmpFile + return screenshot.tmpFile + +def _wnckFunction(wnckFunctionName, windowName = None): + gtkImport = False + try: + import gtk.gdk + import gobject + gobject.threads_init() + gtkImport = True + except ImportError: + if _ldtpDebug: + print 'pygtk package not installed' + return False + + wnckImport = False + try: + import wnck + wnckImport = True + except ImportError: + if _ldtpDebug: + print 'wnck python package not installed' + return False + + class _wnckInternal: + def __init__(self, windowName = None): + self.count = 0 + self.windowName = windowName + + def _operateOnWindow(self, wnckFunctionName): + screen = wnck.screen_get_default() + windowList = screen.get_windows() + self.count += 1 + if not windowList: + if self.count <= 3: + return True + for w in windowList: + if windowName: + _currentWindow = w.get_name() + if re.search(fnmatch.translate(windowName), _currentWindow, re.I) or \ + re.search(fnmatch.translate(windowName), + re.sub(" *\t*\n*", "", _currentWindow), re.I): + if wnckFunctionName not in dir(w): + break + function = getattr(w, wnckFunctionName) + if wnckFunctionName == 'activate': + function(0L) + else: + function() + break + else: + if wnckFunctionName not in dir(w): + continue + function = getattr(w, wnckFunctionName) + function() + gtk.main_quit() + + _wnckInst = _wnckInternal(windowName) + gobject.idle_add(_wnckInst._operateOnWindow, wnckFunctionName) + #gobject.idle_add(gtk.main_quit) + gtk.main() + +def activatewindow(windowName = None): + _wnckFunction('activate', windowName) + +def minimizewindow(windowName = None): + _wnckFunction('minimize', windowName) + +def maximizewindow(windowName = None): + _wnckFunction('maximize', windowName) + +def closewindow(windowName): + _wnckFunction('close', windowName) -def blackoutregion (infile, outfile, topx, topy, botx, boty): +def blackoutregion(infile, outfile, topx, topy, botx, boty): try: import ImageChops, Image except ImportError: - ldtp.log ('Python-Imaging package not installed', 'error') - raise ldtp.LdtpExecutionError ('Python-Imaging package not installed') - im = Image.open (infile) + ldtp.log('Python-Imaging package not installed', 'error') + raise ldtp.LdtpExecutionError('Python-Imaging package not installed') + im = Image.open(infile) box = (topx, topy, botx, boty) - region = im.crop (box) - region = region.point (lambda i: i * 0) - im.paste (region, box) - im.save (outfile) + region = im.crop(box) + region = region.point(lambda i: i * 0) + im.paste(region, box) + im.save(outfile) # XML Data file parser class LdtpDataFileParser: - def __init__ (self, filename = None): + def __init__(self, filename = None): self.ldtpdataxml = [] if filename: try: - dom = xml.dom.minidom.parse (filename) - self.ldtpdataxml = dom.getElementsByTagName ("data") + dom = xml.dom.minidom.parse(filename) + self.ldtpdataxml = dom.getElementsByTagName("data") if self.ldtpdataxml == []: - ldtp.log ('data xml tag not present') + ldtp.log('data xml tag not present') if _ldtpDebug and _ldtpDebug == '2': print 'data xml tag not present' except xml.parsers.expat.ExpatError, msg: - ldtp.log ('XML Error: ' + str (msg), 'error') + ldtp.log('XML Error: ' + str(msg), 'error') except IOError: - ldtp.log ('XML \"' + filename + '\" file not found', 'error') - def setfilename (self, filename): + ldtp.log('XML \"' + filename + '\" file not found', 'error') + def setfilename(self, filename): self.ldtpdataxml = [] if filename: try: - dom = xml.dom.minidom.parse (filename) - self.ldtpdataxml = dom.getElementsByTagName ("data") + dom = xml.dom.minidom.parse(filename) + self.ldtpdataxml = dom.getElementsByTagName("data") if self.ldtpdataxml == []: - ldtp.log ('data xml tag not present') + ldtp.log('data xml tag not present') if _ldtpDebug and _ldtpDebug == '2': print 'data xml tag not present' except xml.parsers.expat.ExpatError, msg: if _ldtpDebug and _ldtpDebug == '2': - print 'XML Error: ' + str (msg) - ldtp.log ('XML Error: ' + str (msg), 'error') + print 'XML Error: ' + str(msg) + ldtp.log('XML Error: ' + str(msg), 'error') except IOError: if _ldtpDebug and _ldtpDebug == '2': print 'XML \"' + filename + '\" file not found' - ldtp.log ('XML \"' + filename + '\" file not found', 'error') - def getText (self, nodelist): + ldtp.log('XML \"' + filename + '\" file not found', 'error') + def getText(self, nodelist): rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc - def gettagvalue (self, tagname): + def gettagvalue(self, tagname): self.taglist = [] if self.ldtpdataxml == []: return self.taglist for dataelements in self.ldtpdataxml: - for data in dataelements.getElementsByTagName (tagname): - self.taglist.append (self.getText (data.childNodes)) + for data in dataelements.getElementsByTagName(tagname): + self.taglist.append(self.getText(data.childNodes)) return self.taglist -class pstats (threading.Thread): +class pstats(threading.Thread): """Capturing Memory and CPU Utilization statistics for an application and its related processes EXAMPLE USAGE: xstats = pstats('evolution', 2) @@ -278,104 +349,104 @@ class pstats (threading.Thread): # Stop the process statistics gathering thread by calling the stopstats method xstats.stop()""" - def __init__ (self, appname, inter = 2): + def __init__(self, appname, inter = 2): if statGrabMsg is not None: - ldtp.log (statGrabMsg, 'error') - raise ldtp.LdtpExecutionError (statGrabMsg) - threading.Thread.__init__ (self) + ldtp.log(statGrabMsg, 'error') + raise ldtp.LdtpExecutionError(statGrabMsg) + threading.Thread.__init__(self) self.processname = appname self.interval = inter self.stop_flag = 0 - def run (self): - while (self.stop_flag == 0): - for i in statgrab.sg_get_process_stats (): + def run(self): + while self.stop_flag == 0: + for i in statgrab.sg_get_process_stats(): if self.stop_flag == 1: break - result = re.search (self.processname, str(i['process_name'])) - if (result): - title = str (i['proctitle']) - proctitle = re.split ("\s", title) - procname = re.split ("\/", proctitle[0]) + result = re.search(self.processname, str(i['process_name'])) + if result: + title = str(i['proctitle']) + proctitle = re.split("\s", title) + procname = re.split("\/", proctitle[0]) # Put the stats into ldtp log file - ldtp.log (procname[-1] + ' - ' + str (i['proc_resident'] / (1024*1024)) + 'M', + ldtp.log(procname[-1] + ' - ' + str(i['proc_resident'] / (1024*1024)) + 'M', 'meminfo') - ldtp.log (procname[-1] + ' - ' + str (round(i['cpu_percent'], 2)), + ldtp.log(procname[-1] + ' - ' + str(round(i['cpu_percent'], 2)), 'cpuinfo') # Wait for interval seconds before gathering stats again - time.sleep (self.interval) + time.sleep(self.interval) - def stop (self): + def stop(self): self.stop_flag = 1 ############# Application Functions ################# -def execute (cmd): - status = commands.getstatusoutput (cmd) +def execute(cmd): + status = commands.getstatusoutput(cmd) if status[0] != 0: - ldtp.log (status[1], 'error') - raise ldtp.LdtpExecutionError (status[1]) + ldtp.log(status[1], 'error') + raise ldtp.LdtpExecutionError(status[1]) return 1 ########### LTFX Functions ############### -def getactivewin (): +def getactivewin(): #Get currently active window title name cmd = "ltfx -e 'get_active_win'" - status = commands.getstatusoutput (cmd) + status = commands.getstatusoutput(cmd) if status[0] != 0: - ldtp.log (status[1], 'error') - raise ldtp.LdtpExecutionError (status[1]) + ldtp.log(status[1], 'error') + raise ldtp.LdtpExecutionError(status[1]) return status[1] -def windowexists (window_name): +def windowexists(window_name): #Check window name exists with the given name cmd = "ltfx -e \'win_exists \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def partialexists (window_name): +def partialexists(window_name): #Check window name exists with the given partial name cmd = "ltfx -e \'win_exists_partial \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def activatewinpartialname (window_name): +def activatewinpartialname(window_name): # Set active window based on the given partial name" cmd = "ltfx -e \'activate_win_partial \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def activatewin (window_name): +def activatewin(window_name): #Set active window based on the given name cmd = "ltfx -e \'activate_win \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def activatewinid (window_id): +def activatewinid(window_id): #Set active window based on the given window-id cmd = "ltfx -e \'activate_win_id \"" + window_id + "\"\'" - return execute (cmd) + return execute(cmd) -def closewindow (window_name): +def closewindow(window_name): #Close the window with the given title return 0 -def waitwinname (window_name): +def waitwinname(window_name): #Wait for window with name to appear cmd = "ltfx -e 'wait_for_win \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def waitwinpartialname (window_name): +def waitwinpartialname(window_name): #Wait for window with partial name to appear cmd = "ltfx -e 'wait_for_win_partial \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def waitwinclose (window_name): +def waitwinclose(window_name): #Wait for window to close with the given name cmd = "ltfx -e 'wait_for_close \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def waitwinpartialclose (window_name): +def waitwinpartialclose(window_name): #Wait for window to close with the given partial name cmd = "ltfx -e 'wait_for_close_partial \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) -def typekey (window_name): +def typekey(window_name): #Type the given text in the focused window cmd = "ltfx -e 'type \"" + window_name + "\"\'" - return execute (cmd) + return execute(cmd) |