test_bufio.py 2.7 KB

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