Doc扩展在C-extension和Python3上使用UnicodeDecodeError失败

Set*_*ton 5 python doctest python-c-extension python-3.x

我很难让我的测试框架适用于Python2和Python3的C扩展模块.我喜欢运行我的文档字符串doctest以确保我没有向用户提供不良信息,所以我想在doctest测试中运行.

我不相信我的问题的根源是文档字符串本身,而是doctest模块如何尝试读取我的扩展模块.如果我运行doctestPython2(在针对Python2编译的模块上),我得到了我期望的输出:

$ python -m doctest myext.so -v
...
1 items passed all tests:
98 tests in myext.so
98 tests in 1 items.
98 passed and 0 failed.
Test passed.
Run Code Online (Sandbox Code Playgroud)

但是,当我使用Python3时,我得到了一个UnicodeDecodeError:

$ python3 -m doctest myext3.so -v
Traceback (most recent call last):
...
  File "/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/doctest.py", line 223, in _load_testfile
    return f.read(), filename
  File "/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/codecs.py", line 301, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte
Run Code Online (Sandbox Code Playgroud)

为了获得更多信息,我通过pytest完整的追溯来完成它:

$ python3 -m pytest --doctest-glob "*.so" --full-trace
...
self = <encodings.utf_8.IncrementalDecoder object at 0x102ff5110>
input = b'\xcf\xfa\xed\xfe\x07\x00\x00\x01\x03\x00\x00\x00\x08\x00\x00\x00\r\x00\x00\x00\xd0\x05\x00\x00\x85\x00\x00\x00\x00\x...edString\x00_PyUnicode_FromString\x00_Py_BuildValue\x00__Py_FalseStruct\x00__Py_TrueStruct\x00dyld_stub_binder\x00\x00'
final = True

    def decode(self, input, final=False):
        # decode input (taking the buffer into account)
        data = self.buffer + input
>       (result, consumed) = self._buffer_decode(data, self.errors, final)
E       UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte

/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/codecs.py:301: UnicodeDecodeError    
Run Code Online (Sandbox Code Playgroud)

它看起来像doctest实际读取.so文件,以获取文档字符串(而不是导入模块),但Python3不知道如何将输入解码.我可以通过尝试自己读取.so文件来复制字节字符串和回溯来确认这一点:

$ python3
Python 3.3.3 (default, Dec 10 2013, 20:13:18) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> open('myext3.so').read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/codecs.py", line 301, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte
>>> open('myext3.so', 'rb').read()
b'\xcf\xfa\xed\xfe\x07\x00\x00\x01\x03\x00\x00\x00\x08\x00\x00\x00\r\x00\x00\x00\xd0\x05...'
Run Code Online (Sandbox Code Playgroud)

有没有其他人遇到过这个问题?是否有标准(或不那么标准)的方式来doctest在python3上执行C扩展模块的测试?

更新:我还应该补充一点,我在Travis-CI上看到相同的结果(见这里),所以它并不特定于我的本地构建.

Set*_*ton 3

我已经找到了解决此问题的方法,因此我将其发布,但我发现它相当不令人满意。我仍在寻找更优雅/更少的解决方案。


要使这项工作成功,需要克服三个问题:doctest.py

1) 获取 doctest 将 .so 文件视为 python 模块。

如果您查看doctest.py源代码,您会注意到测试运行程序中有一个与此类似的块(取决于您正在运行的 python 版本):

if filename.endswith(".py"):
    # It is a module -- insert its dir into sys.path and try to
    # import it. If it is part of a package, that possibly
    # won't work because of package imports.
    dirname, filename = os.path.split(filename)
    sys.path.insert(0, dirname)
    m = __import__(filename[:-3])
    del sys.path[0]
    failures, _ = testmod(m)
else:
    failures, _ = testfile(filename, module_relative=False)
Run Code Online (Sandbox Code Playgroud)

这里发生的是doctest.py检查“.py”扩展名,如果是,则文件作为 python 模块加载,否则文件将被读取为文本(如 README.rst 可能是)。我们需要承认doctest.py扩展名为“.so”的文件是一个Python模块。为此,只需将此if块修改为读取来添加对“.so”扩展名的检查

if filename.endswith(".py") or filename.endswith(".so"):
    ...
Run Code Online (Sandbox Code Playgroud)

2)获取doctest来识别C扩展模块中的函数

doctest.py在模块对象中递归搜索文档字符串时,使用inspect.isfunction函数来确定哪些对象是函数。这个函数的问题是它只识别用 python 编写的函数,而不是用 C 编写的函数(python 将 C 扩展函数识别为内置函数)。因此,为了在递归模块时识别我们的函数,我们需要使用inspect.isbuiltin

为了纠正这个问题,我们需要找到该DocTestFinder._find方法doctest.py并更改它查找函数的方式。我转换了

# Recurse to functions & classes.
if ((inspect.isfunction(val) or inspect.isclass(val)) and
    self._from_module(module, val)):
    self._find(tests, val, valname, module, source_lines,
               globs, seen)
Run Code Online (Sandbox Code Playgroud)

# Recurse to functions & classes.
if ((inspect.isbuiltin(val) or inspect.isclass(val)) and
    self._from_module(module, val)):
    self._find(tests, val, valname, module, source_lines,
               globs, seen)
Run Code Online (Sandbox Code Playgroud)

3) 正确删除.so文件上的版本标签(仅限Python3)。

在 Python3 上,C 扩展可以使用版本标识符进行标记(即“myext.cpython-3mu.so”,请参阅PEP 3149)。我们需要知道在测试运行器中进行初始导入时如何删除它doctest.py

为此,我转换了该行

m = __import__(filename[:-3])
Run Code Online (Sandbox Code Playgroud)

from sysconfig import get_config_var
m = __import__(filename[:-3] if filename.endswith(".py") else filename.replace(get_config_var("EXT_SUFFIX"), ""))
Run Code Online (Sandbox Code Playgroud)

仅 Python3 需要此功能。


进行这些修改后,我可以让 doctest 在 Python2 和 Python3 上按预期工作。由于这些修改相当烦人,因此我制作了一个patch_doctest.py脚本来自动执行此操作并将修补后的内容放在doctest.py当前目录中。如果您想使用该文件,可以在此处获取该文件。然后您可以像这样在扩展模块上运行测试

$ python2 patch_doctest.py
$ python2 -m doctest myext2.so
$ rm doctest.py
$ python3 patch_doctest.py
$ python3 -m doctest myext3.so
Run Code Online (Sandbox Code Playgroud)

作为这一方法有效的证据,以下是新的 Travis-CI 结果