【发布时间】:2017-06-28 18:19:06
【问题描述】:
考虑以下演示脚本:
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
def myDivi():
"""
This is a small demo that just returns the output of a divison.
>>> myDivi()
0.5
"""
return 1/2
def myUnic():
"""
This is a small demo that just returns a string.
>>> myUnic()
'abc'
"""
return 'abc'
if __name__ == "__main__":
import doctest
extraglobs = {}
doctest.testmod(extraglobs=extraglobs)
doctest 在 Python 3.5 上通过,但在 Python 2.7.9 上失败。
奇怪的是,除法测试有效,但 unicode 测试失败。
我看过各种问题,包括以下问题
- Multi version support for Python doctests
- Doctest not recognizing __future__.division
- Python: accept unicode strings as regular strings in doctests
- Python doctests and unicode
- Doctest fails due to unicode leading u
但它们都有些不同(例如,它们已过时(指 Py 2.6 或 Py 3.0),import 语句在 doctest 中而不是全局范围内,使用 pytest 而不是标准 doctest,切换到不同的 assert 等)
尽管如此,我还是根据这些问题尝试了各种替代方案,包括例如
if __name__ == "__main__":
import doctest
import __future__
extraglobs = {'unicode_literals': __future__.unicode_literals}
doctest.testmod(extraglobs=extraglobs)
或
def myUnic():
"""
This is a small demo that just returns a string.
>>> myUnic()
u'abc' # doctest: +ALLOW_UNICODE
"""
return 'abc'
但它仍然无法正常工作,无论是在 Python 2 还是 3 上,或者出现其他错误。
有没有办法让它在 3.5+ 和 2.7.9+ 上都通过,而没有丑陋的黑客?
我也使用这些文档字符串来生成文档,所以我希望它们或多或少保持原样。
【问题讨论】:
-
pytest 有一个用于 doctests 的
ALLOW_UNICODE选项。见docs.pytest.org/en/latest/doctest.html#using-doctest-options(谢谢stackoverflow.com/a/55937187/2747370!) -
我已经尝试过了,请参阅问题中的最后一个代码 sn-p 并没有按预期工作。
-
您是否通过
pytest运行您的文档测试?还是直接用doctest?我相信ALLOW_UNICODE只能通过pytest获得。
标签: python-3.x python-2.x doctest unicode-literals