Python:在doctests中接受unicode字符串作为常规字符串

af3*_*3ld 6 python testing doctest pytest python-2.7

编写doctests,用于通过在原始字典的键中搜索传递的关键字来缩写字典,并返回新的缩写字典.我的docstring看起来如下:

def abbreviate_dict(key_word, original_dict):
    """
    >>> orig_dict = {apple_stems: 2, apple_cores: 5, apple_seeds: 3}
    >>> abbreviate_dict('apple', orig_dict)
    {'cores': 5, 'seeds': 3, 'stems': 2}
    """
   etc.
   return new_dict
Run Code Online (Sandbox Code Playgroud)

该函数有效,但是当我运行py.test的doctest时,该函数未通过测试,因为它将字符串作为unicode返回.我没有以编程方式将字符串切换到我的函数中的unicode,但我知道python 2.7在unicode中返回.

Expected:
    {'cores': 5, 'seeds': 3, 'stems': 2}
Got:
    {u'cores': 5, u'seeds': 3, u'stems': 2}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得doctest以确认unicode和常规字符串输出是否相同?

The*_*ler 6

您可以设置ALLOW_UNICODE标志(全局或每次测试),有关详细信息,请参阅pytest文档.

例:

[pytest]
doctest_optionflags = ALLOW_UNICODE
Run Code Online (Sandbox Code Playgroud)

要么

# content of example.rst
>>> get_unicode_greeting()  # doctest: +ALLOW_UNICODE
'Hello'
Run Code Online (Sandbox Code Playgroud)