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