对 Python doctests 的多版本支持 [英] Multi version support for Python doctests
问题描述
我正在像这样编写我的文档测试:
<预><代码>>>>some_function(a=1, b=2){u'id': u'123', u'name': u'abc'}这适用于 Python 版本 2.5、2.6 &2.7 但对于 Python 3 失败并出现以下错误:
预期:{u'id': u'123', u'name': u'abc'}得到了:{'id': '123', 'name': 'abc'}
问题是,如果我像这样编写我的文档测试:
<预><代码>>>>some_function(a=1, b=2){'id': '123', 'name': 'abc'}它们仅适用于 Python3 并且在 Python2 版本上失败.我的问题是如何使其跨版本兼容?
我在使用 IPython 中的 doctests 时遇到了同样的问题.没有简洁的解决方案,但我将所有的 u'
前缀包裹在 {}
中,即 {u}'
,并做了一个小功能将酌情包括或排除它们.
您可以看到u_format() 函数和
但这相当混乱,所以我已经将许多测试从 doctests 移开.
或者,您可以这样测试:
<预><代码>>>>some_function(a=1, b=2) == {'id': '123', 'name': 'abc'}真的如果你需要一些 unicode 字符串在键中,你可以使用 u'abþ'
,并使用分发在 doctests 上运行 2to3
.但这仅适用于输入代码,不适用于输出代表.
I am writing my doctests like this:
>>> some_function(a=1, b=2)
{u'id': u'123', u'name': u'abc'}
This works fine for Python version 2.5, 2.6 & 2.7 but fails for Python 3 with following error:
Expected:
{u'id': u'123', u'name': u'abc'}
Got:
{'id': '123', 'name': 'abc'}
Problem is that if I write my doctests like this:
>>> some_function(a=1, b=2)
{'id': '123', 'name': 'abc'}
They will work only for Python3 and fail on Python2 version. My question is how do I make it cross version compatible?
I ran into the same problem with doctests in IPython. There's no neat solution, but I wrapped all of the u'
prefixes in {}
, i.e. {u}'
, and made a little function that would include or exclude them as appropriate.
You can see the u_format() function and a doctest using it.
But that's rather messy, so I've moved many tests away from doctests.
Alternatively, you can test it like this:
>>> some_function(a=1, b=2) == {'id': '123', 'name': 'abc'}
True
If you need some unicode strings in the keys, you can use u'abþ'
, and use distribute to run 2to3
on the doctests. But that only works on input code, not output reprs.
这篇关于对 Python doctests 的多版本支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!