以下(废话)Python 模块的 doctest 失败:
"""
>>> L = []
>>> if True:
... append_to(L) # XXX
>>> L
[1]
"""
def append_to(L):
L.append(1)
class A(object):
pass
return A()
import doctest; doctest.testmod()
这是因为标记为 XXX 的行之后的输出是<__main__.A object at ...>
(由 返回append_to
)。当然,我可以将这个输出直接放在标记为 XXX 的行之后,但在我的情况下,这会分散读者对实际测试内容的注意力,即函数的副作用append_to
。那么如何抑制该输出或如何忽略它。我试过了:
"""
>>> L = []
>>> if True:
... append_to(L) # doctest: +ELLIPSIS
...
>>> L
[1]
"""
def append_to(L):
L.append(1)
class A(object):
pass
return A()
import doctest; doctest.testmod()
但是,这会产生一个ValueError: line 4 of the docstring for __main__ has inconsistent leading whitespace: ' ...'
.
我不想做的是将行更改为append_to(L)
会_ = append_to(L)
抑制输出的内容,因为 doctest 用于文档目的,并向读者展示应该如何使用模块。(在记录的情况下,append_to
应该使用类似语句而不是函数。写作_ = append_to(L)
会使读者偏离这一点。)