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