Friday, May 30, 2008

Testing OSX applications with Python

Recently I started a new wxPython based project that would be primarily be running on OSX.

I figured it would be rather useful and neat to have some tests managed by Python that would exercise the whole system so I took a stab at setting some up using some of my standard toolkit. You don't have to test exclusively Python-based application. You can use Python to write the test scripts for the application under test which could be written in any language that OSX supports.


I found out that Apple has already added all the hooks for scripting the UI via an AppleScript service called GUI Scripting or System Events. You can script it easily via AppleScript. Or you can access it all from Python using the appscript module.

It's Easy

Here's some code to get you started testing with GUI Scripting.
from appscript import *
import time

# some boilerplate setup
sysevents = app('System Events')
sysevents.processes['Finder'].menu_bars[1].menus[u'Apple'].menu_items[u'About This Mac'].click()

# some operations may need a pause

loginwindow = sysevents.processes['loginwindow']

# Check that an About this Mac window exists
assert [ win for win in if win.title() == 'About This Mac']

# Check that there is an All Rights Reserved present.
assert['About This Mac'].static_texts['All Rights Reserved.'].get()
The example is a little convoluted because Finder owns the "About This Mac" menu entry, but loginwindow owns the window that pops up.
The hardest part was figuring out the API to work with Apple's UI scripting support. Especially since all of Apple's examples were in AppleScript. Thankfully theres some tools that come with appscript that help. One called ASDictionary that autogenerates documentation for the various AppleScript plugins on your system. Also ASTranslate helps with the job of translating AppleScript code into equivalent appscript usage under Python.

Is that all?

There don't seem to be many Open Source GUI Functional Testing tools for OSX. Anyone know any ? Lots for Web functional testing but not for UI.

There is pywinauto for Windows.

Might be nice if OSX had a similar test layer. pymacauto anyone?

Thursday, May 22, 2008

quick way to debug testbrowser in doctests

Writing doctests I am sometimes wondering what is going on under the hood. Keeping this function around in my test environment makes it a bit easier to find out. After rendering the output to the browser it will pause waiting for a keypress to continue the test.  Note, this code works only on OSX though it should be trivial to modify for any OS.
>>> def render_browser(browser):
...   open('/tmp/browser.html', 'w').write(browser.contents)
...   import os
...   os.system("open /tmp/browser.html")
...   _ = raw_input()