Monday, October 4, 2010

No Cucumber for Python?

Edit: ylluminate posted a comment about freshen, which seems to be exactly what I'm looking for.

--

It would seem that nobody in the Python world is much interested in Cucumber. I've given thought many times to this and wondered, how hard is it, really, to implement Cucumber in Python?

Tonight I made an attempt to create a reasonably Pythonic way of writing test steps. Here is what I have so far.

First, here are a couple example steps:


@step(r'Given I set variable "(.*)" to "(.*)"')
def set_var(args):
context[args[0]] = args[1]

@step(r'When I request "(.*)"')
def urlopen(args):
context['response'] = urllib.urlopen(args[0])


And the 'step' decorator:


def step(pattern):
def outer(f):
@wraps(f)
def wrapper(statement):
match = re.match(pattern, statement)
print pattern
if match:
f(match.groups())
steps.append(wrapper)
return wrapper
return outer


I don't have a test runner yet, but here's a complete example for invoking the steps:


import re, urllib
from functools import wraps

steps = []
context = {}

def step(pattern):
def outer(f):
@wraps(f)
def wrapper(statement):
match = re.match(pattern, statement)
print pattern
if match:
f(match.groups())
steps.append(wrapper)
return wrapper
return outer

@step(r'Given I set variable "(.*)" to "(.*)"')
def set_var(args):
context[args[0]] = args[1]

@step(r'When I request "(.*)"')
def urlopen(args):
context['response'] = urllib.urlopen(args[0])

def go(statement):
for func in steps:
func(statement)

if __name__ == '__main__':
print context
go('Given I set variable "x" to "17"')
go('When I request "http://www.google.com"')
print context

4 comments:

ylluminate said...

Have you thought about: http://github.com/aslakhellesoy/cucumber/wiki/Python

or taken a look at: http://github.com/rlisagor/freshen ?

Matt Hanger said...

ylluminate: Thanks for the tip, I had not seen freshen. Seems to be exactly what I'm looking for.

Thanks!

Cássio said...

There is too the Lettuce project
https://github.com/gabrielfalcao/lettuce

Cássio said...
This comment has been removed by the author.