move sections
[python/dscho.git] / Lib / test / test_bufio.py
blob108b1e18696e1af6aea27c8246000844a5e400fe
1 import unittest
2 from test import test_support as support
4 import io # C implementation.
5 import _pyio as pyio # Python implementation.
7 # Simple test to ensure that optimizations in the IO library deliver the
8 # expected results. For best testing, run this under a debug-build Python too
9 # (to exercise asserts in the C code).
11 lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
12 16384, 32768, 65536, 1000000]
14 class BufferSizeTest(unittest.TestCase):
15 def try_one(self, s):
16 # Write s + "\n" + s to file, then open it and ensure that successive
17 # .readline()s deliver what we wrote.
19 # Ensure we can open TESTFN for writing.
20 support.unlink(support.TESTFN)
22 # Since C doesn't guarantee we can write/read arbitrary bytes in text
23 # files, use binary mode.
24 f = self.open(support.TESTFN, "wb")
25 try:
26 # write once with \n and once without
27 f.write(s)
28 f.write(b"\n")
29 f.write(s)
30 f.close()
31 f = open(support.TESTFN, "rb")
32 line = f.readline()
33 self.assertEqual(line, s + b"\n")
34 line = f.readline()
35 self.assertEqual(line, s)
36 line = f.readline()
37 self.assertTrue(not line) # Must be at EOF
38 f.close()
39 finally:
40 support.unlink(support.TESTFN)
42 def drive_one(self, pattern):
43 for length in lengths:
44 # Repeat string 'pattern' as often as needed to reach total length
45 # 'length'. Then call try_one with that string, a string one larger
46 # than that, and a string one smaller than that. Try this with all
47 # small sizes and various powers of 2, so we exercise all likely
48 # stdio buffer sizes, and "off by one" errors on both sides.
49 q, r = divmod(length, len(pattern))
50 teststring = pattern * q + pattern[:r]
51 self.assertEqual(len(teststring), length)
52 self.try_one(teststring)
53 self.try_one(teststring + b"x")
54 self.try_one(teststring[:-1])
56 def test_primepat(self):
57 # A pattern with prime length, to avoid simple relationships with
58 # stdio buffer sizes.
59 self.drive_one(b"1234567890\00\01\02\03\04\05\06")
61 def test_nullpat(self):
62 self.drive_one(bytes(1000))
65 class CBufferSizeTest(BufferSizeTest):
66 open = io.open
68 class PyBufferSizeTest(BufferSizeTest):
69 open = staticmethod(pyio.open)
71 class BuiltinBufferSizeTest(BufferSizeTest):
72 open = open
75 def test_main():
76 support.run_unittest(CBufferSizeTest, PyBufferSizeTest, BuiltinBufferSizeTest)
78 if __name__ == "__main__":
79 test_main()