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

时间:2016-06-22 17:59:26

标签: python python-2.7 testing pytest doctest

编写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

该函数有效,但是当我运行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}

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

1 个答案:

答案 0 :(得分:6)

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

示例:

[pytest]
doctest_optionflags = ALLOW_UNICODE

# content of example.rst
>>> get_unicode_greeting()  # doctest: +ALLOW_UNICODE
'Hello'
相关问题