Niten 的版本inside_doctest
似乎过于宽泛。重新定义 并不少见sys.stdout
,无论是用于日志记录还是在 doctest 以外的框架中进行测试时,都会产生误报。
更窄的测试如下所示:
import sys
def in_doctest():
"""
Determined by observation
"""
if '_pytest.doctest' in sys.modules:
return True
##
if hasattr(sys.modules['__main__'], '_SpoofOut'):
return True
##
if sys.modules['__main__'].__dict__.get('__file__', '').endswith('/pytest'):
return True
##
return False
def test():
"""
>>> print 'inside comments, running in doctest?', in_doctest()
inside comments, running in doctest? True
"""
print 'outside comments, running in doctest?', in_doctest()
if __name__ == '__main__':
test()
in_doctest
测试_SpoofOut
类 doctest 用于替换sys.stdout
. doctest 模块的其他属性可以以相同的方式进行验证。并不是说您可以阻止另一个模块重用名称,但是这个名称并不常见,因此可能是一个不错的测试。
将上面的内容放在 test.py 中。在非 doctest 模式下运行它,python test.py
产生:
outside comments, running in doctest? False
在 doctest 详细模式下运行,python -m doctest test.py -v
产生:
Trying:
print 'inside comments, running in doctest?', in_doctest()
Expecting:
inside comments, running in doctest? True
ok
我同意其他人的评论,即让代码了解 doctest 通常是一个坏主意。我只是在有些奇怪的情况下才这样做——当我需要通过代码生成器创建测试用例时,因为有太多无法有效地手动制作。但是如果你需要这样做,上面是一个不错的测试。