Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame^] | 1 | import unittest |
| 2 | from test import test_support |
| 3 | |
| 4 | import io |
| 5 | |
| 6 | class IOTest(unittest.TestCase): |
| 7 | |
| 8 | def write_ops(self, f): |
| 9 | f.write(b"blah.") |
| 10 | f.seek(0) |
| 11 | f.write(b"Hello.") |
| 12 | self.assertEqual(f.tell(), 6) |
| 13 | f.seek(-1, 1) |
| 14 | self.assertEqual(f.tell(), 5) |
| 15 | f.write(" world\n\n\n") |
| 16 | f.seek(0) |
| 17 | f.write("h") |
| 18 | f.seek(-2, 2) |
| 19 | f.truncate() |
| 20 | |
| 21 | def read_ops(self, f): |
| 22 | data = f.read(5) |
| 23 | self.assertEqual(data, b"hello") |
| 24 | f.readinto(data) |
| 25 | self.assertEqual(data, b" worl") |
| 26 | f.readinto(data) |
| 27 | self.assertEqual(data, b"d\n") |
| 28 | f.seek(0) |
| 29 | self.assertEqual(f.read(20), b"hello world\n") |
| 30 | f.seek(-6, 2) |
| 31 | self.assertEqual(f.read(5), b"world") |
| 32 | f.seek(-6, 1) |
| 33 | self.assertEqual(f.read(5), b" worl") |
| 34 | self.assertEqual(f.tell(), 10) |
| 35 | |
| 36 | def test_raw_file_io(self): |
| 37 | f = io.open(test_support.TESTFN, "wb", buffering=0) |
| 38 | self.assertEqual(f.readable(), False) |
| 39 | self.assertEqual(f.writable(), True) |
| 40 | self.assertEqual(f.seekable(), True) |
| 41 | self.write_ops(f) |
| 42 | f.close() |
| 43 | f = io.open(test_support.TESTFN, "rb", buffering=0) |
| 44 | self.assertEqual(f.readable(), True) |
| 45 | self.assertEqual(f.writable(), False) |
| 46 | self.assertEqual(f.seekable(), True) |
| 47 | self.read_ops(f) |
| 48 | f.close() |
| 49 | |
| 50 | def test_raw_bytes_io(self): |
| 51 | f = io.BytesIO() |
| 52 | self.write_ops(f) |
| 53 | data = f.getvalue() |
| 54 | self.assertEqual(data, b"hello world\n") |
| 55 | f = io.BytesIO(data) |
| 56 | self.read_ops(f) |
| 57 | |
| 58 | def test_main(): |
| 59 | test_support.run_unittest(IOTest) |
| 60 | |
| 61 | if __name__ == "__main__": |
| 62 | test_main() |