test_file_eintr.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # Written to test interrupted system calls interfering with our many buffered
  2. # IO implementations. http://bugs.python.org/issue12268
  3. #
  4. # It was suggested that this code could be merged into test_io and the tests
  5. # made to work using the same method as the existing signal tests in test_io.
  6. # I was unable to get single process tests using alarm or setitimer that way
  7. # to reproduce the EINTR problems. This process based test suite reproduces
  8. # the problems prior to the issue12268 patch reliably on Linux and OSX.
  9. # - gregory.p.smith
  10. import os
  11. import select
  12. import signal
  13. import subprocess
  14. import sys
  15. import time
  16. import unittest
  17. from test import support
  18. if not support.has_subprocess_support:
  19. raise unittest.SkipTest("test module requires subprocess")
  20. # Test import all of the things we're about to try testing up front.
  21. import _io
  22. import _pyio
  23. @unittest.skipUnless(os.name == 'posix', 'tests requires a posix system.')
  24. class TestFileIOSignalInterrupt:
  25. def setUp(self):
  26. self._process = None
  27. def tearDown(self):
  28. if self._process and self._process.poll() is None:
  29. try:
  30. self._process.kill()
  31. except OSError:
  32. pass
  33. def _generate_infile_setup_code(self):
  34. """Returns the infile = ... line of code for the reader process.
  35. subclasseses should override this to test different IO objects.
  36. """
  37. return ('import %s as io ;'
  38. 'infile = io.FileIO(sys.stdin.fileno(), "rb")' %
  39. self.modname)
  40. def fail_with_process_info(self, why, stdout=b'', stderr=b'',
  41. communicate=True):
  42. """A common way to cleanup and fail with useful debug output.
  43. Kills the process if it is still running, collects remaining output
  44. and fails the test with an error message including the output.
  45. Args:
  46. why: Text to go after "Error from IO process" in the message.
  47. stdout, stderr: standard output and error from the process so
  48. far to include in the error message.
  49. communicate: bool, when True we call communicate() on the process
  50. after killing it to gather additional output.
  51. """
  52. if self._process.poll() is None:
  53. time.sleep(0.1) # give it time to finish printing the error.
  54. try:
  55. self._process.terminate() # Ensure it dies.
  56. except OSError:
  57. pass
  58. if communicate:
  59. stdout_end, stderr_end = self._process.communicate()
  60. stdout += stdout_end
  61. stderr += stderr_end
  62. self.fail('Error from IO process %s:\nSTDOUT:\n%sSTDERR:\n%s\n' %
  63. (why, stdout.decode(), stderr.decode()))
  64. def _test_reading(self, data_to_write, read_and_verify_code):
  65. """Generic buffered read method test harness to validate EINTR behavior.
  66. Also validates that Python signal handlers are run during the read.
  67. Args:
  68. data_to_write: String to write to the child process for reading
  69. before sending it a signal, confirming the signal was handled,
  70. writing a final newline and closing the infile pipe.
  71. read_and_verify_code: Single "line" of code to read from a file
  72. object named 'infile' and validate the result. This will be
  73. executed as part of a python subprocess fed data_to_write.
  74. """
  75. infile_setup_code = self._generate_infile_setup_code()
  76. # Total pipe IO in this function is smaller than the minimum posix OS
  77. # pipe buffer size of 512 bytes. No writer should block.
  78. assert len(data_to_write) < 512, 'data_to_write must fit in pipe buf.'
  79. # Start a subprocess to call our read method while handling a signal.
  80. self._process = subprocess.Popen(
  81. [sys.executable, '-u', '-c',
  82. 'import signal, sys ;'
  83. 'signal.signal(signal.SIGINT, '
  84. 'lambda s, f: sys.stderr.write("$\\n")) ;'
  85. + infile_setup_code + ' ;' +
  86. 'sys.stderr.write("Worm Sign!\\n") ;'
  87. + read_and_verify_code + ' ;' +
  88. 'infile.close()'
  89. ],
  90. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  91. stderr=subprocess.PIPE)
  92. # Wait for the signal handler to be installed.
  93. worm_sign = self._process.stderr.read(len(b'Worm Sign!\n'))
  94. if worm_sign != b'Worm Sign!\n': # See also, Dune by Frank Herbert.
  95. self.fail_with_process_info('while awaiting a sign',
  96. stderr=worm_sign)
  97. self._process.stdin.write(data_to_write)
  98. signals_sent = 0
  99. rlist = []
  100. # We don't know when the read_and_verify_code in our child is actually
  101. # executing within the read system call we want to interrupt. This
  102. # loop waits for a bit before sending the first signal to increase
  103. # the likelihood of that. Implementations without correct EINTR
  104. # and signal handling usually fail this test.
  105. while not rlist:
  106. rlist, _, _ = select.select([self._process.stderr], (), (), 0.05)
  107. self._process.send_signal(signal.SIGINT)
  108. signals_sent += 1
  109. if signals_sent > 200:
  110. self._process.kill()
  111. self.fail('reader process failed to handle our signals.')
  112. # This assumes anything unexpected that writes to stderr will also
  113. # write a newline. That is true of the traceback printing code.
  114. signal_line = self._process.stderr.readline()
  115. if signal_line != b'$\n':
  116. self.fail_with_process_info('while awaiting signal',
  117. stderr=signal_line)
  118. # We append a newline to our input so that a readline call can
  119. # end on its own before the EOF is seen and so that we're testing
  120. # the read call that was interrupted by a signal before the end of
  121. # the data stream has been reached.
  122. stdout, stderr = self._process.communicate(input=b'\n')
  123. if self._process.returncode:
  124. self.fail_with_process_info(
  125. 'exited rc=%d' % self._process.returncode,
  126. stdout, stderr, communicate=False)
  127. # PASS!
  128. # String format for the read_and_verify_code used by read methods.
  129. _READING_CODE_TEMPLATE = (
  130. 'got = infile.{read_method_name}() ;'
  131. 'expected = {expected!r} ;'
  132. 'assert got == expected, ('
  133. '"{read_method_name} returned wrong data.\\n"'
  134. '"got data %r\\nexpected %r" % (got, expected))'
  135. )
  136. def test_readline(self):
  137. """readline() must handle signals and not lose data."""
  138. self._test_reading(
  139. data_to_write=b'hello, world!',
  140. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  141. read_method_name='readline',
  142. expected=b'hello, world!\n'))
  143. def test_readlines(self):
  144. """readlines() must handle signals and not lose data."""
  145. self._test_reading(
  146. data_to_write=b'hello\nworld!',
  147. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  148. read_method_name='readlines',
  149. expected=[b'hello\n', b'world!\n']))
  150. def test_readall(self):
  151. """readall() must handle signals and not lose data."""
  152. self._test_reading(
  153. data_to_write=b'hello\nworld!',
  154. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  155. read_method_name='readall',
  156. expected=b'hello\nworld!\n'))
  157. # read() is the same thing as readall().
  158. self._test_reading(
  159. data_to_write=b'hello\nworld!',
  160. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  161. read_method_name='read',
  162. expected=b'hello\nworld!\n'))
  163. class CTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase):
  164. modname = '_io'
  165. class PyTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase):
  166. modname = '_pyio'
  167. class TestBufferedIOSignalInterrupt(TestFileIOSignalInterrupt):
  168. def _generate_infile_setup_code(self):
  169. """Returns the infile = ... line of code to make a BufferedReader."""
  170. return ('import %s as io ;infile = io.open(sys.stdin.fileno(), "rb") ;'
  171. 'assert isinstance(infile, io.BufferedReader)' %
  172. self.modname)
  173. def test_readall(self):
  174. """BufferedReader.read() must handle signals and not lose data."""
  175. self._test_reading(
  176. data_to_write=b'hello\nworld!',
  177. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  178. read_method_name='read',
  179. expected=b'hello\nworld!\n'))
  180. class CTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase):
  181. modname = '_io'
  182. class PyTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase):
  183. modname = '_pyio'
  184. class TestTextIOSignalInterrupt(TestFileIOSignalInterrupt):
  185. def _generate_infile_setup_code(self):
  186. """Returns the infile = ... line of code to make a TextIOWrapper."""
  187. return ('import %s as io ;'
  188. 'infile = io.open(sys.stdin.fileno(), encoding="utf-8", newline=None) ;'
  189. 'assert isinstance(infile, io.TextIOWrapper)' %
  190. self.modname)
  191. def test_readline(self):
  192. """readline() must handle signals and not lose data."""
  193. self._test_reading(
  194. data_to_write=b'hello, world!',
  195. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  196. read_method_name='readline',
  197. expected='hello, world!\n'))
  198. def test_readlines(self):
  199. """readlines() must handle signals and not lose data."""
  200. self._test_reading(
  201. data_to_write=b'hello\r\nworld!',
  202. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  203. read_method_name='readlines',
  204. expected=['hello\n', 'world!\n']))
  205. def test_readall(self):
  206. """read() must handle signals and not lose data."""
  207. self._test_reading(
  208. data_to_write=b'hello\nworld!',
  209. read_and_verify_code=self._READING_CODE_TEMPLATE.format(
  210. read_method_name='read',
  211. expected="hello\nworld!\n"))
  212. class CTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase):
  213. modname = '_io'
  214. class PyTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase):
  215. modname = '_pyio'
  216. if __name__ == '__main__':
  217. unittest.main()