test_bufio.py 2.6 KB

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