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:
- Take the code to generate the namespace and append some code to generate and run a doctest.
- generate DocTestParser and DocTestRunner objects.
- 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):It's a wonderful feeling when something is suddenly so obvious!
....code = code + '\n__dtest=__parser.get_doctest(__test, globals(), "Crunchy Doctest", "crunchy", 0)\n__runner.run(__dtest)\n'
....runner = DocTestRunner()
....parser = DocTestParser()
....exec code in {'__runner':runner, '__parser':parser, '__test':test}