Python:在 doctests 中接受 unicode 字符串作为常规字符串 [英] Python: accept unicode strings as regular strings in doctests

查看:65
本文介绍了Python:在 doctests 中接受 unicode 字符串作为常规字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为通过在原始字典的键中搜索传递的关键字并返回新的缩写字典来缩写字典的方法编写文档测试.我的文档字符串如下所示:

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

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

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}

我怎样才能让 doctest 确认 unicode 和常规字符串输出相同?

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

推荐答案

您可以设置 ALLOW_UNICODE 标志(全局或每个测试),请参阅 pytest 文档 了解详情.

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

示例:

[pytest]
doctest_optionflags = ALLOW_UNICODE

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

这篇关于Python:在 doctests 中接受 unicode 字符串作为常规字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆