[TIP] TDD and automatic code generation
Andreas Dotzler
andreas.dotzler at fs.ei.tum.de
Mon Sep 3 00:50:00 PDT 2007
Hi,
This is about using Zope3 interfaces (or schemas) and doctest to develop in
TDD fashion. I very much liked the article "Zope3 in 30 Minutes
http://zissue.berlios.de/z3/Zope3In30Minutes.html
which is specific about developing a zope3 application, however the principle
should hold for any python application.
So the steps are:
1. write the interface IClassName.py
2. write the doctest test_ClassName.py
3. implement the class ClassName.py and check if it passes the doctest
There is potential of supporting this development by automatic code
generation. Using the Interface one could generate a template for the doctest
+ the implementation. Here is a example
The interface IClassName.py
from zope.interface import Interface, Attribute
from zope.schema import TextLine
class IClassName( Interface ):
"""The interface for ClassName
"""
attr1 = TextLine(
title=u"Attribute 1",
description=u"stores a string",
required=True
default=u"my default value")
def method1():
""" doc of method1
"""
This would lead to a test_ClassName.py that at least includes the following
"""
This is the doctest for class ClassName
Verify Interface
>>> from zope.interface.verify import *
>>> from ClassName import ClassName
>>> from IClassName import IClassname
>>> verifyClass( IClassname, Classname )
True
Create an Instance
>>> a = ClassName()
Check default value of Attribute 1, which stores a string
>>> print a.attr1
my default value
Run method1()
>>> a.method1()
result of method 1
"""
[...maybe more...]
The base for an implementation would look like
from zope.interface import implements
from IClassName import IClassName
class ClassName( object ):
"""ClassName ....
details:
"""
implements( IClassName )
def __init__( self, attr1="my default value" ):
self.attr1 = attr1
def method1( self ):
pass
def _test():
import doctest
doctest.testfile( "test_NetworkHandler.py" )
if __name__ == "__main__":
_test()
[...maybe more...]
One could think of many thinks for [...maybe more...] especially in case the
schema defines some validation.
Does anyone know a concept, tool, script that does approximately what I
suggest ?
Any comment or remark highly appreciated.
Andreas Dotzler
More information about the testing-in-python
mailing list