Wednesday 18 February 2009

A couple of Specs

Here are a couple of snippets of sample code for lancelot.

First up, a standalone function:
import lancelot

def fib(ordinal=0):
    '''Simple fibonacci generator'''
    ...

@lancelot.verifiable
def specify_fib_zero_to_five():
    '''First five fibonacci numbers should be 1,2,3,5,8'''
    spec = lancelot.Spec(fib)
    spec.fib(1).should_be(1)
    spec.fib(2).should_be(2)
    spec.fib(3).should_be(3)
    spec.fib(4).should_be(5)
    spec.fib(5).should_be(8)


Next, a standalone class:
import lancelot

class Stack:
    '''A simple stack with push, pop and peek'''
    ...

@lancelot.verifiable
def behavior_of_stack_with_values():
    '''Should be able to peek() and pop() values after push()'''
    stack = lancelot.Spec(Stack, given=new_stack)
    stack.when(stack.push(value='a'))
    stack.then(stack.peek()).should_be('a')
    stack.then(stack.pop()).should_be('a')
    stack.then(stack.peek()).should_raise(IndexError)
    stack.then(stack.pop()).should_raise(IndexError)


Finally, a class whose behaviour involves collaborations with other classes:
import lancelot

class Observable:
    '''Simple class that sends notifications to its observers'''
    ...

@lancelot.verifiable
def observable_observer_behaviour():
    '''Added Observers should receive Observer notifications.'''
    observer = lancelot.MockSpec()
    observable = Observable()
    spec = lancelot.Spec(observable)
    spec.when(spec.add_observer(observer))
    spec.then(spec.send_notification())
    spec.should_collaborate_with(observer.notify(observable))

No comments:

Post a Comment