7

在我的模块的文档测试中,我想用完整的命名空间引用我的模块,例如:

  hp.myfunc(1)

而且我想通过编写避免使文档测试混乱:

  import healpy as hp

在每个文档测试中。

如果我运行 doctest.testmod,我知道我可以使用globs关键字来提供这个,而如果我运行nose,我可以使用该setup功能。

是否有另一种可以同时使用的标准方法?

4

2 回答 2

3

你是如何运行文档测试的(没有鼻子,也就是说)?如果您在尝试运行它们时被 cd 到包目录中,您将遇到问题(如果您正在执行完整导入,即)。

我能够使用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 --with-doctest
.
----------------------------------------------------------------------
Ran 1 test in 0.008s

OK

如果我尝试从 'mypackage' 目录中运行 doctest,我会收到一个错误(我怀疑这是你的情况)。

最后,我认为这不会有什么不同,但我正在运行 Python 2.7.2

于 2011-10-14T01:43:33.220 回答
2

我不知道鼻子,但你可以使用and中的globs参数。testmod()testfile()

这是一个简单的模块(称为 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}
于 2011-10-28T11:46:03.227 回答