>> 3+2 5 """ if __name__-6ren">
gpt4 book ai didi

python - 通过iPython和伪控制台运行doctest

转载 作者:行者123 更新时间:2023-11-28 20:00:09 25 4
gpt4 key购买 nike

I've got a fairly basic doctestable file:

class Foo():
"""
>>> 3+2
5
"""

if __name__ in ("__main__", "__console__"):
import doctest
doctest.testmod(verbose=True)

当直接通过python运行时,它可以正常工作。
然而,在伊普顿,我得到
1 items had no tests:
__main__
0 tests in 1 items.
0 passed and 0 failed.
Test passed.

由于这是Django项目的一部分,需要访问所有适当的变量,并设置manage.py,因此我还可以通过修改后的命令运行它,该命令使用code.InteractiveConsole,其中一个结果是 __name__设置为' __console__'。
通过上面的代码,我得到了与iPython相同的结果。I tried changing the last line to this:
 this = __import__(__name__)
doctest.testmod(this, verbose=True)

我对 __console__有点担心,我想这是有道理的。这对python或ipython都没有影响。
所以,我希望能够通过这三种方法成功地运行doctests,特别是InteractiveConsole方法,因为我希望很快就需要Django-pony magic。
为了澄清,这就是我所期待的:
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.

最佳答案

以下工作:

$ ipython
...
In [1]: %run file.py

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.

In [2]:

我不知道为什么 ipython file.py不起作用。但以上至少是一个解决办法。
编辑:
我找到了它不起作用的原因。很简单:
如果未指定要在 doctest.testmod()中测试的模块,则假定要测试 __main__模块。
当IPython在命令行上执行传递给它的文件时, __main__模块是IPython的 __main__,而不是您的模块。所以doctest试图在IPython的入口脚本中执行doctest。
The following works, but feels a bit weird:
if __name__ == '__main__':
import doctest
import the_current_module
doctest.testmod(the_current_module)

所以基本上模块是自己导入的(这就是“感觉有点奇怪”的部分)。但它起作用了。我不喜欢abt。这种方法是每个模块都需要在源代码中包含自己的名称。
编辑2:
The following script, ipython_doctest, makes ipython behave the way you want:
#! /usr/bin/env bash

echo "__IP.magic_run(\"$1\")" > __ipython_run.py
ipython __ipython_run.py


例子:
$ ./ipython_doctest file.py
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.
Python 2.5 (r25:51908, Mar 7 2008, 03:27:42)
Type "copyright", "credits" or "license" for more information.

IPython 0.9.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]:

关于python - 通过iPython和伪控制台运行doctest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1336980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com