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

Viewed 224

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 Answers

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

Related