File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2828 bytes that occupy space in the buffer.
2929- There's a simple test set (see end of this file).
3030"""
31-
31+ import types
3232try :
3333 from errno import EINVAL
3434except ImportError :
3838
3939class StringIO :
4040 def __init__ (self , buf = '' ):
41- # Force self.buf to be a string
42- self .buf = str (buf )
41+ # Force self.buf to be a string or unicode
42+ if type (buf ) is not types .UnicodeType :
43+ buf = str (buf )
44+ self .buf = buf
4345 self .len = len (buf )
4446 self .buflist = []
4547 self .pos = 0
@@ -135,8 +137,9 @@ def write(self, s):
135137 if self .closed :
136138 raise ValueError , "I/O operation on closed file"
137139 if not s : return
138- # Force s to be a string
139- s = str (s )
140+ # Force s to be a string or unicode
141+ if type (s ) is not types .UnicodeType :
142+ s = str (s )
140143 if self .pos > self .len :
141144 self .buflist .append ('\0 ' * (self .pos - self .len ))
142145 self .len = self .pos
Original file line number Diff line number Diff line change @@ -71,6 +71,21 @@ def test_iterator(self):
7171class TestStringIO (TestGenericStringIO ):
7272 MODULE = StringIO
7373
74+ def test_unicode (self ):
75+
76+ # The StringIO module also supports concatenating Unicode
77+ # snippets to larger Unicode strings. This is tested by this
78+ # method. Note that cStringIO does not support this extension.
79+
80+ f = self .MODULE .StringIO ()
81+ f .write (self ._line [:6 ])
82+ f .seek (3 )
83+ f .write (unicode (self ._line [20 :26 ]))
84+ f .write (unicode (self ._line [52 ]))
85+ s = f .getvalue ()
86+ self .assertEqual (s , unicode ('abcuvwxyz!' ))
87+ self .assertEqual (type (s ), types .UnicodeType )
88+
7489class TestcStringIO (TestGenericStringIO ):
7590 MODULE = cStringIO
7691
You can’t perform that action at this time.
0 commit comments