python doctest默认名称空间
在模块的doctests中,我希望使用完整名称空间引用模块,例如:python doctest默认名称空间,python,nose,doctest,Python,Nose,Doctest,在模块的doctests中,我希望使用完整名称空间引用模块,例如: hp.myfunc(1) 我想通过写以下内容来避免博士论文的混乱: import healpy as hp 在每一位博士中 如果我运行doctest.testmod,我知道我可以使用globs关键字来提供此功能,而如果我运行nose,我可以使用setup功能 有没有另一种标准方法可以同时使用这两种方法?您是如何运行doctests的(就是说,没有鼻子)?如果您在尝试运行包目录时将其光盘刻录到包目录中,则会遇到问题(即
hp.myfunc(1)
我想通过写以下内容来避免博士论文的混乱:
import healpy as hp
在每一位博士中
如果我运行doctest.testmod,我知道我可以使用globs
关键字来提供此功能,而如果我运行nose,我可以使用setup
功能
有没有另一种标准方法可以同时使用这两种方法?您是如何运行doctests的(就是说,没有鼻子)?如果您在尝试运行包目录时将其光盘刻录到包目录中,则会遇到问题(即,如果您正在进行完全导入) 我能够使用nosetest和内置的doctestrunner运行一个简单的doctest(带有完全合格的导入)。以下是我的设置: 项目结构:
.
└── mypackage
├── __init__.py
└── mod.py
以下是我的'mod.py'文件的内容:
"""foo() providing module
Example:
>>> import mypackage.mod
>>> mypackage.mod.foo()
'bar'
"""
def foo():
return "bar"
从“.”目录(项目根目录)中,我现在可以运行测试:
$ python -m doctest -v mypackage/*.py
1 items had no tests:
__init__
0 tests in 1 items.
0 passed and 0 failed.
Test passed.
Trying:
import mypackage.mod
Expecting nothing
ok
Trying:
mypackage.mod.foo()
Expecting:
'bar'
ok
1 items had no tests:
mod.foo
1 items passed all tests:
2 tests in mod
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
现在是鼻子测试:
$ nosetests --with-doctest
.
----------------------------------------------------------------------
Ran 1 test in 0.008s
OK
如果我试图从“mypackage”目录中运行doctest,我会得到一个错误(我怀疑,这就是您的情况)
最后,我不认为这有什么区别,但是我正在运行Python 2.7.2,我不知道nose,但是您可以使用
testmod()
和testfile()
中的globs
参数
这里有一个简单的模块(称为foobar.py),请注意,我没有导入os
:
#!/usr/bin/python
"""
>>> os.pipe
<built-in function pipe>
"""
谢谢你的回答,我想避免在每个doctest的开头写“importmypackage.mod”。因此,我正在寻找一种标准的方法来自动导入它,而不是使用globs或特定于nose的设置函数。我的问题的答案似乎是,没有标准的方法来修改所有doctest的名称空间,而这些名称空间可以与不同的测试运行程序一起工作。因此,唯一的方法是在每个doctest之前编写并添加
import
。所以我接受并奖励了这个答案。@Andrea,谢谢。。。很遗憾听到你没有找到更好的答案。除了“它不可能完成”之外,最好的解决方案可能是为nose编写一个插件,在它运行文档测试时填充globs。。。不过,我不确定这其中涉及的工作。不,目的是要有一些标准的东西。如果有一个用于nose的插件,那么我必须提供一个插件。谢谢,但正如我在问题中所写的,我知道我已经可以使用globs了,我不想每次运行测试时都指定它,而且,使用nose它也不起作用。
$ python2.7
Python 2.7.2 (default, Jun 29 2011, 11:10:00)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import doctest, foobar
2
>>> doctest.testmod(foobar) ## will fail as expected because os has not been imported
**********************************************************************
File "foobar.py", line 2, in foobar
Failed example:
os.pipe
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest foobar[0]>", line 1, in <module>
os.pipe
NameError: name 'os' is not defined
**********************************************************************
1 items had failures:
1 of 1 in foobar
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=1)
>>> import os
>>> globs = {'os': os}
>>> doctest.testmod(foobar, globs=globs)
TestResults(failed=0, attempted=1)
>>> # Win :)
globs = {'hp': healp}