Python Doctest 默认命名空间

7

在我的模块的 doctest 中,我希望使用完整的命名空间来引用我的模块,例如:

  hp.myfunc(1)

我希望避免在doctest中写入冗杂的内容:

  import healpy as hp

在每个doctest中。

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

是否还有其他标准方式可以同时适用于两者?

2个回答

3

您是如何运行文档测试的(不使用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

如果我尝试在“mypackage”目录中运行doctest,我会收到一个错误(我怀疑这就是你的情况)。
最后,我不认为这会有什么区别,但我正在运行Python 2.7.2。

感谢您的答复,我希望避免在每个doctest开头写入“import mypackage.mod”。因此,我正在寻找一种标准方法来自动导入它,而不是使用全局或nose特定的设置函数。 - Andrea Zonca
我的问题的答案似乎是没有标准方法可以修改所有doctest的命名空间,这将适用于不同的测试运行程序。因此,唯一的方法是在每个doctest之前编写添加import。所以我接受并授予了这个答案。 - Andrea Zonca
@Andrea,谢谢……很抱歉听到你没有找到更好的答案。除了“无法完成”,这个问题可能最好的解决方案是编写一个nose插件,在运行文档测试时填充全局变量……不过我不确定其中涉及的工作量。 - Adam Wagner
不,目的是要有一个标准化的东西。如果使用nose插件,那么我就必须要打包一个插件。 - Andrea Zonca

2
我不知道鼻子,但是你可以在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}

谢谢,但正如我在问题中所写的那样,我已经知道可以使用通配符,并且我不想每次运行测试时都指定它,而且使用nose也行不通。 - Andrea Zonca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接