Doctests, Unicode and Python3

59 views
Skip to first unread message

Waylan Limberg

unread,
Jul 29, 2011, 12:51:18 AM7/29/11
to nose-users
A doctest with unicode output in Python 2 looks like this:

>>> unicode("foo")
u"foo"

But in Python 3, all strings are unicode so that little `u` in front
of the expected output causes the test to fail. Additionally,
apparently the 2to3 tool can't (and doesn't) modify the output line.
After some searching I've found that the python devs discussed this
and came to the conclusion found here:

http://www.mail-archive.com/pytho...@python.org/msg46171.html

I'm trying to implement something of the sort into nose, but am
running into all sorts of weird problems. I'v tried monkeypatching
`nose.plugins.doctests.DocTestCase._displayhook` but I keep running
into weird errors with my subclass.

So far I have:

class Py3DocTestCase(nose.plugins.doctests.DocTestCase):
""" Ensure unicode output in doctests pass in Python 3. """

def __init__(self, test, optionflags=0, setUp=None,
tearDown=None,
checker=None, obj=None, result_var='_'):
""" Reimplement __init__ to avoid max recursion with
nested super() calls. """
self._result_var = result_var
self._nose_obj = obj
doctest.DocTestCase.__init__(self,
test, optionflags=optionflags, setUp=setUp,
tearDown=tearDown,
checker=checker)

def _displayhook(self, value):
if value is None:
return
setattr(builtin_mod, self._result_var, value)
s = repr(value)
if not isinstance(value, unicode):
# Old behavior
print s
else:
# new behavior
if s.startswith(("u'", 'u"')):
s = s[1:]
print s

if sys.version_info >= (3, 0):
# Monkeypatch Nose
nose.plugins.doctests.DocTestCase = Py3DocTestCase

That gives me this weird error:

File "/opt/python3.2/lib/python3.2/site-packages/nose/plugins/
doctests.py", line 374, in shortDescription
return 'Doctest: %s' % self.id()
File "/opt/python3.2/lib/python3.2/site-packages/nose/plugins/
doctests.py", line 359, in id
name = self._dt_test.name
AttributeError: 'str' object has no attribute 'name'

Any suggestions?
Reply all
Reply to author
Forward
0 new messages