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.

How

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')
app('Finder').activate()
sysevents.processes['Finder'].menu_bars[1].menus[u'Apple'].menu_items[u'About This Mac'].click()

# some operations may need a pause
time.sleep(1)

loginwindow = sysevents.processes['loginwindow']

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

# Check that there is an All Rights Reserved present.
assert loginwindow.windows['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?

No comments: