Python: accept unicode strings as regular strings in doctests

依然范特西╮ 提交于 2019-12-10 04:34:02

问题


Writing doctests for a method that abbreviates a dictionary by searching for a passed key word in the keys of the original dictionary, and returning the new, abbreviated dictionary. My docstring looks as follows:

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

The function works, but when I run py.test's doctest, the function fails the test as it returns the strings as unicode. I do not programmatically switch the strings to unicode in my function, but I am aware that python 2.7 returns in unicode.

Expected:
    {'cores': 5, 'seeds': 3, 'stems': 2}
Got:
    {u'cores': 5, u'seeds': 3, u'stems': 2}

How can I can I get the doctest to acknowledge that unicode and regular string outputs are the same?


回答1:


You can set the ALLOW_UNICODE flag (either globally or per test), see the pytest docs for details.

Example:

[pytest]
doctest_optionflags = ALLOW_UNICODE

or

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


来源:https://stackoverflow.com/questions/37975197/python-accept-unicode-strings-as-regular-strings-in-doctests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!