Sunday, June 22, 2008

Doctesting a Class within a Module

The main reason I started this blog was because I wanted a place to store this example I just worked though. I have no idea if this will have any immediate use, but I like these sorts of things. Here goes:

If I have a module called thing.py and in there I have a Thing class, I was wondering how to run doctests that only belong to the class. The basic way to run all doctests in the module (and any classes in there) is:

"""thing module doctest

>>> 4 + 4
9

"""

def _test():
import doctest
doctest.testmod()


class Thing(object):
"""docstring for Thing

>>> 3 + 3
7

"""
def __init__(self, arg):
self.arg = arg

def printMsg(self):
return "Hello %s !" % self.arg


if __name__ == "__main__":
_test()

If I want to just run the doctest in the class though, I can make a new method in the module like this:
def _testThing():
import doctest
thingy = Thing("world")
doctest.run_docstring_examples(thingy, {})
Then run this in the "if __name__" part:
if __name__ == "__main__":
_testThing()

The part "run_docstring_examples(thingy, {})" takes two required arguments - the object and the globals to use in the tests.

In the beginning...

I've been working with Python for about a year now but I haven't been able to write much novel code. I worked in Perl some years ago, took a couple of years to focus on "management", the dove into Python in a QA-ish role. I was immediately struck by the plethora of tools available for testing in Python. After attending PyCon 2008, I was further impressed by the number of people who spoke highly of testing. The number of presentations that had a testing twist and the attendance at those presentations also struck me as wonderful.

At the job I was in at the time, I wasn't going to get the opportunity I wanted to delve into writing and testing python code so I left to pursue things on my own. Ultimately, I want to be a good python tester. I've seen a lot of great projects get stuck in some form of mild unusability once the "sexy" part of the project is over and the nitpicky requests or bug reports come in. I shed a tear for those projects because I think of how much greater they could be if they could break through that wall by either putting better testing in from the start or taking a version or two to settle things into place once they hit the wall.

Me? I haven't had an original idea for an application in a long time so I'm hoping to piggy back on some projects that could use this help. In the meantime, I'm brushing up on my python and testing skills. Hope to see you at the python testing trough.