views:

46

answers:

1

Hello i was wondering if it is possible and if so how? to do doctests or something similar from the mainline, instead of testing a function as is described in the doctest docs i.e.

"""
>>> 
Hello World
"""

if __name__ == "__main__":
    print "Hello"
    import doctest
    doctest.testmod()

This is part of being able to test students scripts against a docstring, i found this snipet of code that allows me to input both as strongs

import doctest
from doctest import DocTestRunner, DocTestParser
enter code here
def run_doctest(code, test):
    import doctest
    from doctest import DocTestRunner, DocTestParser
    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}

that does more or less but it seems hardly ideal, an suggestions on either point

+2  A: 

doctest is not limited to testing functions. For example, if dt.py is:

'''
  >>> foo
  23
'''

foo = 23

if __name__ == '__main__':
    import doctest
    doctest.testmod()

then, e.g.:

$ py26 dt.py -v
Trying:
    foo
Expecting:
    23
ok
1 items passed all tests:
   1 tests in __main__
1 tests in 1 items.
1 passed and 0 failed.
Test passed.

(works just as well without the -v, but then it wouldn't have much to show: just silence;-). Is this what you're looking for?

Alex Martelli
Nah i am more after getting what happens if the program runs normally
Hugoagogo
...and? What's not "normal" about running the main script's body, then the doctest? Doesn't seem any different from what your convoluted code is doing -- e.g., the `foo = 23` (followed by the check that `foo` is `23`) in my A's example. Please edit your Q to supply examples of what kind of things you expect in lieu of the `enter code here` and why simply running the module's doctests (after its body) is not what you want, because I think I'm confused;-).
Alex Martelli
for example testing the output of the program (i.e. the regular stuff that comes out via print)
Hugoagogo
Alex Martelli
mmm that was my original path, but i wanted to be able to use that as well as standard doctests, i might have to try and use both in combination
Hugoagogo
@Hugo, sure, if you want to test _both_ the program's whole stdout _and_ the value of some expressions at program's end, doctest on module docstring (as per my A) _plus_ "golden-file test" (as per my previous comment) can both be used.
Alex Martelli
Yep thanks for all the help :)
Hugoagogo
@Hugo, so do I get an accept?-)
Alex Martelli
Sure, thanks for the advice
Hugoagogo