如何通过pytest触发doctests忽略字符串的unicode前缀`u'...'`

问题描述 投票:2回答:1

我希望我的代码在Python 2和3中工作。我使用doctests和

from __future__ import unicode_literals

是否有我可以设置的标志/插件使得它忽略了Python 2具有unicode字符串的u前缀?

一个测试适用于Python 3,但在Python 2中失败:

Expected:
    'Me \\& you.'
Got:
    u'Me \\& you.'

最小的例子

from __future__ import unicode_literals


def foo():
    """

    Returns
    -------
    unicode - for Python 2 and Python 3

    Examples
    --------
    >>> foo()
    'bar'
    """
    return 'bar'


if __name__ == '__main__':
    import doctest
    doctest.testmod()
python-2.7 unicode pytest doctest
1个回答
1
投票

如果你直接使用doctest,你可以根据Dirkjan Ochtman的博客文章Single-source Python 2/3 doctests覆盖OutputChecker:

class Py23DocChecker(doctest.OutputChecker):
  def check_output(self, want, got, optionflags):
    if sys.version_info[0] > 2:
      want = re.sub("u'(.*?)'", "'\\1'", want)
      want = re.sub('u"(.*?)"', '"\\1"', want)
    return doctest.OutputChecker.check_output(self, want, got, optionflags)

doctest.DocTestSuite(mod, checker=Py23DocChecker())

如果你正在使用py.test,你可以在pytest.ini中指定doctest_optionflags = ALLOW_UNICODE。见https://docs.pytest.org/en/latest/doctest.html

© www.soinside.com 2019 - 2024. All rights reserved.