在我的模块的 doctest 中,我希望使用完整的命名空间来引用我的模块,例如:
hp.myfunc(1)
我希望避免在doctest中写入冗杂的内容:
import healpy as hp
在每个doctest中。
如果我运行doctest.testmod,我知道我可以使用“globs”关键字来提供这个,而如果我运行nose,我可以使用“setup”函数。
是否还有其他标准方式可以同时适用于两者?
您是如何运行文档测试的(不使用nose)? 如果在尝试运行它们时,您进入软件包目录,那么您将遇到问题(如果您正在执行完整导入)。
我能够使用nosetests和内置的doctest运行程序来运行一个简单的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:
$ nosetests --with-doctest
.
----------------------------------------------------------------------
Ran 1 test in 0.008s
OK
testmod()
和testfile()
中使用globs
参数。
这是一个简单的模块(名为foobar.py),请注意我没有导入os
:
#!/usr/bin/python
"""
>>> os.pipe
<built-in function pipe>
"""
$ 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}
import
。所以我接受并授予了这个答案。 - Andrea Zonca