dogtail-0.9.0/0000775000175000017500000000000012323471036013770 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/PKG-INFO0000664000175000017500000000072512323471036015071 0ustar vhumpavhumpa00000000000000Metadata-Version: 1.0 Name: dogtail Version: 0.9.0 Summary: GUI test tool and automation framework that uses Accessibility (a11y) technologies to communicate with desktop applications. Home-page: http://dogtail.fedorahosted.org/ Author: Zack Cerza , Ed Rousseau , David Malcolm Vitezslav Humpa Author-email: dogtail-list@gnome.org License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN dogtail-0.9.0/setup.py0000775000175000017500000000567112323467707015530 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python __author__ = "Zack Cerza " from distutils.core import setup from distutils.command.bdist_rpm import bdist_rpm def examples(): import os exList = os.listdir(os.curdir + '/examples/') result = [] for ex in exList: if ex.split('.')[-1] == 'py': result = result + ['examples/' + ex] return result def examples_data(): import os dataList = os.listdir(os.curdir + '/examples/data/') result = [] for data in dataList: result = result + ['examples/data/' + data] return result def tests(): import os exList = os.listdir(os.curdir + '/tests/') result = [] for ex in exList: if ex.split('.')[-1] == 'py': result = result + ['tests/' + ex] return result def sniff_icons(): import os list = os.listdir(os.curdir + '/sniff/icons/') result = [] for file in list: if file.split('.')[-1] in ('xpm'): result = result + ['sniff/icons/' + file] return result def icons(ext_tuple): import os list = os.listdir(os.curdir + '/icons/') result = [] for file in list: if file.split('.')[-1] in ext_tuple: result = result + ['icons/' + file] return result def scripts(): import os list = os.listdir(os.curdir + '/scripts/') result = ['sniff/sniff'] for file in list: result = result + ['scripts/' + file] return result def session_file(): result = ['scripts/gnome-dogtail-headless.session'] return result setup ( name = 'dogtail', version = '0.9.0', description = """GUI test tool and automation framework that uses Accessibility (a11y) technologies to communicate with desktop applications.""", author = """Zack Cerza , Ed Rousseau , David Malcolm Vitezslav Humpa """, author_email = 'dogtail-list@gnome.org', url = 'http://dogtail.fedorahosted.org/', packages = ['dogtail'], scripts = scripts(), data_files = [ ('share/doc/dogtail/examples', examples() ), ('share/doc/dogtail/examples/data', examples_data() ), ('share/doc/dogtail/tests', tests() ), ('share/dogtail/glade', ['sniff/sniff.ui']), ('share/dogtail/icons', sniff_icons() ), ('share/applications', ['sniff/sniff.desktop']), ('share/icons/hicolor/48x48/apps', icons('png')), ('share/icons/hicolor/scalable/apps', icons('svg')) ], cmdclass = { 'bdist_rpm': bdist_rpm } ) # vim: sw=4 ts=4 sts=4 noet ai dogtail-0.9.0/COPYING0000664000175000017500000004313311777051772015044 0ustar vhumpavhumpa00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. dogtail-0.9.0/scripts/0000775000175000017500000000000012323471036015457 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/scripts/dogtail-run-headless-next0000775000175000017500000003226412323451232022377 0ustar vhumpavhumpa00000000000000#!/usr/bin/python descr = """ Unlike the original headless script this will make use of an Display Manager (DM - currently gdm) to handle starting the X server and user session. It's motivated by changes related to systemd - that disallows running a gnome session from an environment spawned by 'su'. The original headless will not work in these cases anymore on systemd systems Instead this script uses the AutoLogin feature of the DM, so that when it starts DM's service the session will login for particular user at once. It then uses the environment properties from the new session and runs the target script inthere. Will work with distros where 'service gdm/kdm start/stop' takes an effect, and quite likely only on systemd systems that use systemd-logind service. Even if you are still able to use dogtail-run-headless in your usecase, you might consider switching to this script - as making use of DM is likely to be more reliable and less buggy compared to headless itself taking care of everything. """ drop_overview = '''from dogtail.utils import absoluteMotion, keyPress absoluteMotion(100,100) keyPress('esc')''' import argparse import sys import os import glob import subprocess import time import ConfigParser import shutil import re from dogtail.sessions import Script preserve_envs = ['PYTHONPATH', 'TEST'] def getSessionEnvironment(sessionBinary): def isSessionProcess(fileName): try: if os.path.realpath(fileName + 'exe') != ('/usr/bin/plasma-desktop' if sessionBinary.split('/')[-1] == 'startkde' else sessionBinary): return False except OSError: return False pid = fileName.split('/')[2] if pid == 'self' or pid == str(os.getpid()): return False return True def getEnvDict(fileName): try: envString = open(fileName, 'r').read() except IOError: return {} envItems = envString.split('\x00') envDict = {} for item in envItems: if not '=' in item: continue k, v = item.split('=', 1) envDict[k] = v return envDict def copyVars(envDict): '''Copy a couple of old variables we want to preserve''' for env in preserve_envs: if os.environ.has_key(env): envDict[env] = os.environ[env] return envDict envDict = False for path in glob.glob('/proc/*/'): if not isSessionProcess(path): continue envFile = path + 'environ' envDict = getEnvDict(envFile) if not envDict: raise RuntimeError("Can't find our environment!") return copyVars(envDict) def execCodeWithEnv(code, env=None): with open("/tmp/execcode.dogtail", "w") as text_file: text_file.write(code) subprocess.Popen('python /tmp/execcode.dogtail'.split(), env=(os.environ if env is None else env)).wait() class DisplayManagerSession(object): gdm_config = '/etc/gdm/custom.conf' kdm_config = '/etc/kde/kdm/kdmrc' gdm_options = {'section': 'daemon', 'enable': 'AutomaticLoginEnable', 'user': 'AutomaticLogin'} kdm_options = {'section': 'X-:0-Core', 'enable': 'AutoLoginEnable', 'user': 'AutoLoginUser'} scriptDelay = 20 user = 'test' def isProcessRunning(self, process): '''Gives true if process can be greped out of full ps dump ''' s = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE) for x in s.stdout: if re.search(process, x): return True return False def waitForProcess(self, process, invert=False): '''Waits until a process appears''' while self.isProcessRunning(process) is invert: time.sleep(1) def __init__(self, dm='gdm', session='gnome', session_binary='gnome-shell', user=None): self.session_binary = session_binary self.session = session self.accountfile = '/var/lib/AccountsService/users/%s' % self.user if user is not None: self.user = user if dm == 'gdm': self.tmp_file = '/tmp/%s' % os.path.basename(self.gdm_config) self.options = self.gdm_options self.config = self.gdm_config elif dm == 'kdm': self.tmp_file = '/tmp/%s' % os.path.basename(self.kdm_config) self.options = self.kdm_options self.config = self.kdm_config self.dm = dm def setup(self, restore=False): shutil.copy(self.config, self.tmp_file) config = ConfigParser.SafeConfigParser() config.optionxform = str config.read(self.tmp_file) if not restore: config.set(self.options['section'], self.options['enable'], 'true') config.set( self.options['section'], self.options['user'], self.user) else: config.remove_option( self.options['section'], self.options['enable']) config.remove_option(self.options['section'], self.options['user']) output = open(self.tmp_file, 'w') config.write(output) output.flush() subprocess.Popen('sudo mv -f %s %s' % (self.tmp_file, self.config), shell=True).wait() if not restore: if 'kwin' in self.session_binary: try: os.makedirs(os.getenv('HOME') + '/.kde/env/') except: pass subprocess.Popen( 'echo "export QT_ACCESSIBILITY=1" > ~/.kde/env/qt-at-spi.sh', shell=True).wait() if self.dm == 'gdm': need_restart = False tempfile = '/tmp/%s_headless' % self.user subprocess.Popen('cp -f %s %s' % (self.accountfile, tempfile), shell=True).wait() account_config = ConfigParser.SafeConfigParser() account_config.optionxform = str account_config.read(tempfile) try: saved_session = account_config.get('User', 'XSession') if self.session is None: if 'kde' in saved_session and 'gnome-shell' in self.session_binary: self.session_binary = '/usr/bin/kwin' elif 'gnome' in saved_session and 'kwin' in self.session_binary: self.session_binary = '/usr/bin/gnome-shell' elif saved_session != self.session: account_config.set('User', 'XSession', self.session) need_restart = True except ConfigParser.NoSectionError: account_config.add_section('User') account_config.set('User', 'XSession', self.session if self.session else '') account_config.set('User', 'SystemAccount', 'false') need_restart = True if need_restart: output = open(tempfile, 'w') account_config.write(output) output.flush() subprocess.Popen('sudo mv -f %s %s' % (tempfile, self.accountfile), shell=True).wait() time.sleep(1) os.system('sudo service accounts-daemon restart') time.sleep(6) # prevent a possible race condition os.system('sudo service systemd-logind restart') time.sleep(6) # these are fast, but we still need to make sure no races happen else: subprocess.Popen('sudo rm -f %s' % tempfile, shell=True).wait() elif self.dm == 'kdm': if self.session is not None: subprocess.Popen( 'echo "[Desktop]\nSession=%s" > /home/%s/.dmrc' % (self.session, self.user), shell=True).wait() def start(self, restart=False): if restart: subprocess.Popen(('sudo service %s stop' % (self.dm)).split()) time.sleep(0.5) subprocess.Popen(('sudo service %s start' % (self.dm)).split()) self.waitForProcess(self.session_binary.split('/')[-1]) # some extra time for an environment (shell/kwin) to load all resources # etc. if self.dm == 'kdm': time.sleep(10) # KDE keeps loading screen on untill all is loaded else: time.sleep(4) # GNOME shows stuff as it appears def setA11y(self, enable): subprocess.Popen('/usr/bin/gsettings set org.gnome.desktop.interface toolkit-accessibility %s' % ('true' if enable else 'false'), shell=True, env=os.environ) # if enable: # mouse is at 0x0 at the start - which brings in the overview # execCodeWithEnv(drop_overview, env = os.environ) # time.sleep(2) # time for the overview to go away def stop(self): subprocess.Popen(('sudo service %s stop' % (self.dm)).split()).wait() self.waitForProcess('/usr/bin/%s' % self.dm, invert=True) time.sleep(3) # extra safe time # did i.e. gnome-shell get stuck running? if self.isProcessRunning(self.session_binary.split('/')[-1]): print( 'dogtail-run-headless-next: WARNING: %s still running, proceeding with kill -9' % self.session_binary.split('/')[-1]) subprocess.Popen( ('sudo pkill --signal 9 %s' % (self.session_binary.split('/')[-1])).split()).wait() time.sleep(1) def parse(): parser = argparse.ArgumentParser( prog='$ dogtail-run-headless-next', description=descr, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('script', help="""Command to execute the script""") parser.add_argument('--session', required=False, help="""What session to use. Not specifying results in system default session on first login or test user's last session with follow-up logins. Otherwise you can set any xsession desktop file name here (i.e. 'gnome-classic', 'gnome', 'lxde' etc.). 'kde' defaults to 'kde-plasma for legacy reasons.'""") parser.add_argument('--session-binary', required=False, help="""Specify an in-session ever-running binary (full path) to get the environment from. Only needed for non-gnome/kde sessions.""") parser.add_argument('--dm', required=False, help="""What display manager to use for spawning session. Supported are 'gdm' (default) and 'kdm'.""") parser.add_argument('--restart', action='store_true', help="""Restart previously running display manager session before script execution.""") parser.add_argument('--dont-start', action='store_true', help="""Use already running session (doesn't have to be under Display Manager)""") parser.add_argument('--dont-kill', action='store_true', help="""Do not kill session when script exits.""") parser.add_argument('--disable-a11y', action='store_true', help="""Disable accessibility technologies on script(not session) exit.""") return parser.parse_args() def main(): args = parse() scriptCmdList = args.script.split() if args.session is None or 'gnome' in args.session: if args.session_binary is None: args.session_binary = '/usr/bin/gnome-shell' elif 'kde' in args.session: if args.session_binary is None: args.session_binary = '/usr/bin/kwin' if args.session == 'kde': args.session = 'kde-plasma' else: if args.session_binary is None: print('dogtail-run-headless-next: Need to specify a --session-binary ever-present in the session to get env from.') sys.exit(-1) if args.dm == 'gdm' or args.dm is None: dm_name = 'gdm' elif args.dm == 'kdm': dm_name = 'kdm' else: print('dogtail-run-headless-next: I do not recognize the display manager!') sys.exit(-1) print('dogtail-run-headless-next: Using display manager: %s' % dm_name) dm = DisplayManagerSession(dm_name, args.session, args.session_binary) if args.dont_start is not True: dm.setup() dm.start(restart=args.restart) print('dogtail-run-headless-next: Using %s to bind to the session' % dm.session_binary) try: os.environ = getSessionEnvironment(dm.session_binary) except: print( 'dogtail-run-headless-next: Could not get the environment from %s process' % dm.session_binary) dm.stop() dm.setup(restore=True) sys.exit(1) if dm_name == 'gdm': dm.setA11y(True) script = Script(scriptCmdList) scriptPid = script.start() print('dogtail-run-headless-next: Started the script with PID %d' % scriptPid) exitCode = script.wait() print('dogtail-run-headless-next: The script has finnished with return code %d' % exitCode) if args.disable_a11y is True: dm.setA11y(False) if args.dont_kill is False: dm.stop() dm.setup(restore=True) sys.exit(exitCode) if __name__ == "__main__": main() dogtail-0.9.0/scripts/dogtail-run-headless0000775000175000017500000000517612323451232021425 0ustar vhumpavhumpa00000000000000#!/usr/bin/python """ dogtail-run-headless This script runs a session within an X server, allowing dogtail scripts to be run on systems with no graphic cards, among other things. Scripts are run in the current directory. After they are finished, dogtail can optionally log out of the session, which will also termninate the X server. """ import optparse from dogtail import sessions import sys import os.path def findXServers(path="/usr/bin"): l = [os.path.join(path, f) for f in os.listdir(path) if f[0] == 'X'] s = set(os.path.realpath(p) for p in l) return list(s) def parse(): yesno = ('y', 'n') sessions = ("GNOME", "KDE") usage = "usage: %prog: [options] {script [args]}" parser = optparse.OptionParser(usage=usage) parser.add_option("-s", "--session", type="choice", dest="session", choices=sessions, help="which session to use") parser.add_option("-x", "--x-server", type="choice", dest="xserver", choices=findXServers(), help="which X server to use") parser.add_option("-l", "--logout", type="choice", dest="logout", choices=yesno, help="attempt to log out of the session gracefully after" + "script completion") parser.add_option("-t", "--terminate", type="choice", dest="terminate", choices=yesno, help="after script completion, and after any attempt to log" + "out, terminate the session") parser.set_defaults(session=sessions[0], logout='y', terminate='y') options, args = parser.parse_args() if not args: parser.print_usage() sys.exit(1) return options, args def main(): options, args = parse() if 'XDG_RUNTIME_DIR' in os.environ: del os.environ['XDG_RUNTIME_DIR'] if options.session == "GNOME": session = sessions.Session(sessionBinary='/usr/bin/gnome-session', scriptCmdList=args, scriptDelay=10) if options.session == "KDE": session = sessions.Session(sessionBinary='/usr/bin/startkde', scriptCmdList=args, scriptDelay=25) if options.xserver: session.xserver.server = options.xserver pid = session.start() scriptExitCode = session.script.exitCode if options.logout == 'y': session.attemptLogout() if options.terminate == 'y': session.stop() else: session.wait() sys.exit(scriptExitCode) if __name__ == "__main__": main() dogtail-0.9.0/scripts/dogtail-detect-session0000775000175000017500000000314112323451232021752 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python """ dogtail-detect session This script checks for some main pieces of a running GNOME session, specifically gnome-panel and metacity. It checks to see that the gnome-panel node has at least some child nodes. For example, the main gnome-panel node by default has two direct descendents: the top panel, and the bottom panel. Metacity's existence is also checked. However, metacity currently never has any child nodes. If a proper session is running, the scripts exits with a status of 0. If no session is found, a non-zero exit code is returned. Author: Zack Cerza """ __author__ = "Zack Cerza " from dogtail.procedural import * import sys def GNOME(): """ "Is an accessibility-enabled GNOME session running?" """ running = False try: assert focus.desktop assert focus.desktop.children focus.application('gnome-panel') assert focus.application.children focus.application('metacity') print focus.application.node assert focus.application.node running = True print "GNOME Session detected." except AttributeError or AssertionError or FocusError: print "ERROR: No session found." return running def KDE(): """ "Is an accessibility-enabled KDE session running?" """ running = False return running def JustSomeApps(): """ "Is at least one accessibility-enabled application running?" """ assert focus.desktop assert focus.desktop.children if GNOME() or KDE() or JustSomeApps(): sys.exit() else: sys.exit(1) dogtail-0.9.0/scripts/dogtail-logout0000775000175000017500000000244312323451232020336 0ustar vhumpavhumpa00000000000000#!/usr/bin/python # Logs out the full gnome session. Be sure to have your documents saved, as running # may cause loosing the changes, or it may halt the logout process. from dogtail.tree import * from dogtail.rawinput import pressKey from time import sleep import getpass # A gnome-shell object shell = root.application('gnome-shell') # Click onto a super menu label that we find under the g-s top panel object. # We need these indexes as g-s a11y support is a wee bit messy. shell[0][1][2].child(getpass.getuser(), roleName='label').click() # We can child this all the way down from the app as there's no other Log # Out... label shell.child('Log Out...', roleName='label').click() # This takes care of the 60 second dialog. # Sometimes a dialog warning about unsaved work in gedit etc. pops out, but that has the same # push button in which case this will take care of that dialog. If another dialog pops-out # in the affected application however, that might put the logout process on hold again. Unfortunatelly # we cannot do anything about that with dotail at that point as a11y registry got disabled already # by the logout process. shell[0][1].child(roleName='dialog', recursive=False).child( 'Log Out', roleName='push button').click() # Give the session some time to end before we kill it. sleep(10) dogtail-0.9.0/dogtail.spec0000664000175000017500000001617612323470401016275 0ustar vhumpavhumpa00000000000000Summary: GUI test tool and automation framework Name: dogtail Version: 0.9.0 Release: 1%{?dist} License: GPLv2 URL: http://dogtail.fedorahosted.org/ Source0: http://fedorahosted.org/released/dogtail/%{name}-%{version}.tar.gz BuildArch: noarch BuildRequires: python2-devel BuildRequires: desktop-file-utils Requires: pyatspi Requires: pygobject3 Requires: pycairo Requires: rpm-python Requires: xorg-x11-xinit Requires: python-imaging %description GUI test tool and automation framework that uses assistive technologies to communicate with desktop applications. %prep %setup -q -n %{name}-%{version} %build python ./setup.py build %install python ./setup.py install -O2 --root=$RPM_BUILD_ROOT --record=%{name}.files rm -rf $RPM_BUILD_ROOT/%{_docdir}/dogtail rm -f $RPM_BUILD_ROOT/%{python_sitelib}/%{name}-%{version}-py%{python_version}.egg-info find examples -type f -exec chmod 0644 \{\} \; desktop-file-install $RPM_BUILD_ROOT/%{_datadir}/applications/sniff.desktop \ --dir=$RPM_BUILD_ROOT/%{_datadir}/applications \ %post /bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null || : %postun if [ $1 -eq 0 ] ; then /bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null /usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || : fi %posttrans /usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || : %files %{_bindir}/* %{python_sitelib}/dogtail/ %{_datadir}/applications/* %{_datadir}/dogtail/ %{_datadir}/icons/hicolor/* %doc COPYING %doc README %doc NEWS %doc examples/ %changelog * Wed Apr 16 2014 Vitezslav Humpa - 0.9.0-1 - Update to upstream version 0.9.0 * Tue Jul 9 2013 Vitezslav Humpa - 0.8.2-1 - Update to upstream version 0.8.2 * Sat Feb 23 2013 Rahul Sundaram - 0.8.1-5 - drop unversioned obsolete * Sat Feb 23 2013 Rahul Sundaram - 0.8.1-4 - remove vendor tag from desktop file. https://fedorahosted.org/fpc/ticket/247 - clean up spec to follow current guidelines * Wed Feb 13 2013 Fedora Release Engineering - 0.8.1-3 - Rebuilt for https://fedoraproject.org/wiki/Fedora_19_Mass_Rebuild * Wed Jul 18 2012 Fedora Release Engineering - 0.8.0-3 - Rebuilt for https://fedoraproject.org/wiki/Fedora_18_Mass_Rebuild * Mon Jun 04 2012 Jaroslav Reznik - 0.8.0-2 - respin * Thu May 31 2012 Jaroslav Reznik - 0.8.0-1 - Update to 0.8.0 Final - New upstream release * Mon Apr 16 2012 Jaroslav Reznik - 0.8.0-0.5.beta5 - Update to 0.8.0 beta 5 * Mon Apr 02 2012 Jaroslav Reznik - 0.8.0-0.2.beta2 - Update to 0.8.0 beta 2 * Mon Mar 19 2012 Jaroslav Reznik - 0.8.0-0.1.beta1 - Update to 0.8.0 beta 1 * Fri Jan 13 2012 Fedora Release Engineering - 0.7.0-4 - Rebuilt for https://fedoraproject.org/wiki/Fedora_17_Mass_Rebuild * Tue Feb 08 2011 Fedora Release Engineering - 0.7.0-3 - Rebuilt for https://fedoraproject.org/wiki/Fedora_15_Mass_Rebuild * Wed Jul 21 2010 David Malcolm - 0.7.0-2 - Rebuilt for https://fedoraproject.org/wiki/Features/Python_2.7/MassRebuild * Thu Oct 08 2009 Zack Cerza - 0.7.0-1 - New upstream release. - Drop Requires on xorg-x11-server-Xvfb. - Update URL and Source0. - Ship NEWS file. * Fri Jul 24 2009 Fedora Release Engineering - 0.6.90-4.401 - Rebuilt for https://fedoraproject.org/wiki/Fedora_12_Mass_Rebuild * Tue Feb 24 2009 Fedora Release Engineering - 0.6.90-3.401 - Rebuilt for https://fedoraproject.org/wiki/Fedora_11_Mass_Rebuild * Sat Nov 29 2008 Ignacio Vazquez-Abrams - 0.6.90-2.401 - Rebuild for Python 2.6 * Tue Aug 12 2008 Zack Cerza - 0.6.90-1.401 - New upstream snapshot. - Require python-imaging * Tue Aug 12 2008 Zack Cerza - 0.6.90-1.381.2 - Really fix license tag. * Wed Jul 16 2008 Tom "spot" Callaway - 0.6.90-1.381.1 - fix license tag * Thu Jan 31 2008 Zack Cerza - 0.6.90-1.381 - New upstream snapshot. - Obsolete pyspi; Require at-spi-python. - Require pygtk2-libglade. - Don't ship the .egg-info file. * Wed Jan 3 2007 Zack Cerza - 0.6.1-1 - New upstream release. * Thu Dec 7 2006 Jeremy Katz - 0.6.0-2 - build for python 2.5 - BR python-devel * Wed Sep 13 2006 Zack Cerza - 0.6.0-1 - New upstream release. - Add Requires for xorg-x11-xinit. - Add Requires for gnome-python2-gconf. - Bump pyspi Requires. - Remove upstreamed patches. * Fri Aug 18 2006 Zack Cerza - 0.5.2-3 - Add Requires for xorg-x11-xinit. Closes: #203189. * Fri Aug 11 2006 Zack Cerza - 0.5.2-2 - Added headless-gconf.patch to use the python gconf bindings. - Added desktop-file-categories.patch to put sniff and dogtail-recorder under the 'Programming' menu. * Tue Aug 01 2006 Zack Cerza - 0.5.2-1 - New upstream release. - Update Requires from Xvfb to xorg-x11-server-Xvfb. - Bump pyspi Requires. - Remove ImageMagick Requires. - Escape post-macro in changelog-macro. * Mon Apr 17 2006 Zack Cerza - 0.5.1-3 - Fix the URL field. * Tue Mar 21 2006 Zack Cerza - 0.5.1-2 - Fix URL and Source0 fields. - Fix desktop-file-utils magic; use desktop-file-install. * Fri Feb 24 2006 Zack Cerza - 0.5.1-1 - Remove BuildRequires on at-spi-devel. Added one on python. - Use macros instead of absolute paths. - Touch _datadir/icons/hicolor/ before running gtk-update-icon-cache. - Require and use desktop-file-utils. - postun = post. - Shorten BuildArchitectures to BuildArch. The former worked, but even vim's hilighting hated it. - Put each *Requires on a separate line. - Remove __os_install_post definition. - Use Fedora Extras BuildRoot. - Instead of _libdir, which kills the build if it's /usr/lib64, use a python macro to define python_sitelib and use that. - Remove the executable bit on the examples in install scriptlet. - Remove call to /bin/rm in post scriptlet. - Use dist in Release. * Fri Feb 17 2006 Zack Cerza - 0.5.0-2 - It looks like xorg-x11-Xvfb changed names. Require 'Xvfb' instead. - Remove Requires on python-elementtree, since RHEL4 didn't have it. The functionality it provides is probably never used anyway, and will most likely be removed in the future. - Don't run gtk-update-icon-cache if it doesn't exist. * Fri Feb 3 2006 Zack Cerza - 0.5.0-1 - New upstream release. - Added missing BuildRequires on at-spi-devel. - Added Requires on pyspi >= 0.5.3. - Added Requires on rpm-python, pygtk2, ImageMagick, xorg-x11-Xvfb, python-elementtree. - Moved documentation (including examples) to the correct place. - Make sure /usr/share/doc/dogtail is removed. - Added 'gtk-update-icon-cache' to %%post. * Mon Oct 24 2005 Zack Cerza - 0.4.3-1 - New upstream release. * Sat Oct 8 2005 Jeremy Katz - 0.4.2-1 - Initial build. dogtail-0.9.0/icons/0000775000175000017500000000000012323471036015103 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/icons/dogtail-head.svg0000664000175000017500000015415411777051773020176 0ustar vhumpavhumpa00000000000000 image/svg+xml Máirín Duffy Red Hat, Inc. dogtail head dogtail-0.9.0/icons/dogtail-tail-48.png0000664000175000017500000000463611777051773020443 0ustar vhumpavhumpa00000000000000PNG  IHDR00WbKGD pHYs  tIME  mƘ +IDAThՙmll/`C!& 4 S[RPHJDJQ|i+CCHi`JhZw{{7Y[!؏4՞4>f zE_ H`Of4SFL 6϶*m8͍p!ϊ{̸Otr\t|lƤ cLi23AdaPRNuf91`3hNN?Yp~r)ƛ(/Pd ޅRF0EX2IDpzf?Tq%(;P(#IXSbPB>5ۅLDDwz(W(/y#A"v+j>r}Rf˃i?0a' p+ 9zPU5iߑurۊeY&''uد?(Pb\pB:nw.Hd|w$=_]]]#hZ", =r$=kZe1|8=ϑ׸\.(0|~> LG")mLЭ.8^Q^-lt:mC4LbZOO|%]ex~mhG*r2ƆL Onll|>ݍkךv]|@ UQ*++f.į^zŋΝ;wvvv,YEQdhs XKKb2]v-?66wwwBimm_t:'&&ZlҥK-p8H$RJ_ovuuE@ƍsȲ1|[U>sP(5M{xݺut:MO:5J0Ǝӳg.X,={p>~6WWWK?G'''W)r1v4~… oÇ=k׮}Dbw:n+) EE[ <[ [yp%kjj,~?dw8M۷oX" ~A}||\K&† 8jNzs^ӹ>ZZ/ٳS=|>mjjNi/))yhŊr]]Xii)3,tO~Ɗ=/a|UUU^c~y^vСիW!n)))yj:!- |'NL&t:惇'Oxp)?)EwW\B\rUӴl}ׯpӦM0Ƹ`0ai)RUR;:!~^ZZZ 't?b-[ V dӓOpɲ쫯u=?00ࣔn,@-!8_J_Geee R*Q4"_)INgiz<7>H{Oy8!|$`/Yw8s>ףh.c8Fi-$Il63Fbqr#z M\.8cs!ñy1FE!Bqvid.,{$I$˲L&O)pw5fk%˺@!TE"OuNBOIENDB`dogtail-0.9.0/icons/dogtail-tail.svg0000664000175000017500000007232011777051773020220 0ustar vhumpavhumpa00000000000000 image/svg+xml Máirín Duffy Red Hat, Inc. dogtail tail dogtail-0.9.0/icons/dogtail-head-48.png0000664000175000017500000000530711777051773020407 0ustar vhumpavhumpa00000000000000PNG  IHDR00WbKGD pHYs  tIME !D TIDAThZklfc{mjc5O0 $`PTQhHԊJ$R@SERѦ J*h*4A X&FNl2fg;h+ =ѽ{ν9 bg> ?l?A:PL0y[#(w`aM|}I mǂ',DO $o+9p,, 7j1a8xxWkz⇑2`oRbZ_{ۅj b S47UU:߇Eu , ,//ܩro5mڴ*Mӄx8ޓ(˲+W\Q]]]]{e?###~.\h9}/UU3gaڵk\WW;)4555tvv* ,ihhhPXXdhhJrϸ!Dp\TUv( xd2{II[4/Sg@G}ʒ%K' U!nUU+r$ /^#MTU'S BȴYf|e=N/bYEE'Lĉ͗.]:`^BE$=  !eX~?af(E*kTSpB8a[??$If̘QVZZj/**2ɤ駟%yCCVZA&M4MPJY'hV(RYnm݁l}СC-j###ܹs' X+Q(D)==6^pEEEQOOo@3gD?JJJiiⷝNr (dY0FQ(p8P(tC BvZbtt R)0[(`Y/W~A^{mݻ]y<`Y}}}FHӈ㨮ƶmq F$l6.]˗cƌu---8eY#/^| @󝶘Z/flI]DBݳgS^6M4Bct D4H$+W4>igYyG٬oid2wwwO=Ԁ=`ݾ\1cx~QWW繫>eYHOW_}mmm6 5YVX!rv=z4yH0r\dY7jNAOz /6MӜ$p9e˖Xyyl0AI^߷o_Du&c>$I0m۪.;n=@wwwRe-h]]]ʁ͛7G:x`9VE8[xl5Q%i9˲8 )dM nWIENDB`dogtail-0.9.0/MANIFEST.in0000664000175000017500000000047612205607614015537 0ustar vhumpavhumpa00000000000000include COPYING include MANIFEST.in include Makefile include HACKING include INSTALL include NEWS include dogtail.spec recursive-include docs * recursive-include scripts * include sniff/sniff.glade sniff/sniff.desktop sniff/icons/*.xpm recursive-include examples *.py *.txt *.png *.cfg include icons/*.svg icons/*.png dogtail-0.9.0/README0000664000175000017500000000331312205607614014652 0ustar vhumpavhumpa00000000000000dogtail is a GUI test tool and automation framework written in Python. It uses Accessibility (a11y) technologies to communicate with desktop applications. dogtail scripts are written in Python and executed like any other Python program. News ==== See NEWS file. Installation ============ See INSTALL file. Dependencies ============ Python bindings for your distribution, e.g. python-apt or rpm-python PyGObject and GNOME-Python Applications to test, e.g. from the GNOME desktop: http://gnome.org/ Xvfb and xinit: http://xorg.freedesktop.org/ Using ===== Currently GNOME and GTK+ applications are supported. Thanks to qt-at-spi KDE4 and QT applications are now available too. First, enable accessibility support in your GNOME session with: gsettings set org.gnome.desktop.interface toolkit-accessibility true This only affects newly-started applications, so you may want to log out and log back in again. Then, look at some of the example scripts. Run them, tweak them, write your own. I suggest starting with gedit-test-utf8-procedural-api.py, as it's updated the most often. If you are using KDE instead, install the 'qt-at-spi' QT plugin and make sure you QT_ACCESSIBILITY set to 1 throughout your environment (you can put 'export QT_ACCESSIBILITY=1' to your profile file). QT accessibility should be stable from QT 4.8.3 onward. Bugs ==== Please report any bugs at: https://fedorahosted.org/dogtail/newticket Contact ======= Website: http://dogtail.fedorahosted.org/ API Documentation: http://fedorapeople.org/~vhumpa/dogtail/epydoc/ IRC: #dogtail on irc.freenode.net Mailing list for users: dogtail-list@gnome.org Mailing list for developers: dogtail-devel-list@gnome.org dogtail-0.9.0/examples/0000775000175000017500000000000012323471036015606 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/examples/gedit-test-utf8-procedural-api.py0000775000175000017500000000730212205607614024031 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # Dogtail demo script from dogtail.config import config #config.debugSleep = True #config.debugSearching = True #config.debugTranslation = True import dogtail.tc from dogtail.procedural import * from dogtail.utils import screenshot from dogtail.predicate import GenericPredicate # These next two lines get us translations for free. To see the script run # translated, run it like this: # LANG=ja_JP.UTF-8 ./gedit-test-utf8-procedural-api.py # You might also want to set config.debugTranslation and # config.debugSearching to True, just for fun. #import dogtail.i18n #dogtail.i18n.loadTranslationsFromPackageMoFiles('gedit') from os import environ, path, remove # Load our persistent Dogtail objects TestString = dogtail.tc.TCString() # Remove the output file, if it's still there from a previous run if path.isfile(path.join(path.expandvars("$HOME"), "Desktop", "UTF8demo.txt")): remove(path.join(path.expandvars("$HOME"), "Desktop", "UTF8demo.txt")) # Start gedit. run('gedit') # Set focus on gedit focus.application('gedit') # Focus gedit's text buffer. focus.text() # Load the UTF-8 demo file. Use codecs.open() instead of open(). from codecs import open from sys import path utfdemo = open(path[0] + '/data/UTF-8-demo.txt') # Load the UTF-8 demo file into the text buffer. focus.widget.text = utfdemo.read() # Take a screenshot of the window #screenshot() # Click gedit's Save button. click.button('Save') # Focus gedit's Save As... dialog try: focus.widget.findByPredicate(GenericPredicate(roleName='file chooser')) except FocusError: try: # This string changed somewhere around gedit 2.13.2. # This is the new string focus.dialog(u'Save As\u2026') except FocusError: # Fall back to the old string. focus.dialog('Save as...') # Click the Desktop widget click('Desktop', roleName = 'table cell') # Focus on dialog again try: focus.widget.findByPredicate(GenericPredicate(roleName='file chooser')) except FocusError: try: # This string changed somewhere around gedit 2.13.2. # This is the new string focus.dialog(u'Save As\u2026') except FocusError: # Fall back to the old string. focus.dialog('Save as...') # We want to save to the file name 'UTF8demo.txt'. focus.text() focus.widget.text = 'UTF8demo.txt' # And focus on dialog again try: focus.widget.findByPredicate(GenericPredicate(roleName='file chooser')) except FocusError: try: # This string changed somewhere around gedit 2.13.2. # This is the new string focus.dialog(u'Save As\u2026') except FocusError: # Fall back to the old string. focus.dialog('Save as...') # Click the Save button. click('Save') # Let's quit now. click('File') click('Quit') # We have driven gedit now lets check to see if the saved file is the same as # the baseline file # Read in the "gold" file import codecs try: # When reading the file, we have to make sure and tell codecs.open() which # encoding we're using, otherwise python gets confused later. gold = open(path[0] + '/data/UTF-8-demo.txt', encoding='utf-8').readlines() except IOError: print "File open failed" # Read the test file for comparison filepath = environ['HOME'] + '/Desktop/UTF8demo.txt' # When reading the file, we have to make sure and tell codecs.open() which # encoding we're using, otherwise python gets confused later. testfile = open(filepath, encoding='utf-8').readlines() # We now have the original and saved files as lists. Let's compare them line # by line to see if they are the same i = 0 for baseline in gold: label = "line test " + str(i + 1) TestString.compare(label, baseline, testfile[i], encoding='utf-8') i = i + 1 dogtail-0.9.0/examples/gedit-test-utf8-tree-api.py0000775000175000017500000000404312205607614022627 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # Dogtail demo script using tree.py # FIXME: Use TC. __author__ = 'Zack Cerza %s'%(name, content, name) def generateUnhelpfulHelp(appName): try: app = root.application(appName) except SearchError: run(appName) print '' print '' print '
' taggedAppName = '%s'%cgi.escape(appName) # Artile info: print '\t' writePCDataElement("title", "The Totally Definitive No-Nonsense Unhelpful Complete Guide to %s for Mannequins in 40 Days - Unleashed!"%taggedAppName) print '\t' # Guts of the article: print '\t' writePCDataElement("title", "Introduction") writePCDataElement("caution", "Do not take these instructions seriously. They are a parody of unhelpful help files found on many computer systems, and were autogenerated by no-help-at-all") writePCDataElement("para", "You can start %s by opening a terminal and typing the %s command."%(taggedAppName, cgi.escape(appName))) print '\t' menus = app.findChildren(predicate.GenericPredicate(roleName="menu")) for menu in menus: print '\t' writePCDataElement("title", "The %s menu"%cgi.escape(menu.name)) writePCDataElement("para", "Use the %s menu to work with %ss"%(cgi.escape(menu.name), cgi.escape(menu.name.lower()))) items = menu.findChildren(predicate.GenericPredicate(roleName="menu item"), recursive=False) if items!=None: for item in items: verb = unicode(item.name, 'UTF-8') noun = unicode(menu.name, 'UTF-8') print '\t\t' writePCDataElement("title", "%sing a %s"%(cgi.escape(verb.title()), cgi.escape(noun.lower()))) writePCDataElement("para", "To %s a %s, choose %s > %s"%(cgi.escape(verb.lower()), cgi.escape(noun.lower()), cgi.escape(menu.name), cgi.escape(item.name))) print '\t\t' print '\t' print '
' if __name__=='__main__': try: generateUnhelpfulHelp(sys.argv[1]) except IndexError: print "####################################" print "please supply an application name on the cmdline" print "####################################" dogtail-0.9.0/examples/data/0000775000175000017500000000000012323471036016517 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/examples/data/10w.png0000664000175000017500000000023712024120503017622 0ustar vhumpavhumpa00000000000000PNG  IHDR PX pHYs  tIME !tEXtCommentCreated with The GIMPd%nIDATc?nĀTi9IENDB`dogtail-0.9.0/examples/data/20w.png0000664000175000017500000000025012024120503017616 0ustar vhumpavhumpa00000000000000PNG  IHDRZ pHYs  tIME  ,lHtEXtCommentCreated with The GIMPd%nIDAT8c?0yTQ͔k%!h[IENDB`dogtail-0.9.0/examples/data/10b.png0000664000175000017500000000022712024120503017574 0ustar vhumpavhumpa00000000000000PNG  IHDR PX pHYs  tIME !̑tEXtCommentCreated with The GIMPd%n IDATc`6ՍIENDB`dogtail-0.9.0/examples/data/UTF-8-demo.txt0000664000175000017500000003212611777051772021026 0ustar vhumpavhumpa00000000000000UTF-8 encoded sample plain-text file ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ Markus Kuhn [ˈmaʳkʊs kuːn] — 1999-08-20 The ASCII compatible UTF-8 encoding of ISO 10646 and Unicode plain-text files is defined in RFC 2279 and in ISO 10646-1 Annex R. Using Unicode/UTF-8, you can write in emails and source code things such as Mathematics and Sciences: ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (A ⇔ B), 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm Linguistics and dictionaries: ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] APL: ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ Nicer typography in plain text files: ╔══════════════════════════════════════════╗ ║ ║ ║ • ‘single’ and “double” quotes ║ ║ ║ ║ • Curly apostrophes: “We’ve been here” ║ ║ ║ ║ • Latin-1 apostrophe and accents: '´` ║ ║ ║ ║ • ‚deutsche‘ „Anführungszeichen“ ║ ║ ║ ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ ║ ║ ║ • ASCII safety test: 1lI|, 0OD, 8B ║ ║ ╭─────────╮ ║ ║ • the euro symbol: │ 14.95 € │ ║ ║ ╰─────────╯ ║ ╚══════════════════════════════════════════╝ Greek (in Polytonic): The Greek anthem: Σὲ γνωρίζω ἀπὸ τὴν κόψη τοῦ σπαθιοῦ τὴν τρομερή, σὲ γνωρίζω ἀπὸ τὴν ὄψη ποὺ μὲ βία μετράει τὴ γῆ. ᾿Απ᾿ τὰ κόκκαλα βγαλμένη τῶν ῾Ελλήνων τὰ ἱερά καὶ σὰν πρῶτα ἀνδρειωμένη χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! From a speech of Demosthenes in the 4th century BC: Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. Δημοσθένους, Γ´ ᾿Ολυνθιακὸς Georgian: From a Unicode conference invitation: გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. Russian: From a Unicode conference invitation: Зарегистрируйтесь сейчас на Десятую Международную Конференцию по Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. Конференция соберет широкий круг экспертов по вопросам глобального Интернета и Unicode, локализации и интернационализации, воплощению и применению Unicode в различных операционных системах и программных приложениях, шрифтах, верстке и многоязычных компьютерных системах. Thai (UCS Level 2): Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese classic 'San Gua'): [----------------------------|------------------------] ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ (The above is a two-column text. If combining characters are handled correctly, the lines of the second column should be aligned with the | character above.) Ethiopian: Proverbs in the Amharic language: ሰማይ አይታረስ ንጉሥ አይከሰስ። ብላ ካለኝ እንደአባቴ በቆመጠኝ። ጌጥ ያለቤቱ ቁምጥና ነው። ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። የአፍ ወለምታ በቅቤ አይታሽም። አይጥ በበላ ዳዋ ተመታ። ሲተረጉሙ ይደረግሙ። ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። ድር ቢያብር አንበሳ ያስር። ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። ሥራ ከመፍታት ልጄን ላፋታት። ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። ተንጋሎ ቢተፉ ተመልሶ ባፉ። ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። እግርህን በፍራሽህ ልክ ዘርጋ። Runes: ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ (Old English, which transcribed into Latin reads 'He cwaeth that he bude thaem lande northweardum with tha Westsae.' and means 'He said that he lived in the northern land near the Western Sea.') Braille: ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ (The first couple of paragraphs of "A Christmas Carol" by Dickens) Compact font selection example text: ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა Greetings in various languages: Hello world, Καλημέρα κόσμε, コンニチハ Box drawing alignment tests: █ ▉ ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ dogtail-0.9.0/examples/data/sample.cfg0000664000175000017500000000020011777051772020466 0ustar vhumpavhumpa00000000000000logDir = '../scratch/logs/' scratchDir = '../scratch/' dataDir = '../scripts/pound' encoding = utf-8 scriptname = config-loaded dogtail-0.9.0/examples/data/20b.png0000664000175000017500000000023412024120503017573 0ustar vhumpavhumpa00000000000000PNG  IHDRZ pHYs  tIME  5itEXtCommentCreated with The GIMPd%nIDAT8c`` p:IENDB`dogtail-0.9.0/examples/appstartup.py0000775000175000017500000000132612205117332020363 0ustar vhumpavhumpa00000000000000#!/usr/bin/python import os import signal import sys from dogtail.config import config config.logDebugToFile = False from dogtail.procedural import * from dogtail.tc import TCNode, TCBool tcn = TCNode() def appStartup(binary, roleName = "menu item"): """Launches the given binary, then checks to see that the application started correctly by looking for a Node with the given roleName.""" pid = run(binary) tcn.compare("app exists", None, focus.application.node) focus.widget.node = focus.app.node.child(roleName=roleName) tcn.compare("app has a %s" % roleName, None, focus.widget.node) os.kill(pid, signal.SIGTERM) if __name__ == "__main__": binary = sys.argv[1] appStartup(binary) dogtail-0.9.0/examples/i18n-test.py0000775000175000017500000000167612057144014017726 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # Dogtail demo script __author__ = 'David Malcolm ' # i18n tests from dogtail.tree import root import dogtail.i18n import dogtail.distro def translateAllStrings(appName): """ Test of the translation functions. Take all user-visible strings in an app that's running in the default locale and try translating them all into the locale that this script is running in. """ for string in root.application(appName).getUserVisibleStrings(): print "User-visible string: %s"%string print "Translation is:%s"%dogtail.i18n.translate(string) print "Package dependencies: %s"%dogtail.distro.packageDb.getDependencies('evolution') #print dogtail.i18n.getMoFilesForPackage('evolution', True) print "Translation domains: %s"%dogtail.i18n.getTranslationDomainsForPackage('evolution', True) #dogtail.i18n.loadTranslationsFromPackageMoFiles('evolution') #translateAllStrings('evolution') dogtail-0.9.0/examples/filechooser-stress-test.py0000775000175000017500000000110212205607614022757 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # Stress test: repeatedly open and close the filechooser dialog from dogtail.tree import * from dogtail.utils import run from sys import exit run('gedit') gedit = root.application('gedit') while True: try: gedit.child('Open').click() except SearchError: #toolbar not present? gedit.child('Open...').click() try: filechooser = gedit.child(name='Open Files', roleName='file chooser') filechooser.childNamed('Cancel').click() except SearchError: print('File chooser did not open') exit(1) dogtail-0.9.0/examples/test-events.py0000775000175000017500000000526112205117332020443 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # Dogtail demo script # Note that this script is outdated and may cause your session to lock up until # it is killed. It will most likely be deleted in the next release. __author__ = 'David Malcolm ' import dogtail.tree import pyatspi import Accessibility # Test of event callbacks # Under construction def callback(event): source = event.source if isinstance(source, Accessibility.Accessible): sourceStr = " source:%s"% str(source) else: sourceStr = "" print "Got event: %s%s"%(event.type, sourceStr) #listener = atspi.EventListener(callback, ["window:create"]) #listener = atspi.EventListener(callback, ["focus:", "object:", "window:"]) #listener = atspi.EventListener(callback, ["window:"]) #listener = atspi.EventListener(callback, ["object:"]) #listener = atspi.EventListener(callback, ["focus:"]) # explicit list of all events, taken from at-spi/test/event-listener-test.c: eventNames = [ "focus:", "mouse:rel", "mouse:button", "mouse:abs", "keyboard:modifiers", "object:property-change", "object:property-change:accessible-name", "object:property-change:accessible-description", "object:property-change:accessible-parent", "object:state-changed", "object:state-changed:focused", "object:selection-changed", "object:children-changed", "object:active-descendant-changed", "object:visible-data-changed", "object:text-selection-changed", # "object:text-caret-moved", # "object:text-changed", "object:column-inserted", "object:row-inserted", "object:column-reordered", "object:row-reordered", "object:column-deleted", "object:row-deleted", "object:model-changed", "object:link-selected", #"object:bounds-changed", # avoid swamping log "window:minimize", "window:maximize", "window:restore", "window:activate", "window:create", "window:deactivate", "window:close", "window:lower", "window:raise", "window:resize", "window:shade", "window:unshade", "object:property-change:accessible-table-summary", "object:property-change:accessible-table-row-header", "object:property-change:accessible-table-column-header", "object:property-change:accessible-table-summary", "object:property-change:accessible-table-row-description", "object:property-change:accessible-table-column-description", "object:test" ] listeners = [] for eventName in eventNames: #listener = atspi.EventListener(callback, [eventName]) listeners.append(pyatspi.Registry.registerEventListener(callback, eventName)) #listener = atspi.EventListener(callback, [""]) pyatspi.Registry.start(False, False) dogtail-0.9.0/tests/0000775000175000017500000000000012323471036015132 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/tests/gtkdemotest.py0000664000175000017500000000273412323451232020040 0ustar vhumpavhumpa00000000000000# -*- coding: utf-8 -*- import unittest class GtkDemoTest(unittest.TestCase): """ TestCase subclass which handles bringing up and shutting down gtk-demo as a fixture. Used for writing other test cases. """ def setUp(self): import dogtail.config dogtail.config.config.logDebugToStdOut = True dogtail.config.config.logDebugToFile = False import dogtail.utils self.pid = dogtail.utils.run('gtk3-demo') self.app = dogtail.tree.root.application('gtk3-demo') def tearDown(self): import os import signal import time os.kill(self.pid, signal.SIGKILL) # Sleep just enough to let the app actually die. # AT-SPI doesn't like being hammered too fast. time.sleep(0.5) def runDemo(self, demoName): """ Click on the named demo within the gtk-demo app. """ tree = self.app.child(roleName="tree table") tree.child(demoName).doActionNamed('activate') def trap_stdout(function, args=None): """ Grab stdout output during function execution """ import sys from StringIO import StringIO saved_stdout = sys.stdout try: out = StringIO() sys.stdout = out if type(args) is dict: function(**args) elif args: function(args) else: function() output = out.getvalue().strip() finally: sys.stdout = saved_stdout return output dogtail-0.9.0/tests/test_procedural.py0000664000175000017500000001626512323451232020711 0ustar vhumpavhumpa00000000000000#!/usr/bin/python """ Unit tests for the dogtail.procedural API """ __author__ = "Zack Cerza " from dogtail.procedural import focus, keyCombo, deselect, select, click, tree, FocusError, run, config, type config.logDebugToFile = False config.logDebugToStdOut = True import pyatspi from gtkdemotest import GtkDemoTest, trap_stdout from nose.tools import nottest class GtkDemoTest(GtkDemoTest): def setUp(self): self.pid = run('gtk3-demo') self.app = focus.application.node # FIXME: Implement doubleclick() in d.procedural and override the other # methods of Node.GtkDemoTest class TestFocusApplication(GtkDemoTest): def testFocusingBogusNameWithoutAFatalError(self): config.fatalErrors = False output = trap_stdout(focus.application, "should not be found") self.assertTrue( 'The requested widget could not be focused: "should not be found" application' in output) def testThrowExceptionOnFocusingBogusName(self): config.fatalErrors = True self.assertRaises(FocusError, focus.application, "should not be found") def testFocusingBasic(self): "Ensure that focus.application() sets focus.application.node properly" focus.application.node = None focus.application("gtk3-demo") self.assertEquals(focus.application.node, self.app) class TestFocusWindow(GtkDemoTest): def testFocusingBogusNameWithoutAFatalError(self): config.fatalErrors = False output = trap_stdout(focus.window, "should not be found") self.assertEquals(focus.window.node, None) self.assertTrue( 'The requested widget could not be focused: "should not be found" window' in output) def testThrowExceptionOnFocusingBogusName(self): config.fatalErrors = True self.assertRaises(FocusError, focus.window, "should not be found") class TestFocusDialog(GtkDemoTest): def testFocusingBogusNameWithoutAFatalError(self): config.fatalErrors = False output = trap_stdout(focus.dialog, "should not be found") self.assertEquals(focus.dialog.node, None) self.assertTrue( 'The requested widget could not be focused: "should not be found" dialog' in output) def testThrowExceptionOnFocusingBogusName(self): config.fatalErrors = True self.assertRaises(FocusError, focus.dialog, "should not be found") class TestFocusWidget(GtkDemoTest): def testFocusingEmptyName(self): self.assertRaises(TypeError, focus.widget) def testFocusingBogusNameWithoutAFatalError(self): config.fatalErrors = False output = trap_stdout(focus.widget, "should not be found") self.assertEquals(focus.widget.node, None) self.assertTrue( 'The requested widget could not be focused: child with name="should not be found"' in output) def testThrowExceptionOnFocusingBogusName(self): config.fatalErrors = True self.assertRaises(FocusError, focus.widget, "should not be found") def testFocusingBasic(self): "Ensure that focus.widget('foo') finds a node with name 'foo'" focus.widget("Application window") self.assertEquals(focus.widget.name, "Application window") class TestFocus(GtkDemoTest): def testInitialState(self): "Ensure that focus.widget, focus.dialog and focus.window are None " + \ "initially." self.assertEquals(focus.widget.node, None) self.assertEquals(focus.dialog.node, None) self.assertEquals(focus.window.node, None) def testFocusingApp(self): "Ensure that focus.app() works" focus.app.node = None focus.app('gtk3-demo') self.assertEquals(focus.app.node, self.app) def testFocusingAppViaApplication(self): "Ensure that focus.application() works" focus.app.node = None focus.application('gtk3-demo') self.assertEquals(focus.app.node, self.app) def testFocusGettingBogusAttribute(self): self.assertRaises(AttributeError, getattr, focus, 'nosuchtype') def testFocusSettingBogusAttribute(self): self.assertRaises( AttributeError, setattr, focus, 'nosuchtype', 'nothing') def testFocusingRoleName(self): "Ensure that focus.widget(roleName=...) works." focus.widget(roleName='page tab') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_PAGE_TAB) def testFocusMenu(self): self.runDemo('Application window') focus.window('Application Window') focus.menu('File') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_MENU) def testFocusMenuItem(self): self.runDemo('Application window') focus.window('Application Window') click.menu('File') focus.menuItem('New') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_MENU_ITEM) def testFocusButton(self): self.runDemo('Application window') focus.window('Application Window') focus.button('Open') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_PUSH_BUTTON) def testFocusTable(self): self.runDemo('Builder') focus.window('GtkBuilder demo') focus.table('') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_TABLE) def testFocusTableCell(self): self.runDemo('Builder') focus.window('GtkBuilder demo') focus.tableCell('') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_TABLE_CELL) def testFocusText(self): self.runDemo('Application window') focus.window('Application Window') focus.text('') self.assert_(isinstance(focus.widget.node, tree.Node)) self.assertEquals(focus.widget.node.role, pyatspi.ROLE_TEXT) class TestKeyCombo(GtkDemoTest): def testKeyCombo(self): self.runDemo('Application window') focus.window('Application Window') keyCombo("a") focus.dialog('About GTK+ Code Demos') class TestActions(GtkDemoTest): def testClick(self): click('Source') self.assertTrue(focus.widget.isSelected) def testClickWithRaw(self): click('Source', raw=True) self.assertTrue(focus.widget.isSelected) def testSelect(self): select('Source') self.assertTrue(focus.widget.isSelected) @nottest def testDeselect(self): type('Icon View') click('Icon View') type('+') self.runDemo('Icon View Basics') focus.window('GtkIconView demo') focus.widget(roleName='icon') select() deselect() self.assertFalse(focus.widget.isSelected) def testTyping(self): self.runDemo('Dialog and Message Boxes') focus.window('Dialogs') focus.widget(roleName='text') type("hello world") self.assertEquals(focus.widget.node.text, 'hello world') dogtail-0.9.0/tests/test_logging.py0000664000175000017500000000577412323451232020202 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for the dogtail.logging package """ import unittest import dogtail.tree from gtkdemotest import trap_stdout class TestLogging(unittest.TestCase): def setUp(self): self.old_log_dir = dogtail.config.config.logDir def tearDown(self): dogtail.config.config.logDebugToFile = False dogtail.config.config.logDir = self.old_log_dir def test_entryStamp_is_not_empty(self): ts = dogtail.logging.TimeStamp() self.assertEquals(len(ts.entryStamp()) > 0, True) def test_correct_error_if_log_dir_does_not_exist(self): import shutil shutil.rmtree(dogtail.config.config.logDir) self.assertRaises(IOError, dogtail.logging.Logger, "log", file=True) def test_unique_name(self): logger1 = dogtail.logging.Logger("log", file=True) logger1.createFile() logger2 = dogtail.logging.Logger("log", file=True) logger2.createFile() logger3 = dogtail.logging.Logger("log", file=True) self.assertNotEquals(logger1.fileName, logger2.fileName) self.assertNotEquals(logger2.fileName, logger3.fileName) def test_no_new_line_to_file(self): dogtail.config.config.logDebugToFile = True logger = dogtail.logging.Logger("log", file=True, stdOut=False) logger.log("hello world", newline=False) self.assertTrue("hello world " in open(logger.fileName, 'r').read()) def test_no_new_line_to_stdout(self): dogtail.config.config.logDebugToFile = False logger = dogtail.logging.Logger("log", file=False, stdOut=True) output = trap_stdout( logger.log, {'message': 'hello world', 'newline': False}) self.assertEquals(output, "hello world") def test_no_new_line_to_both_file_and_stdout(self): dogtail.config.config.logDebugToFile = True logger = dogtail.logging.Logger("log", file=True, stdOut=True) output = trap_stdout( logger.log, {'message': 'hello world', 'newline': False}) self.assertTrue("hello world" in output) self.assertTrue("hello world " in open(logger.fileName, 'r').read()) def test_empty_script_name(self): dogtail.config.config.scriptName = None logger = dogtail.logging.Logger("log", file=True, stdOut=True) self.assertTrue(logger.fileName, "log") def test_force_to_file(self): dogtail.config.config.logDebugToFile = False logger = dogtail.logging.Logger("log", file=True, stdOut=False) logger.log("hello world", force=True) self.assertTrue("hello world" in open(logger.fileName, 'r').read()) def test_results_logger_correct_dict(self): logger = dogtail.logging.ResultsLogger("log") output = trap_stdout(logger.log, {'entry': {'a': '1'}}) self.assertEquals('a: 1' in output, True) def test_results_logger_incorrect_dict(self): logger = dogtail.logging.ResultsLogger("log") self.assertRaises(ValueError, logger.log, "not a dict") dogtail-0.9.0/tests/test_predicate.py0000664000175000017500000002213212323451232020477 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for the dogtail.predicate package """ import unittest import dogtail.tree import dogtail.predicate class TestPredicate(unittest.TestCase): class DummyNode: def __init__(self, name='', roleName='', description=''): self.name = name self.roleName = roleName self.description = description self.labeller = None def test_capitalization(self): self.assertEquals( dogtail.predicate.makeCamel("gnome-terminal"), "gnomeTerminal") self.assertEquals( dogtail.predicate.makeCamel("Evolution - Mail"), "evolutionMail") self.assertEquals( dogtail.predicate.makeCamel( 'self.assertEquals(makeCamel("Evolution - Mail"), "evolutionMail")'), "selfAssertequalsMakecamelEvolutionMailEvolutionmail") def test_abstract_class(self): predicate = dogtail.predicate.Predicate() self.assertRaises(NotImplementedError, predicate.satisfiedByNode, None) self.assertRaises( NotImplementedError, predicate.makeScriptMethodCall, None) self.assertRaises( NotImplementedError, predicate.makeScriptVariableName) self.assertRaises( NotImplementedError, predicate.describeSearchResult, None) def test_correct_equality(self): predicate1 = dogtail.predicate.Predicate() predicate2 = dogtail.predicate.Predicate() self.assertEquals(predicate1, predicate2) def test_incorrect_equality(self): predicate = dogtail.predicate.Predicate() self.assertNotEquals(predicate, self) def test_predicates_application(self): dummyApp = self.DummyNode('dummy', 'application') appPredicate = dogtail.predicate.IsAnApplicationNamed(dummyApp.name) self.assertTrue(appPredicate.satisfiedByNode(dummyApp)) self.assertEquals( appPredicate.makeScriptMethodCall(True), u'application("dummy")') self.assertEquals(appPredicate.makeScriptVariableName(), u'dummyApp') def test_predicates_window(self): dummyWin = self.DummyNode('dummy', 'frame') self.assertTrue( dogtail.predicate.IsAWindow().satisfiedByNode(dummyWin)) self.assertEquals( dogtail.predicate.IsAWindow().describeSearchResult(), 'window') def test_predicates_window_named(self): dummyWin = self.DummyNode('dummy', 'frame') frameNamedPredicate = dogtail.predicate.IsAWindowNamed(dummyWin.name) self.assertTrue(frameNamedPredicate.satisfiedByNode(dummyWin)) self.assertEquals( frameNamedPredicate.makeScriptMethodCall(False), u'window("dummy")') self.assertEquals( frameNamedPredicate.makeScriptVariableName(), u'dummyWin') def test_predicates_menu_named(self): dummyMenu = self.DummyNode('dummy', 'menu') menuNamedPredicate = dogtail.predicate.IsAMenuNamed(dummyMenu.name) self.assertTrue(menuNamedPredicate.satisfiedByNode(dummyMenu)) self.assertEquals(menuNamedPredicate.makeScriptMethodCall( False), u'menu("dummy", recursive=False)') self.assertEquals( menuNamedPredicate.makeScriptVariableName(), u'dummyMenu') def test_predicates_menu_item_named(self): dummyMenuItem = self.DummyNode('dummy', 'menu item') menuItemNamedPredicate = dogtail.predicate.IsAMenuItemNamed( dummyMenuItem.name) self.assertTrue(menuItemNamedPredicate.satisfiedByNode(dummyMenuItem)) self.assertEquals(menuItemNamedPredicate.makeScriptMethodCall( False), u'menuItem("dummy", recursive=False)') self.assertEquals( menuItemNamedPredicate.makeScriptVariableName(), u'dummyMenuItem') def test_predicates_text_entry_named(self): dummyText = self.DummyNode('dummy', 'text') textNamedPredicate = dogtail.predicate.IsATextEntryNamed( dummyText.name) self.assertTrue(textNamedPredicate.satisfiedByNode(dummyText)) self.assertEquals(textNamedPredicate.makeScriptMethodCall( False), u'textentry("dummy", recursive=False)') self.assertEquals( textNamedPredicate.makeScriptVariableName(), u'dummyEntry') def test_predicates_button_named(self): dummyButton = self.DummyNode('dummy', 'push button') buttonNamedPredicate = dogtail.predicate.IsAButtonNamed( dummyButton.name) self.assertTrue(buttonNamedPredicate.satisfiedByNode(dummyButton)) self.assertEquals(buttonNamedPredicate.makeScriptMethodCall( False), u'button("dummy", recursive=False)') self.assertEquals( buttonNamedPredicate.makeScriptVariableName(), u'dummyButton') def test_predicates_page_tab_named(self): dummyTab = self.DummyNode('dummy', 'page tab') pageTabNamedPredicate = dogtail.predicate.IsATabNamed(dummyTab.name) self.assertTrue(pageTabNamedPredicate.satisfiedByNode(dummyTab)) self.assertEquals(pageTabNamedPredicate.makeScriptMethodCall( False), u'tab("dummy", recursive=False)') self.assertEquals( pageTabNamedPredicate.makeScriptVariableName(), u'dummyTab') def test_predicates_generic_by_name(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') genericPredicateByName = dogtail.predicate.GenericPredicate( name=dn1.name) self.assertTrue(genericPredicateByName.satisfiedByNode(dn1)) self.assertEquals(genericPredicateByName.makeScriptMethodCall( False), u'child( name="dummy name 1", recursive=False)') self.assertEquals( genericPredicateByName.makeScriptVariableName(), u'dummyName1Node') def test_predicates_generic_by_roleName(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') genericPredicateByRole = dogtail.predicate.GenericPredicate( roleName=dn1.roleName) self.assertTrue(genericPredicateByRole.satisfiedByNode(dn1)) self.assertEquals(genericPredicateByRole.makeScriptMethodCall( False), u"child( roleName='dummy role 1', recursive=False)") self.assertEquals( genericPredicateByRole.makeScriptVariableName(), u'dummyRole1Node') def test_predicates_generic_by_description(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') genericPredicateByDescription = dogtail.predicate.GenericPredicate( description=dn1.description) self.assertTrue(genericPredicateByDescription.satisfiedByNode(dn1)) self.assertEquals(genericPredicateByDescription.makeScriptMethodCall( False), u"child( description='dummy desc 1', recursive=False)") self.assertEquals( genericPredicateByDescription.makeScriptVariableName(), u'dummyDesc1Node') def test_predicates_generic_by_label(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') dn2 = self.DummyNode('dummy name 2', 'dummy role 2', 'dummy desc 2') dn2.labeller = dn1 genericPredicateByLabel = dogtail.predicate.GenericPredicate( label=dn1.name) self.assertTrue(genericPredicateByLabel.satisfiedByNode(dn2)) self.assertEquals(genericPredicateByLabel.makeScriptMethodCall( False), u'child(label="dummy name 1", recursive=False)') self.assertEquals( genericPredicateByLabel.makeScriptVariableName(), u'dummyName1Node') def test_predicates_named(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') genericNamedPredicate = dogtail.predicate.IsNamed(dn1.name) self.assertTrue(genericNamedPredicate.satisfiedByNode(dn1)) self.assertEquals(genericNamedPredicate.makeScriptMethodCall( False), u'child(name="dummy name 1", recursive=False)') self.assertEquals( genericNamedPredicate.makeScriptVariableName(), u'dummyName1Node') def test_predicates_labelled_as(self): dn1 = self.DummyNode('dummy name 1', 'dummy role 1', 'dummy desc 1') dn2 = self.DummyNode('dummy name 2', 'dummy role 2', 'dummy desc 2') dn2.labeller = dn1 genericLabelledPredicate = dogtail.predicate.IsLabelledAs(dn1.name) self.assertTrue(genericLabelledPredicate.satisfiedByNode(dn2)) self.assertFalse(genericLabelledPredicate.satisfiedByNode(dn1)) self.assertEquals(genericLabelledPredicate.makeScriptMethodCall( False), u'child(label="dummy name 1", recursive=False)') self.assertEquals( genericLabelledPredicate.makeScriptVariableName(), u'dummyName1Node') def test_predicates_dialog_named(self): dn1 = self.DummyNode('dummy name 1', 'dialog', 'dummy desc 1') genericNamedPredicate = dogtail.predicate.IsADialogNamed(dn1.name) self.assertTrue(genericNamedPredicate.satisfiedByNode(dn1)) self.assertEquals(genericNamedPredicate.makeScriptMethodCall( False), u'dialog("dummy name 1")') self.assertEquals( genericNamedPredicate.makeScriptVariableName(), u'dummyName1Dlg') dogtail-0.9.0/tests/test_utils.py0000664000175000017500000000406012323451232017677 0ustar vhumpavhumpa00000000000000#!/usr/bin/python """ Unit tests for the dogtail.procedural API """ __author__ = "Zack Cerza " import unittest import dogtail.tree import dogtail.predicate dogtail.config.config.logDebugToFile = False dogtail.config.config.logDebugToStdOut = True from gtkdemotest import GtkDemoTest class TestScreenshot(GtkDemoTest): def make_expected_and_compare(self, actual_path, jpg_tolerance=None): extension = actual_path.split('.')[-1] expected_path = actual_path.replace(extension, "expected." + extension) import os os.system("gnome-screenshot -f %s" % expected_path) command = ["compare", "-metric", "MAE", actual_path, expected_path, "output"] import subprocess p = subprocess.Popen(command, stderr=subprocess.PIPE) output, error = p.communicate() import re m = re.search(r"\((.*)\)", error) self.assertTrue(0.1 >= float(m.group(1))) def test_screenshot_incorrect_timestamp(self): self.assertRaises( TypeError, dogtail.utils.screenshot, "timeStamp", None) def test_screenshot_default(self): actual_path = dogtail.utils.screenshot() self.make_expected_and_compare(actual_path) def test_screenshot_basename(self): actual_path = dogtail.utils.screenshot("basename") self.make_expected_and_compare(actual_path) def test_screenshot_no_time_stamp(self): actual_path = dogtail.utils.screenshot(timeStamp=False) self.make_expected_and_compare(actual_path) def test_screenshot_jpeg(self): actual_path = dogtail.utils.screenshot("basename.jpg") self.make_expected_and_compare(actual_path, jpg_tolerance=True) def test_screenshot_unknown_format(self): self.assertRaises(ValueError, dogtail.utils.screenshot, "basename.dat") class TestA11Y(unittest.TestCase): def test_bail_when_a11y_disabled(self): self.assertRaises(SystemExit, dogtail.utils.bailBecauseA11yIsDisabled) def test_enable_a11y(self): dogtail.utils.enableA11y() dogtail-0.9.0/tests/test_config.py0000664000175000017500000000454012323451232020007 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for the dogtail.config class """ import unittest import dogtail.config class TestConfiguration(unittest.TestCase): def test_get_set_all_properties(self): for option in dogtail.config.config.defaults.keys(): print("Setting config.%s property" % option) value = '' if 'Dir' in option: value = '/tmp/dogtail/' # Special value for dir-related properties dogtail.config.config.__setattr__(option, value) self.assertEquals(dogtail.config.config.__getattr__(option), value) def test_default_directories_created(self): import os.path self.assertEquals( os.path.isdir(dogtail.config.config.scratchDir), True) self.assertEquals(os.path.isdir(dogtail.config.config.logDir), True) self.assertEquals(os.path.isdir(dogtail.config.config.dataDir), True) def test_set(self): self.assertRaises( AttributeError, setattr, dogtail.config.config, 'nosuchoption', 42) def test_get(self): self.assertRaises( AttributeError, getattr, dogtail.config.config, 'nosuchoption') def helper_create_directory_and_set_option(self, path, property_name): import os.path if os.path.isdir(path): import shutil shutil.rmtree(path) dogtail.config.config.__setattr__(property_name, path) self.assertEquals(os.path.isdir(path), True) def test_create_scratch_directory(self): new_folder = "/tmp/dt" self.helper_create_directory_and_set_option(new_folder, 'scratchDir') def test_create_data_directory(self): new_folder = "/tmp/dt_data" self.helper_create_directory_and_set_option(new_folder, 'dataDir') def test_create_log_directory(self): new_folder = "/tmp/dt_log" self.helper_create_directory_and_set_option(new_folder, 'logDir') def test_load(self): dogtail.config.config.load({'actionDelay': 2.0}) self.assertEquals(dogtail.config.config.actionDelay, 2.0) def test_reset(self): default_actionDelay = dogtail.config.config.defaults['actionDelay'] dogtail.config.config.actionDelay = 2.0 dogtail.config.config.reset() self.assertEquals( dogtail.config.config.actionDelay, default_actionDelay) dogtail-0.9.0/tests/test_node.py0000664000175000017500000005044112323451232017470 0ustar vhumpavhumpa00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for the dogtail.Node class Notes on pyunit (the "unittest" module): Test classes are written as subclass of unittest.TestCase. A test is a method of such a class, beginning with the string "test" unittest.main() will run all such methods. Use "-v" to get feedback on which tests are being run. Tests are run in alphabetical order; all failure reports are gathered at the end. setUp and tearDown are "magic" methods, called before and after each such test method is run. """ __author__ = "Dave Malcolm " import unittest import dogtail.tree import dogtail.predicate import dogtail.config dogtail.config.config.logDebugToFile = False import pyatspi from nose.tools import nottest from gtkdemotest import GtkDemoTest, trap_stdout class TestNodeAttributes(GtkDemoTest): """ Unit tests for the the various synthesized attributes of a Node """ def testGetBogus(self): "Getting a non-existant attribute should raise an attribute error" self.assertRaises( AttributeError, getattr, self.app, "thisIsNotAnAttribute") # FIXME: should setattr for a non-existant attr be allowed? # 'name' (read-only string): def testGetName(self): """ Node.name of the gtk-demo app should be "gtk-demo" """ self.assertEquals(self.app.name, 'gtk3-demo') self.assertEquals(dogtail.tree.root.name, 'main') def testSetName(self): "Node.name should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "name", "hello world") # 'roleName' (read-only string): def testGetRoleName(self): """ roleName of the gtk-demo app should be "application" """ self.assertEquals(self.app.roleName, 'application') def testSetRoleName(self): """Node.roleName should be read-only""" self.assertRaises( AttributeError, self.app.__setattr__, "roleName", "hello world") # 'role' (read-only atspi role enum): def testGetRole(self): """Node.role for a gtk-demo app should be SPI_ROLE_APPLICATION""" self.assertEquals(self.app.role, dogtail.tree.pyatspi.ROLE_APPLICATION) def testSetRole(self): """Node.role should be read-only""" # FIXME should be AttributeError? self.assertRaises( RuntimeError, self.app.__setattr__, "role", pyatspi.Atspi.Role(1)) # 'description' (read-only string): def testGetDescription(self): # FIXME: can we get a more interesting test case here? self.assertEquals(self.app.description, "") def testSetDescription(self): "Node.description should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "description", "hello world") # 'parent' (read-only Node instance): def testGetParent(self): # the app has a parent if gnome-shell is used, so parent.parent is a # safe choice if filter(lambda x: x.name == 'gnome-shell', self.app.applications()): self.assertEquals(self.app.parent.parent, None) self.assertEquals(self.app.children[0].parent, self.app) def testSetParent(self): "Node.parent should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "parent", None) # 'children' (read-only list of Node instances): def testGetChildren(self): "A fresh gtk-demo app should have a single child: the window." kids = self.app.children self.assertEquals(len(kids), 1) self.assertEquals(kids[0].name, "GTK+ Code Demos") self.assertEquals(kids[0].roleName, "frame") def testSetChildren(self): "Node.children should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "children", []) # 'text' (string): @nottest def testSimpleTextEntry(self): """ Use gtk-demo's text entry example to check that reading and writing Node.text works as expected """ self.runDemo('Dialog and Message Boxes') wnd = self.app.window('Dialogs') wnd.button('Interactive Dialog').click() dlg = self.app.dialog('Interactive Dialog') entry1 = dlg.child(label='Entry 1') entry2 = dlg.child(label='Entry 2') # Try reading the entries: self.assertEquals(entry1.text, "") self.assertEquals(entry2.text, "") # Set them... entry1.text = "hello" entry2.text = "world" # Ensure that they got set: self.assertEquals(entry1.text, "hello") self.assertEquals(entry2.text, "world") # and try again, searching for them again, to ensure it actually # affected the UI: self.assertEquals(dlg.child(label='Entry 1').text, "hello") self.assertEquals(dlg.child(label='Entry 2').text, "world") # Ensure app.text is None self.assertEquals(self.app.text, None) # Ensure a label's text is read-only as expected: # FIXME: this doesn't work; the label has no 'text'; it has a name. we wan't a readonly text entry # label = dlg.child('Entry 1') # self.assertRaises(dogtail.tree.ReadOnlyError, label.text.__setattr__, "text", "hello world") # FIXME: should we assert that things are logged and delays are added? # FIXME: should have a test case involving the complex GtkTextView # widget @nottest def testCaretOffset(self): "Make sure the caret offset works as expected" self.runDemo('Dialog and Message Boxes') wnd = self.app.window('Dialogs') entry1 = wnd.child(label='Entry 1') entry2 = wnd.child(label='Entry 2') # Try reading the entries: self.assertEquals(entry1.text, '') self.assertEquals(entry2.text, '') # Set them... s1 = "I just need a sentence" s2 = "And maybe a second one to be sure" entry1.text = s1 entry2.text = s2 # Make sure the caret offset is zero self.assertEquals(entry1.caretOffset, 0) self.assertEquals(entry2.caretOffset, 0) # Set the caret offset to something ridiculous entry1.caretOffset = len(s1 * 3) entry2.caretOffset = len(s2 * 3) # Make sure the caret offset only goes as far as the end of the string self.assertEquals(entry1.caretOffset, len(s1)) self.assertEquals(entry2.caretOffset, len(s2)) def splitByOffsets(node, string): # Verify the equality of node.text and string, word by word. # I realize this doesn't really test dogtail itself, but that could # change in the future and I don't want to throw the code away. textIface = node.queryText() endOffset = -1 # We only set this now so the loop looks nicer startOffset = 0 while startOffset != len(string): (text, startOffset, endOffset) = textIface.getTextAtOffset( startOffset, pyatspi.TEXT_BOUNDARY_WORD_START) self.assertEquals(startOffset, string.find(text, startOffset, endOffset)) startOffset = endOffset splitByOffsets(entry1, s1) splitByOffsets(entry2, s2) # 'combovalue' (read/write string): @nottest def testSetComboValue(self): self.runDemo('Combo boxes') wnd = self.app.window('Combo boxes') combo1 = wnd.child('Some stock icons').child(roleName='combo box') combo1.combovalue = 'Clear' self.assertEquals(combo1.combovalue, 'Clear') # 'stateSet' (read-only StateSet instance): def testGetStateSet(self): "Node.sensitive should be False for the gtk-demo app node" self.assert_(not self.app.sensitive) def testSetStateSet(self): "Node.stateSet should be read-only" # FIXME should be AttributeError? self.assertRaises( RuntimeError, self.app.__setattr__, "states", pyatspi.StateSet()) # 'relations' (read-only list of atspi.Relation instances): def testGetRelations(self): # FIXME once relations are used for something other than labels pass # 'labelee' (read-only list of Node instances): @nottest def testGetLabelee(self): "Entry1/2's labelee should be a text widget" self.runDemo('Dialog and Message Boxes') wnd = self.app.window('Dialogs') label = wnd.child(roleName='label') self.assertEquals(label.labelee.roleName, 'text') def testSetLabelee(self): "Node.labelee should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "labellee", None) # 'labeler' (read-only list of Node instances): # def testGetLabeler(self): # "The text areas in the 'Dialogs' window should have labelers." # self.runDemo('Dialog and Message Boxes') # wnd = self.app.window('Dialogs') # text = wnd.child(roleName = 'text') # self.assertEquals(text.labeler.name, 'Entry 2') def testSetLabeller(self): "Node.labeller should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "labeller", None) # 'sensitive' (read-only boolean): def testGetSensitive(self): """ Node.sensitive should not be set for the gtk-demo app. It should be set for the window within the app. """ self.assert_(not self.app.sensitive) self.assert_(self.app.children[0].sensitive) def testSetSensitive(self): "Node.sensitive should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "sensitive", True) # 'showing' (read-only boolean): def testGetShowing(self): "Node.showing should not be set for the gtk-demo. It should be set for the window within the app" self.assert_(not self.app.showing) self.assert_(self.app.children[0].showing) def testSetShowing(self): "Node.showing should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "showing", True) # 'actions' (read-only list of Action instances): def testGetActions(self): "Node.actions should be an empty list for the app node" self.assertEquals(len(self.app.actions), 0) def testSetActions(self): "Node.actions should be read-only" self.assertRaises(AttributeError, self.app.__setattr__, "actions", {}) # 'extents' (readonly tuple): def testGetExtents(self): "Node.extents should be a 4-tuple for a window, with non-zero size" (x, y, w, h) = self.app.children[0].extents self.assert_(w > 0) self.assert_(h > 0) def testSetExtents(self): "Node.extents should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "extents", (0, 0, 640, 480)) # 'position' (readonly tuple): def testGetPosition(self): "Node.position should be a 2-tuple for a window" (x, y) = self.app.children[0].position def testSetPosition(self): "Node.position should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "position", (0, 0)) # 'size' (readonly tuple): def testGetSize(self): "Node.size should be a 2-tuple for a window, with non-zero values" (w, h) = self.app.children[0].size self.assert_(w > 0) self.assert_(h > 0) def testSetSize(self): "Node.size should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "size", (640, 480)) # 'toolkitName' (readonly string): def testGetToolkit(self): self.assertEquals(self.app.toolkitName, "gtk") def testSetToolkit(self): "Node.toolkit should be read-only" self.assertRaises( AttributeError, self.app.__setattr__, "toolkitName", "gtk") # 'ID' def testGetID(self): "Node.id should be numeric" self.assertEquals(type(self.app.id), type(42)) def testSetID(self): "Node.id should be read-only" self.assertRaises(AttributeError, setattr, self.app, "id", 42) class TestSelection(GtkDemoTest): def testTabs(self): """ Tabs in the gtk-demo should be selectable, and be queryable for "isSelected", and the results should change as they are selected. """ # Use the Info/Source tabs of gtk-demo: info = self.app.child('Info') source = self.app.child('Source') # Check initial state: self.assert_(info.isSelected) self.assert_(not source.isSelected) # Select other tab: source.select() # Check new state: self.assert_(not info.isSelected, False) self.assert_(source.isSelected) # Deselect tab: # source.deselect() # Check state: # self.assert_(info.isSelected) #self.assert_(not source.isSelected) class TestValue(GtkDemoTest): def testGetValue(self): "The scrollbar starts out at position zero." sb = self.app.child(roleName='scroll bar') self.assertEquals(sb.value, 0) # def testSetValue(self): # "Ensure that we can set the value of the scrollbar." # sb = self.app.child(roleName = 'scroll bar') # sb.value = 100 # self.assertEquals(sb.value, 100) def testMinValue(self): "Ensure that the minimum value for the scrollbar is correct." sb = self.app.child(roleName='scroll bar') self.assertEquals(sb.minValue, 0) # def testMaxValue(self): # "Ensure that the maximum value for the scrollbar is plausible." # sb = self.app.child(roleName = 'scroll bar') # self.assert_(sb.maxValue > 250) def testMinValueIncrement(self): "Ensure that the minimum value increment of the scrollbar is an int." sb = self.app.child(roleName='scroll bar') self.assertEquals(sb.minValueIncrement, sb.minValueIncrement) class TestSearching(GtkDemoTest): # FIXME: should test the various predicates and the search methods of Node def testFindChildren(self): """ Ensure that there are the correct number of table cells in the list of demos. """ pred = dogtail.predicate.GenericPredicate(roleName='table cell') tableCells = self.app.findChildren(pred) def get_table_cells_recursively(node): counter = 0 for child in node.children: if child.roleName == 'table cell': counter += 1 counter += get_table_cells_recursively(child) return counter counter = get_table_cells_recursively(self.app) self.assertEquals(len(tableCells), counter) def testFindChildren2(self): "Ensure that there are two tabs in the second page tab list." pred = dogtail.predicate.GenericPredicate(roleName='page tab list') pageTabLists = self.app.findChildren(pred) pred = dogtail.predicate.GenericPredicate(roleName='page tab') # The second page tab list is the one with the 'Info' and 'Source' tabs pageTabs = pageTabLists[1].findChildren(pred) self.assertEquals(len(pageTabs), 6) def testFindChildrenLambdas(self): self.runDemo('Dialog and Message Boxes') wnd = self.app.window('Dialogs') texts = wnd.findChildren(lambda x: x.roleName=='text', isLambda = True) self.assertEquals(len(texts), 2) self.assertEquals(texts[0].roleName, 'text') self.assertEquals(texts[1].roleName, 'text') texts1 = wnd.findChildren(lambda x: x.roleName=='text' and x.labeler.name == 'Entry 1', isLambda = True) self.assertEquals(len(texts1), 1) self.assertEquals(texts1[0].roleName, 'text') self.assertEquals(texts1[0].labeler.name, 'Entry 1') texts2 = wnd.findChildren(lambda x: x.roleName=='text' and x.showing, isLambda = True) self.assertEquals(len(texts2), 2) self.assertEquals(texts2[0].roleName, 'text') self.assertTrue(texts2[0].showing) self.assertEquals(texts2[1].roleName, 'text') self.assertTrue(texts2[1].showing) # def testFindChildrenNonRecursive(self): # """ # Ensure that there are the correct number of table cells in the Tree # Store demo. # """ # The next several lines exist to expand the 'Tree View' item and # scroll down, so that runDemo() will work. # FIXME: make runDemo() handle this for us. # treeViewCell = self.app.child('Tree View', roleName = 'table cell') # treeViewCell.typeText('+') # dogtail.tree.doDelay() # sb = self.app.child(roleName = 'scroll bar') # sb.value = sb.maxValue # self.runDemo('Tree Store') # wnd = self.app.window('Card planning sheet') # table = wnd.child(roleName = 'tree table') # pred = dogtail.predicate.GenericPredicate(roleName = 'table cell') # dogtail.config.config.childrenLimit = 10000 # cells = table.findChildren(pred, recursive = False) # direct_cells = filter(lambda cell: cell.roleName=='table cell', table.children) # self.assertEquals(len(cells), len(direct_cells)) class TestActions(GtkDemoTest): # FIXME: should test the various actions pass class TestProcedural(GtkDemoTest): # FIXME: should test the procedural API pass class TestExceptions(GtkDemoTest): @nottest def test_exception(self): # Kill the gtk-demo prematurely: import os import signal os.kill(self.pid, signal.SIGKILL) from gi.repository import GLib # Ensure that we get an exception when we try to work further with it: self.assertRaises(GLib.GError, self.app.dump) class TestConfiguration(unittest.TestCase): def test_get_set_all_properties(self): for option in dogtail.config.config.defaults.keys(): print("Setting config.%s property" % option) value = '' if 'Dir' in option: value = '/tmp/dogtail/' # Special value for dir-related properties dogtail.config.config.__setattr__(option, value) self.assertEquals(dogtail.config.config.__getattr__(option), value) def test_default_directories_created(self): import os.path self.assertEquals( os.path.isdir(dogtail.config.config.scratchDir), True) self.assertEquals(os.path.isdir(dogtail.config.config.logDir), True) self.assertEquals(os.path.isdir(dogtail.config.config.dataDir), True) def test_set(self): self.assertRaises( AttributeError, setattr, dogtail.config.config, 'nosuchoption', 42) def test_get(self): self.assertRaises( AttributeError, getattr, dogtail.config.config, 'nosuchoption') def helper_create_directory_and_set_option(self, path, property_name): import os.path if os.path.isdir(path): import shutil shutil.rmtree(path) dogtail.config.config.__setattr__(property_name, path) self.assertEquals(os.path.isdir(path), True) def test_create_scratch_directory(self): new_folder = "/tmp/dt" self.helper_create_directory_and_set_option(new_folder, 'scratchDir') def test_create_data_directory(self): new_folder = "/tmp/dt_data" self.helper_create_directory_and_set_option(new_folder, 'dataDir') def test_create_log_directory(self): new_folder = "/tmp/dt_log" self.helper_create_directory_and_set_option(new_folder, 'logDir') def test_load(self): dogtail.config.config.load({'actionDelay': 2.0}) self.assertEquals(dogtail.config.config.actionDelay, 2.0) def test_reset(self): default_actionDelay = dogtail.config.config.defaults['actionDelay'] dogtail.config.config.actionDelay = 2.0 dogtail.config.config.reset() self.assertEquals( dogtail.config.config.actionDelay, default_actionDelay) class TestDump(GtkDemoTest): @nottest def test_dump_to_stdout(self): child = self.app.child('Source') output = trap_stdout(child.dump) self.assertEquals( output, """[page tab | Source] [scroll pane | ] [text | ] [scroll bar | ] [action | activate | ] [scroll bar | ] [action | activate | ]""") dogtail-0.9.0/Makefile0000664000175000017500000000277012323451231015431 0ustar vhumpavhumpa00000000000000# dogtail *development* Makefile all: python setup.py build install: python setup.py install --root=$(DESTDIR) clean: rm -rf api_docs/ python setup.py clean rm -f MANIFEST rm -rf build dist find . -name '*.pyc' -exec rm {} \; # Dollar signs must be escaped with dollar signs in variables. export camelCAPS='[a-z_][a-zA-Z0-9_]*$$' export StudlyCaps='[a-zA-Z_][a-zA-Z0-9_]*$$' check: pylint --indent-string=" " --class-rgx=${StudlyCaps} --function-rgx=${camelCAPS} --method-rgx=${camelCAPS} --variable-rgx=${camelCAPS} --argument-rgx=${camelCaps} dogtail sniff/sniff examples/*.py recorder/dogtail-recorder scripts/*.py tarball: python setup.py sdist rpm: tarball # Build using the custom rpmrc in the rpms/ sub-dir rpmbuild -tb dist/dogtail-*.tar.gz # Move the source and binary RPMs to dist/ mv ~/rpmbuild/RPMS/noarch/* dist/ srpm: rpm_prep # Build using the custom rpmrc in the rpms/ sub-dir rpmbuild --rcfile /usr/lib/rpm/rpmrc:/usr/lib/rpm/redhat/rpmrc:`pwd`/rpms/tmp.rpmrc -ts dist/dogtail-*.tar.gz # Move the source and binary RPMs to dist/ mv rpms/SRPMS/* dist/ rm -rf rpms/ apidocs: apidocs_html apidocs_pdf apidocs_html: epydoc --html --config epydoc.conf apidocs_pdf: epydoc --pdf --config epydoc.conf mv api_docs/api.pdf api_docs/dogtail.pdf update_apidocs: apidocs # Sadly, I'm still the only one who can update the API docs. ssh zmc@fedorapeople.org rm -rf \~/public_html/dogtail/epydoc/* scp api_docs/*.{html,css,png,pdf} zmc@fedorapeople.org:~/public_html/dogtail/epydoc/ dogtail-0.9.0/INSTALL0000664000175000017500000000030112205117332015006 0ustar vhumpavhumpa00000000000000Installation on Red-Hat-like systems: make rpm rpm -Uvh ./dist/dogtail-*.noarch.rpm Installation on other systems: ./setup.py install --prefix=/usr (or /usr/local, $HOME/local, etc...) dogtail-0.9.0/dogtail/0000775000175000017500000000000012323471036015413 5ustar vhumpavhumpa00000000000000dogtail-0.9.0/dogtail/rawinput.py0000664000175000017500000001564112323451231017640 0ustar vhumpavhumpa00000000000000# -*- coding: utf-8 -*- """ Handles raw input using AT-SPI event generation. Note: Think of keyvals as keysyms, and keynames as keystrings. Authors: David Malcolm , Zack Cerza """ __author__ = """ David Malcolm , Zack Cerza """ import gi gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') from gi.repository import Gdk from config import config from utils import doDelay from logging import debugLogger as logger from pyatspi import Registry as registry from pyatspi import (KEY_SYM, KEY_PRESS, KEY_PRESSRELEASE, KEY_RELEASE) from exceptions import ValueError from __builtin__ import unicode, unichr def doTypingDelay(): doDelay(config.typingDelay) def checkCoordinates(x, y): if x < 0 or y < 0: raise ValueError( "Attempting to generate a mouse event at negative coordinates: (%s,%s)" % (x, y)) def click(x, y, button=1, check=True): """ Synthesize a mouse button click at (x,y) """ if check: checkCoordinates(x, y) logger.log("Mouse button %s click at (%s,%s)" % (button, x, y)) registry.generateMouseEvent(x, y, 'b%sc' % button) doDelay(config.actionDelay) def doubleClick(x, y, button=1, check=True): """ Synthesize a mouse button double-click at (x,y) """ if check: checkCoordinates(x, y) logger.log("Mouse button %s doubleclick at (%s,%s)" % (button, x, y)) registry.generateMouseEvent(x, y, 'b%sd' % button) doDelay() def press(x, y, button=1, check=True): """ Synthesize a mouse button press at (x,y) """ if check: checkCoordinates(x, y) logger.log("Mouse button %s press at (%s,%s)" % (button, x, y)) registry.generateMouseEvent(x, y, 'b%sp' % button) doDelay() def release(x, y, button=1, check=True): """ Synthesize a mouse button release at (x,y) """ if check: checkCoordinates(x, y) logger.log("Mouse button %s release at (%s,%s)" % (button, x, y)) registry.generateMouseEvent(x, y, 'b%sr' % button) doDelay() def absoluteMotion(x, y, mouseDelay=None, check=True): """ Synthesize mouse absolute motion to (x,y) """ if check: checkCoordinates(x, y) logger.log("Mouse absolute motion to (%s,%s)" % (x, y)) registry.generateMouseEvent(x, y, 'abs') if mouseDelay: doDelay(mouseDelay) else: doDelay() def relativeMotion(x, y, mouseDelay=None): logger.log("Mouse relative motion of (%s,%s)" % (x, y)) registry.generateMouseEvent(x, y, 'rel') if mouseDelay: doDelay(mouseDelay) else: doDelay() def drag(fromXY, toXY, button=1, check=True): """ Synthesize a mouse press, drag, and release on the screen. """ logger.log("Mouse button %s drag from %s to %s" % (button, fromXY, toXY)) (x, y) = fromXY press(x, y, button, check) # doDelay() (x, y) = toXY absoluteMotion(x, y, check=check) doDelay() release(x, y, button, check) doDelay() def typeText(string): """ Types the specified string, one character at a time. Please note, you may have to set a higher typing delay, if your machine misses/switches the characters typed. Needed sometimes on slow setups/VMs typing non-ASCII utf8 chars. """ if not isinstance(string, unicode): string = string.decode('utf-8') for char in string: pressKey(char) keyNameAliases = { 'enter': 'Return', 'esc': 'Escape', 'alt': 'Alt_L', 'control': 'Control_L', 'ctrl': 'Control_L', 'shift': 'Shift_L', 'del': 'Delete', 'ins': 'Insert', 'pageup': 'Page_Up', 'pagedown': 'Page_Down', ' ': 'space', '\t': 'Tab', '\n': 'Return' } # TODO: Dead code def keySymToUniChar(keySym): # pragma: no cover i = Gdk.keyval_to_unicode(keySym) if i: UniChar = unichr(i) else: UniChar = '' return UniChar def uniCharToKeySym(uniChar): # OK, if it's not actually unicode we can fix that, right? if not isinstance(uniChar, unicode): uniChar = unicode(uniChar, 'utf-8') i = ord(uniChar) keySym = Gdk.unicode_to_keyval(i) return keySym # dead code def keySymToKeyName(keySym): # pragma: no cover return Gdk.keyval_name(keySym) def keyNameToKeySym(keyName): keyName = keyNameAliases.get(keyName.lower(), keyName) keySym = Gdk.keyval_from_name(keyName) # various error 'codes' returned for non-recognized chars in versions of GTK3.X if keySym == 0xffffff or keySym == 0x0 or keySym is None: try: keySym = uniCharToKeySym(keyName) except: # not even valid utf-8 char try: # Last attempt run at a keyName ('Meta_L', 'Dash' ...) keySym = getattr(Gdk, 'KEY_' + keyName) except AttributeError: raise KeyError(keyName) return keySym def keyNameToKeyCode(keyName): """ Use GDK to get the keycode for a given keystring. Note that the keycode returned by this function is often incorrect when the requested keystring is obtained by holding down the Shift key. Generally you should use uniCharToKeySym() and should only need this function for nonprintable keys anyway. """ keymap = Gdk.Keymap.get_for_display(Gdk.Display.get_default()) entries = keymap.get_entries_for_keyval( Gdk.keyval_from_name(keyName)) try: return entries[1][0].keycode except TypeError: pass def pressKey(keyName): """ Presses (and releases) the key specified by keyName. keyName is the English name of the key as seen on the keyboard. Ex: 'enter' Names are looked up in Gdk.KEY_ If they are not found there, they are looked up by uniCharToKeySym(). """ keySym = keyNameToKeySym(keyName) registry.generateKeyboardEvent(keySym, None, KEY_SYM) doTypingDelay() def keyCombo(comboString): """ Generates the appropriate keyboard events to simulate a user pressing the specified key combination. comboString is the representation of the key combo to be generated. e.g. 'p' or 'PageUp' or 'q' """ strings = [] for s in comboString.split('<'): if s: for S in s.split('>'): if S: S = keyNameAliases.get(S.lower(), S) strings.append(S) for s in strings: if not hasattr(Gdk, s): if not hasattr(Gdk, 'KEY_' + s): raise ValueError("Cannot find key %s" % s) modifiers = strings[:-1] finalKey = strings[-1] for modifier in modifiers: code = keyNameToKeyCode(modifier) registry.generateKeyboardEvent(code, None, KEY_PRESS) code = keyNameToKeyCode(finalKey) registry.generateKeyboardEvent(code, None, KEY_PRESSRELEASE) for modifier in modifiers: code = keyNameToKeyCode(modifier) registry.generateKeyboardEvent(code, None, KEY_RELEASE) doDelay() dogtail-0.9.0/dogtail/sessions.py0000664000175000017500000001576512323451231017644 0ustar vhumpavhumpa00000000000000import time import os import pwd import errno import re import subprocess import signal import tempfile import random import glob from dogtail.config import config def scratchFile(label): # pragma: no cover """Uses tempfile.NamedTemporaryFile() to create a unique tempfile in config.scratchDir, with a filename like: dogtail-headless-