|
1 | 1 | import unittest |
| 2 | +from unittest import mock |
2 | 3 | import test._test_multiprocessing |
3 | 4 |
|
| 5 | +import os |
4 | 6 | import sys |
5 | 7 | from test import support |
6 | 8 |
|
|
10 | 12 | if sys.platform == "win32": |
11 | 13 | raise unittest.SkipTest("forkserver is not available on Windows") |
12 | 14 |
|
| 15 | +import multiprocessing |
| 16 | +import multiprocessing.connection |
| 17 | +import multiprocessing.forkserver |
| 18 | + |
13 | 19 | test._test_multiprocessing.install_tests_in_module_dict(globals(), 'forkserver') |
14 | 20 |
|
| 21 | + |
| 22 | +class TestForkserverControlAuthentication(unittest.TestCase): |
| 23 | + def setUp(self): |
| 24 | + super().setUp() |
| 25 | + self.context = multiprocessing.get_context("forkserver") |
| 26 | + self.pool = self.context.Pool(processes=1, maxtasksperchild=4) |
| 27 | + self.assertEqual(self.pool.apply(eval, ("2+2",)), 4) |
| 28 | + self.forkserver = multiprocessing.forkserver._forkserver |
| 29 | + self.addr = self.forkserver._forkserver_address |
| 30 | + self.assertTrue(self.addr) |
| 31 | + self.authkey = self.forkserver._forkserver_authkey |
| 32 | + self.assertGreater(len(self.authkey), 15) |
| 33 | + self.assertTrue(self.forkserver._forkserver_pid) |
| 34 | + |
| 35 | + def tearDown(self): |
| 36 | + self.pool.terminate() |
| 37 | + self.pool.join() |
| 38 | + super().tearDown() |
| 39 | + |
| 40 | + def test_auth_works(self): |
| 41 | + """FYI: An 'EOFError: ran out of input' from a worker is normal.""" |
| 42 | + # First, demonstrate that a raw auth handshake as Client makes |
| 43 | + # does not raise. |
| 44 | + client = multiprocessing.connection.Client( |
| 45 | + self.addr, authkey=self.authkey) |
| 46 | + client.close() |
| 47 | + |
| 48 | + # Now use forkserver code to do the same thing and more. |
| 49 | + status_r, data_w = self.forkserver.connect_to_new_process([]) |
| 50 | + # It is normal for this to trigger an EOFError on stderr from the |
| 51 | + # process... it is expecting us to send over a pickle of a Process |
| 52 | + # instance to tell it what to do. |
| 53 | + # If the authentication handshake and subsequent file descriptor |
| 54 | + # sending dance had failed, an exception would've been raised. |
| 55 | + os.close(data_w) |
| 56 | + os.close(status_r) |
| 57 | + |
| 58 | + def test_no_auth_fails(self): |
| 59 | + with mock.patch.object(self.forkserver, '_forkserver_authkey', None): |
| 60 | + # With no authkey set, the connection this makes will fail to |
| 61 | + # do the file descriptor transfer over the pipe. |
| 62 | + with self.assertRaisesRegex(RuntimeError, 'not receive ack'): |
| 63 | + status_r, data_w = self.forkserver.connect_to_new_process([]) |
| 64 | + |
| 65 | + |
15 | 66 | if __name__ == '__main__': |
16 | 67 | unittest.main() |
0 commit comments