2006-04-11

Twill and py.test

The latest tool in my arsenal is twill. It's a cross between a web browser and a testing framework. I think it works quite well, and I use it in conjunction with Buildbot, for testing the web interfaces at work.

Twill allows you to use a trivial little script like:

go http://myhost.exmaple.com/
formvalue login username "stephen"
formvalue login password "secr3t"
submit
code 200
find "Login Successful"

And that will go to a website, login, check that a HTTP 200 code was returned, and verify that the words "Login Succesful" appeared on the page. If any problems occur, then the script will exit with a non-zero exit code, and an error message. This makes buildbot integration trivial.

But why twill is so nice, is because it's completely python. Instead of taking the long way around and invoking twill-sh, you can access the web browser directly, like so.

from twill import commands as web web.go('http://myhost.exmaple.com/')
web.formvalue('login', 'username', "stephen")
web.formvalue('login', ' password', "secr3t")
web.submit
web.code(200)
web.find('Login Successful')

And where this comes in real handy, is when I use it in a test suite such as py.test. py.test -ls --looponfailing is a command that really needs a post of its own to both explain and exclaim about, but suffice it to say that it's lifechanging.

import py.test
from twill.errors import TwillAssertionError
from twill import commands as web

def test_login():
    web.go('http://myhost.exmaple.com/')
    web.formvalue('login', 'username', "stephen")
    web.formvalue('login', ' password', "secr3t")
    web.submit
    web.code(200)
    web.find('Login Successful')
    py.test.raises(TwillAssertionError, web.find, 'Login Failed')

def test_failed_login():     web.go('http://myhost.exmaple.com/')
    web.formvalue('login', 'username', "stephen")
    web.formvalue('login', ' password', "notmypassword")
    web.submit
    web.code(200)
    web.find('Login Failed')
    py.test.raises(TwillAssertionError, web.find, 'Login Successful')

There, tests. Easy to write, easy to read, all written in python, I can leverage as much of python as I want, while still having a quick and easy way of puppeting a website, and testing that it works.

'rati tags: , ,

1 comment:

Sarah said...

TOO DAMN SEXY :)