I’ve got a fairly basic doctestable file:
class Foo():
"""
>>> 3+2
5
"""
if __name__ in ("__main__", "__console__"):
import doctest
doctest.testmod(verbose=True)
which works as expected when run directly through python.
However, in iPython, I get
1 items had no tests:
__main__
0 tests in 1 items.
0 passed and 0 failed.
Test passed.
Since this is part of a Django project and will need access to all of the appropriate variables and such that manage.py sets up, I can also run it through a modified command, which uses code.InteractiveConsole, one result of which is __name__ gets set to ‘__console__‘.
With the code above, I get the same result as with iPython. I tried changing the last line to this:
this = __import__(__name__)
doctest.testmod(this, verbose=True)
and I get an ImportError on __console__, which makes sense, I guess. This has no effect on either python or ipython.
So, I’d like to be able to run doctests successfully through all three of these methods, especially the InteractiveConsole one, since I expect to be needing Django pony magic fairly soon.
Just for clarification, this is what I’m expecting:
Trying:
3+2
Expecting:
5
ok
1 items had no tests:
__main__
1 items passed all tests:
1 tests in __main__.Foo
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
The following works:
I have no idea why
ipython file.pydoes not work. But the above is at least a workaround.EDIT:
I found the reason why it does not work. It is quite simple:
doctest.testmod(), it assumes that you want to test the__main__module.__main__module is IPython’s__main__, not your module. So doctest tries to execute doctests in IPython’s entry script.The following works, but feels a bit weird:
So basically the module imports itself (that’s the “feels a bit weird” part). But it works. Something I do not like abt. this approach is that every module needs to include its own name in the source.
EDIT 2:
The following script,
ipython_doctest, makes ipython behave the way you want:The script creates a python script that will execute
%run argnamein IPython.Example: