# Tests StringIO and cStringIO
from test
import test_support
class TestGenericStringIO(unittest
.TestCase
):
# use a class variable MODULE to define which module is being tested
# Line of data to test as string
_line
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!'
# Constructor to use for the test data (._line is passed to this
self
._line
= self
.constructor(self
._line
)
self
._lines
= self
.constructor((self
._line
+ '\n') * 5)
self
._fp
= self
.MODULE
.StringIO(self
._lines
)
self
.assertRaises(TypeError, self
._fp
.seek
)
eq(self
._fp
.read(10), self
._line
[:10])
eq(self
._fp
.readline(), self
._line
[10:] + '\n')
eq(len(self
._fp
.readlines(60)), 2)
f
= self
.MODULE
.StringIO()
self
.assertRaises(TypeError, f
.seek
)
f
.write(self
._line
[20:26])
self
.assertEqual(f
.getvalue(), 'abcuvwxyz!')
def test_writelines(self
):
f
= self
.MODULE
.StringIO()
f
.writelines([self
._line
[0], self
._line
[1], self
._line
[2]])
self
.assertEqual(f
.getvalue(), 'abc')
def test_writelines_error(self
):
raise KeyboardInterrupt()
f
= self
.MODULE
.StringIO()
self
.assertRaises(KeyboardInterrupt, f
.writelines
, errorGen())
f
= self
.MODULE
.StringIO()
eq(f
.getvalue(), 'abcdefghij')
eq(f
.getvalue(), 'abcde')
eq(f
.getvalue(), 'abcdexyz')
self
.assertRaises(ValueError, f
.write
, 'frobnitz')
def test_closed_flag(self
):
f
= self
.MODULE
.StringIO()
self
.assertEqual(f
.closed
, False)
self
.assertEqual(f
.closed
, True)
f
= self
.MODULE
.StringIO("abc")
self
.assertEqual(f
.closed
, False)
self
.assertEqual(f
.closed
, True)
eq(iter(self
._fp
), self
._fp
)
# Does this object support the iteration protocol?
unless(hasattr(self
._fp
, '__iter__'))
unless(hasattr(self
._fp
, 'next'))
eq(line
, self
._line
+ '\n')
class TestStringIO(TestGenericStringIO
):
if not test_support
.have_unicode
: return
# The StringIO module also supports concatenating Unicode
# snippets to larger Unicode strings. This is tested by this
# method. Note that cStringIO does not support this extension.
f
= self
.MODULE
.StringIO()
f
.write(unicode(self
._line
[20:26]))
f
.write(unicode(self
._line
[52]))
self
.assertEqual(s
, unicode('abcuvwxyz!'))
self
.assertEqual(type(s
), types
.UnicodeType
)
class TestcStringIO(TestGenericStringIO
):
if sys
.platform
.startswith('java'):
# Jython doesn't have a buffer object, so we just do a useless
# fake of the buffer tests.
class TestBufferStringIO(TestStringIO
):
class TestBuffercStringIO(TestcStringIO
):
test_support
.run_unittest(
if __name__
== '__main__':