How can I make doctests triggered by pytest ignore unicode prefix `u'…'` of strings?

与世无争的帅哥 提交于 2019-12-23 21:07:23

问题


I want my code to work in Python 2 and 3. I use doctests and

from __future__ import unicode_literals

Is there a flag I can set / a plugin which makes it ignore that Python 2 has the u prefix for unicode strings?

Example

One test that works in Python 3, but fails in Python 2:

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

Minimal example

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()

回答1:


If you're using doctest directly, you can override the OutputChecker as per Dirkjan Ochtman's blog post Single-source Python 2/3 doctests:

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())

If you're using py.test, you can specify doctest_optionflags = ALLOW_UNICODE in pytest.ini. See https://docs.pytest.org/en/latest/doctest.html



来源:https://stackoverflow.com/questions/46465422/how-can-i-make-doctests-triggered-by-pytest-ignore-unicode-prefix-u-of-st

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