Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unicode problems when using io.StringIO to mock a file

I am using an io.StringIO object to mock a file in a unit-test for a class. The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings:

>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream

But

>>> buffer.write(str((1, 2)) + u"")
6

works. I assume this is because the concatenation with a unicode string makes the result unicode as well. Is there a more elegant solution to this problem?

like image 354
Björn Pollex Avatar asked Sep 20 '10 07:09

Björn Pollex


1 Answers

The io package provides python3.x compatibility. In python 3, strings are unicode by default.

Your code works fine with the standard StringIO package,

>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>

If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.

>>> io.StringIO().write(unicode((1,2)))
6
like image 81
Ivo van der Wijk Avatar answered Sep 22 '22 01:09

Ivo van der Wijk