Thursday, June 29, 2006

Say no to temporary files!

My last post mentioned the problems I was having with doctests, luckily I managed to solve them - but only after about 5 hours of frustrated playing with the API.

The problem arose because to get a DocTest object you have to know the namespace over which it is to be tested, but getting that namespace in the right place is tricky. My final solution was (I like to think) quite an inspired hack:

  1. Take the code to generate the namespace and append some code to generate and run a doctest.
  2. generate DocTestParser and DocTestRunner objects.
  3. exec the code in a namespace that has references to the DocTestParser, the DocTestRunner and a string containing the actual doctests.

The end result looks something like this:

def run_doctest(code, test):
....code = code + '\n__dtest=__parser.get_doctest(__test, globals(), "Crunchy Doctest", "crunchy", 0)\\n'
....runner = DocTestRunner()
....parser = DocTestParser()
....exec code in {'__runner':runner, '__parser':parser, '__test':test}
It's a wonderful feeling when something is suddenly so obvious!

1 comment:

Anonymous said...

w333, i know exactly how you feel when you bash at something till it works :D

it feels like your on top of the world until the next problem pops up hehe.

PS i just got bored of staring at code an decided to search out uk SoC'ers ;)

Hope your having fun