python doctest 默认命名空间

7 投票
2 回答
987 浏览
提问于 2025-04-17 03:50

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

  hp.myfunc(1)

而且我希望避免在每个测试文档中都写:

  import healpy as hp

这样会让测试文档显得很乱。

如果我运行 doctest.testmod,我知道可以用 globs 这个关键词来提供这个命名空间,而如果我用 nose 运行,就可以用 setup 函数。

有没有其他标准的方法可以同时适用于这两种情况呢?

2 个回答

2

我不太了解nose,但你可以在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}
3

你是怎么运行这些文档测试的(不使用nose的情况下)?如果你在尝试运行测试时已经进入了包的目录,这样做可能会遇到问题(前提是你在进行完整导入)。

我成功地用nosetests和内置的文档测试运行器运行了一个简单的文档测试(使用了完全限定的导入)。这是我的设置:

项目结构:

.
└── 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

如果我尝试在'mypackage'目录中运行文档测试,我会遇到错误(我怀疑这就是你遇到的问题)。

最后,我觉得这应该没有影响,但我使用的是Python 2.7.2。

撰写回答