pytest 无法在 Python 2.7 下的 README 中的 doctest 中处理 Unicode



我有一个README.rst文件,其中包含我的Python库的几个文档测试。 它们都可以工作,除了最后一个 doctest,它print的 Unicode 输出,用 UTF-8 编码:

Here is a failing example::
>>> print(u'xE5xE9xEExF8xFC')
åéîøü

(使用print而不仅仅是字符串对我的实际用例非常重要,因为真正的字符串包含嵌入的换行符,我需要展示不同行上的内容是如何对齐的。

运行pytest README.rst可以成功地与 Python 3.6.5 和 pytest 3.6.1 配合使用,但在 Python 2.7.10 下,它失败了,回溯很长,结尾为:

input = 'åéîøü
', errors = 'strict'
def decode(input, errors='strict'):
>       return codecs.utf_8_decode(input, errors, True)
E       UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py:16: UnicodeEncodeError

tox.ini中设置setenv = LC_ALL=en_US.UTF-8并在 tox 下运行不会改变任何内容;在tox.ini[pytest]部分添加doctest_encoding = utf-8也不会改变。 我没有看到与我的困境相关的文档测试选项。 如何让测试在 Python 2.7 下成功运行?

更新:导致此问题的错误已在 pytest 3.6.2 中修复。

是的,print是罪魁祸首。例外中最有趣的部分是:

def getvalue(self):
result = _SpoofOut.getvalue(self)
if encoding:
result = result.decode(encoding)

local/lib/python2.7/site-packages/_pytest/doctest.py:509:

pytest尝试解码Unicode,所以Python首先尝试对其进行编码,但失败了。我认为这是pytest中的一个错误:它应该测试result是字节还是Unicode:

if encoding and isinstance(result, bytes):
result = result.decode(encoding)

请将其报告给pytest问题跟踪器。您可以测试修复程序,如果 作品 您可以发送拉取请求。

最新更新