问题描述
请考虑以下演示脚本:
# -*- 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上失败.
奇怪的是,divison测试有效,但是unicode测试失败.
The doctest passes on Python 3.5, but fails on Python 2.7.9.
The strange thing is, the divison test works, but the unicode test fails.
我看到了各种问题,包括以下问题
I have seen various questions, including the following
- 对Python doctest的多版本支持
- Doctest无法识别__future __.division
- Python:接受unicode字符串作为doctests中的常规字符串
- Python doctest和unicode
- 由于unicode导致u doctest失败
- 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等).
尽管如此,我还是根据这些问题尝试了多种选择,例如
but they are all somewhat different (e.g. they are outdated (referring to Py 2.6 or Py 3.0), import statement is within the doctest instead of globally, use pytest instead of standard doctest, switch to different assert etc)
Still, I tried various alternatives based on these questions, including e.g.
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+上都通过,而又没有丑陋的骇客?我还在使用这些文档字符串来生成文档,因此我希望保留它们的大小不变.
but it still does not work, either on Python 2 or 3 or gives other errors.
Is there a way to make it pass on both 3.5+ AND 2.7.9+, without ugly hacks?I am also using these docstrings for generating documentation, so I would prefer to keep them more or less as they are.
推荐答案
与Martijn Pieters达成的协议对Python doctests的多版本支持,我建议使用某些 real 单元测试框架进行测试.
In agreement with Martijn Pieters comments in Multi version support for Python doctests, I suggest to rely on testing using some real unit test framework.
您仍然可以使用doctest字符串,因为它们可能对文档很有用.考虑未来,并为Python 3编写它们.同时,为另一个单元测试框架编写单元测试.不要将doctest
用于您的应用程序/模块的Python 2版本.
You may still use the doctest strings, because they may be nice for documentation. Think for the future, and write them for Python 3. The same time, write unit tests for another unit-testing framework. Do not rely on doctest
for Python 2 version of your application/module.
这篇关于Python 2.7和Python 3.5中的unicode_literals和doctest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!