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?
The io package provides python3.x compatibility. In python 3, strings are unicode by default.
Your code works fine with the standard StringIO package,
If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.