def test_truncate(): s = u"1234567890" sio = StringIO(s) raises(ValueError, sio.truncate, -1) sio.seek(6) res = sio.truncate() assert res == 6 assert sio.getvalue() == s[:6] res = sio.truncate(4) assert res == 4 assert sio.getvalue() == s[:4] # truncate() accepts long objects res = sio.truncate(4L) assert res == 4 assert sio.getvalue() == s[:4] assert sio.tell() == 6 sio.seek(0, 2) sio.write(s) assert sio.getvalue() == s[:4] + s pos = sio.tell() res = sio.truncate(None) assert res == pos assert sio.tell() == pos raises(TypeError, sio.truncate, '0') sio.close() raises(ValueError, sio.truncate, 0)
def test_tell(): s = u"1234567890" sio = StringIO(s) assert sio.tell() == 0 sio.seek(5) assert sio.tell() == 5 sio.seek(10000) assert sio.tell() == 10000 sio.close() raises(ValueError, sio.tell)
def test_roundtrip_translation(): sio1 = StringIO(u'a\nb', newline='\r\n') pos = sio1.seek(1) assert sio1.getvalue() == u'a\r\nb' state = sio1.__getstate__() sio2 = StringIO() sio2.__setstate__(state) assert sio2.getvalue() == u'a\r\nb' assert sio2.tell() == pos
def test_roundtrip_state(): s = u'12345678' sio1 = StringIO(s) sio1.foo = 42 sio1.seek(2) assert sio1.getvalue() == s state = sio1.__getstate__() sio2 = StringIO() sio2.__setstate__(state) assert sio2.getvalue() == s assert sio2.foo == 42 assert sio2.tell() == 2
def test_overseek(): s = u"1234567890" sio = StringIO(s) res = sio.seek(11) assert res == 11 res = sio.read() assert res == u"" assert sio.tell() == 11 assert sio.getvalue() == s sio.write(u"") assert sio.getvalue() == s sio.write(s) assert sio.getvalue() == s + u"\0" + s
# File : summary_StringIO.py # Software: PyCharm try: from _io import StringIO except ImportError: from io import StringIO f = StringIO() f.write('hello world!!!') print(f.getvalue(), len(f.getvalue())) f.write('hello world!!!') print(f.getvalue(), len(f.getvalue())) f.truncate(0) f.write('start write!') print(f.tell()) print("next:\t", f.getvalue(), len(f.getvalue())) f_test = StringIO('Hello! Hi! Goodbye!') print("1:\t", f_test.read()) print(f_test.getvalue()) print(f_test.getvalue()) print("2:\t", f_test.read()) print("3:\t", f_test.read()) print("4:\t", f_test.read()) print("next:\t", f_test.getvalue(), len(f_test.getvalue())) f_test.close() f.close()