Debian Codegraph @

Lib/test/test__interpreters.py

raw
1 import contextlib
2 import itertools
3 import os
4 import pickle
5 import sys
6 from textwrap import dedent
7 import threading
8 import unittest
9
10 from test import support
11 from test.support import import_helper
12 from test.support import os_helper
13 from test.support import script_helper
14
15
16 _interpreters = import_helper.import_module('_interpreters')
17 _testinternalcapi = import_helper.import_module('_testinternalcapi')
18 from _interpreters import InterpreterNotFoundError
19
20
21 ##################################
22 # helpers
23
24 def _captured_script(script):
25 r, w = os.pipe()
26 indented = script.replace('\n', '\n ')
27 wrapped = dedent(f"""
28 import contextlib
29 with open({w}, 'w', encoding="utf-8") as spipe:
30 with contextlib.redirect_stdout(spipe):
31 {indented}
32 """)
33 return wrapped, open(r, encoding="utf-8")
34
35
36 def _run_output(interp, request):
37 script, rpipe = _captured_script(request)
38 with rpipe:
39 _interpreters.run_string(interp, script)
40 return rpipe.read()
41
42
43 def _wait_for_interp_to_run(interp, timeout=None):
44 # bpo-37224: Running this test file in multiprocesses will fail randomly.
45 # The failure reason is that the thread can't acquire the cpu to
46 # run subinterpreter eariler than the main thread in multiprocess.
47 if timeout is None:
48 timeout = support.SHORT_TIMEOUT
49 for _ in support.sleeping_retry(timeout, error=False):
50 if _interpreters.is_running(interp):
51 break
52 else:
53 raise RuntimeError('interp is not running')
54
55
56 @contextlib.contextmanager
57 def _running(interp):
58 r, w = os.pipe()
59 def run():
60 _interpreters.run_string(interp, dedent(f"""
61 # wait for "signal"
62 with open({r}, encoding="utf-8") as rpipe:
63 rpipe.read()
64 """))
65
66 t = threading.Thread(target=run)
67 t.start()
68 _wait_for_interp_to_run(interp)
69
70 yield
71
72 with open(w, 'w', encoding="utf-8") as spipe:
73 spipe.write('done')
74 t.join()
75
76
77 def clean_up_interpreters():
78 for id, *_ in _interpreters.list_all():
79 if id == 0: # main
80 continue
81 try:
82 _interpreters.destroy(id)
83 except _interpreters.InterpreterError:
84 pass # already destroyed
85
86
87 class TestBase(unittest.TestCase):
88
89 def tearDown(self):
90 clean_up_interpreters()
91
92
93 ##################################
94 # misc. tests
95
96 class IsShareableTests(unittest.TestCase):
97
98 def test_default_shareables(self):
99 shareables = [
100 # singletons
101 None,
102 # builtin objects
103 b'spam',
104 'spam',
105 10,
106 -10,
107 True,
108 False,
109 100.0,
110 (1, ('spam', 'eggs')),
111 ]
112 for obj in shareables:
113 with self.subTest(obj):
114 self.assertTrue(
115 _interpreters.is_shareable(obj))
116
117 def test_not_shareable(self):
118 class Cheese:
119 def __init__(self, name):
120 self.name = name
121 def __str__(self):
122 return self.name
123
124 class SubBytes(bytes):
125 """A subclass of a shareable type."""
126
127 not_shareables = [
128 # singletons
129 NotImplemented,
130 ...,
131 # builtin types and objects
132 type,
133 object,
134 object(),
135 Exception(),
136 # user-defined types and objects
137 Cheese,
138 Cheese('Wensleydale'),
139 SubBytes(b'spam'),
140 ]
141 for obj in not_shareables:
142 with self.subTest(repr(obj)):
143 self.assertFalse(
144 _interpreters.is_shareable(obj))
145
146
147 class ShareableTypeTests(unittest.TestCase):
148
149 def _assert_values(self, values):
150 for obj in values:
151 with self.subTest(obj):
152 xid = _testinternalcapi.get_crossinterp_data(obj)
153 got = _testinternalcapi.restore_crossinterp_data(xid)
154
155 self.assertEqual(got, obj)
156 self.assertIs(type(got), type(obj))
157
158 def test_singletons(self):
159 for obj in [None]:
160 with self.subTest(obj):
161 xid = _testinternalcapi.get_crossinterp_data(obj)
162 got = _testinternalcapi.restore_crossinterp_data(xid)
163
164 # XXX What about between interpreters?
165 self.assertIs(got, obj)
166
167 def test_types(self):
168 self._assert_values([
169 b'spam',
170 9999,
171 ])
172
173 def test_bytes(self):
174 self._assert_values(i.to_bytes(2, 'little', signed=True)
175 for i in range(-1, 258))
176
177 def test_strs(self):
178 self._assert_values(['hello world', '你好世界', ''])
179
180 def test_int(self):
181 self._assert_values(itertools.chain(range(-1, 258),
182 [sys.maxsize, -sys.maxsize - 1]))
183
184 def test_non_shareable_int(self):
185 ints = [
186 sys.maxsize + 1,
187 -sys.maxsize - 2,
188 2**1000,
189 ]
190 for i in ints:
191 with self.subTest(i):
192 with self.assertRaises(OverflowError):
193 _testinternalcapi.get_crossinterp_data(i)
194
195 def test_bool(self):
196 self._assert_values([True, False])
197
198 def test_float(self):
199 self._assert_values([0.0, 1.1, -1.0, 0.12345678, -0.12345678])
200
201 def test_tuple(self):
202 self._assert_values([(), (1,), ("hello", "world", ), (1, True, "hello")])
203 # Test nesting
204 self._assert_values([
205 ((1,),),
206 ((1, 2), (3, 4)),
207 ((1, 2), (3, 4), (5, 6)),
208 ])
209
210 def test_tuples_containing_non_shareable_types(self):
211 non_shareables = [
212 Exception(),
213 object(),
214 ]
215 for s in non_shareables:
216 value = tuple([0, 1.0, s])
217 with self.subTest(repr(value)):
218 # XXX Assert the NotShareableError when it is exported
219 with self.assertRaises(ValueError):
220 _testinternalcapi.get_crossinterp_data(value)
221 # Check nested as well
222 value = tuple([0, 1., (s,)])
223 with self.subTest("nested " + repr(value)):
224 # XXX Assert the NotShareableError when it is exported
225 with self.assertRaises(ValueError):
226 _testinternalcapi.get_crossinterp_data(value)
227
228
229 class ModuleTests(TestBase):
230
231 def test_import_in_interpreter(self):
232 _run_output(
233 _interpreters.create(),
234 'import _interpreters',
235 )
236
237
238 ##################################
239 # interpreter tests
240
241 class ListAllTests(TestBase):
242
243 def test_initial(self):
244 main, *_ = _interpreters.get_main()
245 ids = [id for id, *_ in _interpreters.list_all()]
246 self.assertEqual(ids, [main])
247
248 def test_after_creating(self):
249 main, *_ = _interpreters.get_main()
250 first = _interpreters.create()
251 second = _interpreters.create()
252 ids = [id for id, *_ in _interpreters.list_all()]
253 self.assertEqual(ids, [main, first, second])
254
255 def test_after_destroying(self):
256 main, *_ = _interpreters.get_main()
257 first = _interpreters.create()
258 second = _interpreters.create()
259 _interpreters.destroy(first)
260 ids = [id for id, *_ in _interpreters.list_all()]
261 self.assertEqual(ids, [main, second])
262
263
264 class GetCurrentTests(TestBase):
265
266 def test_main(self):
267 main, *_ = _interpreters.get_main()
268 cur, *_ = _interpreters.get_current()
269 self.assertEqual(cur, main)
270 self.assertIsInstance(cur, int)
271
272 def test_subinterpreter(self):
273 main, *_ = _interpreters.get_main()
274 interp = _interpreters.create()
275 out = _run_output(interp, dedent("""
276 import _interpreters
277 cur, *_ = _interpreters.get_current()
278 print(cur)
279 assert isinstance(cur, int)
280 """))
281 cur = int(out.strip())
282 _, expected = [id for id, *_ in _interpreters.list_all()]
283 self.assertEqual(cur, expected)
284 self.assertNotEqual(cur, main)
285
286
287 class GetMainTests(TestBase):
288
289 def test_from_main(self):
290 [expected] = [id for id, *_ in _interpreters.list_all()]
291 main, *_ = _interpreters.get_main()
292 self.assertEqual(main, expected)
293 self.assertIsInstance(main, int)
294
295 def test_from_subinterpreter(self):
296 [expected] = [id for id, *_ in _interpreters.list_all()]
297 interp = _interpreters.create()
298 out = _run_output(interp, dedent("""
299 import _interpreters
300 main, *_ = _interpreters.get_main()
301 print(main)
302 assert isinstance(main, int)
303 """))
304 main = int(out.strip())
305 self.assertEqual(main, expected)
306
307
308 class IsRunningTests(TestBase):
309
310 def test_main(self):
311 main, *_ = _interpreters.get_main()
312 self.assertTrue(_interpreters.is_running(main))
313
314 @unittest.skip('Fails on FreeBSD')
315 def test_subinterpreter(self):
316 interp = _interpreters.create()
317 self.assertFalse(_interpreters.is_running(interp))
318
319 with _running(interp):
320 self.assertTrue(_interpreters.is_running(interp))
321 self.assertFalse(_interpreters.is_running(interp))
322
323 def test_from_subinterpreter(self):
324 interp = _interpreters.create()
325 out = _run_output(interp, dedent(f"""
326 import _interpreters
327 if _interpreters.is_running({interp}):
328 print(True)
329 else:
330 print(False)
331 """))
332 self.assertEqual(out.strip(), 'True')
333
334 def test_already_destroyed(self):
335 interp = _interpreters.create()
336 _interpreters.destroy(interp)
337 with self.assertRaises(InterpreterNotFoundError):
338 _interpreters.is_running(interp)
339
340 def test_does_not_exist(self):
341 with self.assertRaises(InterpreterNotFoundError):
342 _interpreters.is_running(1_000_000)
343
344 def test_bad_id(self):
345 with self.assertRaises(ValueError):
346 _interpreters.is_running(-1)
347
348
349 class CreateTests(TestBase):
350
351 def test_in_main(self):
352 id = _interpreters.create()
353 self.assertIsInstance(id, int)
354
355 after = [id for id, *_ in _interpreters.list_all()]
356 self.assertIn(id, after)
357
358 @unittest.skip('enable this test when working on pystate.c')
359 def test_unique_id(self):
360 seen = set()
361 for _ in range(100):
362 id = _interpreters.create()
363 _interpreters.destroy(id)
364 seen.add(id)
365
366 self.assertEqual(len(seen), 100)
367
368 def test_in_thread(self):
369 lock = threading.Lock()
370 id = None
371 def f():
372 nonlocal id
373 id = _interpreters.create()
374 lock.acquire()
375 lock.release()
376
377 t = threading.Thread(target=f)
378 with lock:
379 t.start()
380 t.join()
381 after = set(id for id, *_ in _interpreters.list_all())
382 self.assertIn(id, after)
383
384 def test_in_subinterpreter(self):
385 main, = [id for id, *_ in _interpreters.list_all()]
386 id1 = _interpreters.create()
387 out = _run_output(id1, dedent("""
388 import _interpreters
389 id = _interpreters.create()
390 print(id)
391 assert isinstance(id, int)
392 """))
393 id2 = int(out.strip())
394
395 after = set(id for id, *_ in _interpreters.list_all())
396 self.assertEqual(after, {main, id1, id2})
397
398 def test_in_threaded_subinterpreter(self):
399 main, = [id for id, *_ in _interpreters.list_all()]
400 id1 = _interpreters.create()
401 id2 = None
402 def f():
403 nonlocal id2
404 out = _run_output(id1, dedent("""
405 import _interpreters
406 id = _interpreters.create()
407 print(id)
408 """))
409 id2 = int(out.strip())
410
411 t = threading.Thread(target=f)
412 t.start()
413 t.join()
414
415 after = set(id for id, *_ in _interpreters.list_all())
416 self.assertEqual(after, {main, id1, id2})
417
418 def test_after_destroy_all(self):
419 before = set(id for id, *_ in _interpreters.list_all())
420 # Create 3 subinterpreters.
421 ids = []
422 for _ in range(3):
423 id = _interpreters.create()
424 ids.append(id)
425 # Now destroy them.
426 for id in ids:
427 _interpreters.destroy(id)
428 # Finally, create another.
429 id = _interpreters.create()
430 after = set(id for id, *_ in _interpreters.list_all())
431 self.assertEqual(after, before | {id})
432
433 def test_after_destroy_some(self):
434 before = set(id for id, *_ in _interpreters.list_all())
435 # Create 3 subinterpreters.
436 id1 = _interpreters.create()
437 id2 = _interpreters.create()
438 id3 = _interpreters.create()
439 # Now destroy 2 of them.
440 _interpreters.destroy(id1)
441 _interpreters.destroy(id3)
442 # Finally, create another.
443 id = _interpreters.create()
444 after = set(id for id, *_ in _interpreters.list_all())
445 self.assertEqual(after, before | {id, id2})
446
447
448 class DestroyTests(TestBase):
449
450 def test_one(self):
451 id1 = _interpreters.create()
452 id2 = _interpreters.create()
453 id3 = _interpreters.create()
454 before = set(id for id, *_ in _interpreters.list_all())
455 self.assertIn(id2, before)
456
457 _interpreters.destroy(id2)
458
459 after = set(id for id, *_ in _interpreters.list_all())
460 self.assertNotIn(id2, after)
461 self.assertIn(id1, after)
462 self.assertIn(id3, after)
463
464 def test_all(self):
465 initial = set(id for id, *_ in _interpreters.list_all())
466 ids = set()
467 for _ in range(3):
468 id = _interpreters.create()
469 ids.add(id)
470 before = set(id for id, *_ in _interpreters.list_all())
471 self.assertEqual(before, initial | ids)
472 for id in ids:
473 _interpreters.destroy(id)
474 after = set(id for id, *_ in _interpreters.list_all())
475 self.assertEqual(after, initial)
476
477 def test_main(self):
478 main, = [id for id, *_ in _interpreters.list_all()]
479 with self.assertRaises(_interpreters.InterpreterError):
480 _interpreters.destroy(main)
481
482 def f():
483 with self.assertRaises(_interpreters.InterpreterError):
484 _interpreters.destroy(main)
485
486 t = threading.Thread(target=f)
487 t.start()
488 t.join()
489
490 def test_already_destroyed(self):
491 id = _interpreters.create()
492 _interpreters.destroy(id)
493 with self.assertRaises(InterpreterNotFoundError):
494 _interpreters.destroy(id)
495
496 def test_does_not_exist(self):
497 with self.assertRaises(InterpreterNotFoundError):
498 _interpreters.destroy(1_000_000)
499
500 def test_bad_id(self):
501 with self.assertRaises(ValueError):
502 _interpreters.destroy(-1)
503
504 def test_from_current(self):
505 main, = [id for id, *_ in _interpreters.list_all()]
506 id = _interpreters.create()
507 script = dedent(f"""
508 import _interpreters
509 try:
510 _interpreters.destroy({id})
511 except _interpreters.InterpreterError:
512 pass
513 """)
514
515 _interpreters.run_string(id, script)
516 after = set(id for id, *_ in _interpreters.list_all())
517 self.assertEqual(after, {main, id})
518
519 def test_from_sibling(self):
520 main, = [id for id, *_ in _interpreters.list_all()]
521 id1 = _interpreters.create()
522 id2 = _interpreters.create()
523 script = dedent(f"""
524 import _interpreters
525 _interpreters.destroy({id2})
526 """)
527 _interpreters.run_string(id1, script)
528
529 after = set(id for id, *_ in _interpreters.list_all())
530 self.assertEqual(after, {main, id1})
531
532 def test_from_other_thread(self):
533 id = _interpreters.create()
534 def f():
535 _interpreters.destroy(id)
536
537 t = threading.Thread(target=f)
538 t.start()
539 t.join()
540
541 def test_still_running(self):
542 main, = [id for id, *_ in _interpreters.list_all()]
543 interp = _interpreters.create()
544 with _running(interp):
545 self.assertTrue(_interpreters.is_running(interp),
546 msg=f"Interp {interp} should be running before destruction.")
547
548 with self.assertRaises(_interpreters.InterpreterError,
549 msg=f"Should not be able to destroy interp {interp} while it's still running."):
550 _interpreters.destroy(interp)
551 self.assertTrue(_interpreters.is_running(interp))
552
553
554 class CommonTests(TestBase):
555 def setUp(self):
556 super().setUp()
557 self.id = _interpreters.create()
558
559 def test_signatures(self):
560 # See https://github.com/python/cpython/issues/126654
561 msg = "expected 'shared' to be a dict"
562 with self.assertRaisesRegex(TypeError, msg):
563 _interpreters.exec(self.id, 'a', 1)
564 with self.assertRaisesRegex(TypeError, msg):
565 _interpreters.exec(self.id, 'a', shared=1)
566 with self.assertRaisesRegex(TypeError, msg):
567 _interpreters.run_string(self.id, 'a', shared=1)
568 with self.assertRaisesRegex(TypeError, msg):
569 _interpreters.run_func(self.id, lambda: None, shared=1)
570 # See https://github.com/python/cpython/issues/135855
571 msg = r'_interpreters.set___main___attrs\(\) argument 2 must be dict, not int'
572 with self.assertRaisesRegex(TypeError, msg):
573 _interpreters.set___main___attrs(self.id, 1)
574
575 def test_invalid_shared_none(self):
576 msg = "expected 'shared' to be a dict"
577 with self.assertRaisesRegex(TypeError, msg):
578 _interpreters.exec(self.id, 'a', shared=None)
579 with self.assertRaisesRegex(TypeError, msg):
580 _interpreters.run_string(self.id, 'a', shared=None)
581 with self.assertRaisesRegex(TypeError, msg):
582 _interpreters.run_func(self.id, lambda: None, shared=None)
583 msg = "must be dict, not None"
584 with self.assertRaisesRegex(TypeError, msg):
585 _interpreters.set___main___attrs(self.id, None)
586
587 def test_invalid_shared_encoding(self):
588 # See https://github.com/python/cpython/issues/127196
589 bad_shared = {"\uD82A": 0}
590 msg = 'surrogates not allowed'
591 with self.assertRaisesRegex(UnicodeEncodeError, msg):
592 _interpreters.exec(self.id, 'a', shared=bad_shared)
593 with self.assertRaisesRegex(UnicodeEncodeError, msg):
594 _interpreters.run_string(self.id, 'a', shared=bad_shared)
595 with self.assertRaisesRegex(UnicodeEncodeError, msg):
596 _interpreters.run_func(self.id, lambda: None, shared=bad_shared)
597
598
599 class RunStringTests(TestBase):
600
601 def setUp(self):
602 super().setUp()
603 self.id = _interpreters.create()
604
605 def test_success(self):
606 script, file = _captured_script('print("it worked!", end="")')
607 with file:
608 _interpreters.run_string(self.id, script)
609 out = file.read()
610
611 self.assertEqual(out, 'it worked!')
612
613 def test_in_thread(self):
614 script, file = _captured_script('print("it worked!", end="")')
615 with file:
616 def f():
617 _interpreters.run_string(self.id, script)
618
619 t = threading.Thread(target=f)
620 t.start()
621 t.join()
622 out = file.read()
623
624 self.assertEqual(out, 'it worked!')
625
626 def test_create_thread(self):
627 subinterp = _interpreters.create()
628 script, file = _captured_script("""
629 import threading
630 def f():
631 print('it worked!', end='')
632
633 t = threading.Thread(target=f)
634 t.start()
635 t.join()
636 """)
637 with file:
638 _interpreters.run_string(subinterp, script)
639 out = file.read()
640
641 self.assertEqual(out, 'it worked!')
642
643 def test_create_daemon_thread(self):
644 with self.subTest('isolated'):
645 expected = 'spam spam spam spam spam'
646 subinterp = _interpreters.create('isolated')
647 script, file = _captured_script(f"""
648 import threading
649 def f():
650 print('it worked!', end='')
651
652 try:
653 t = threading.Thread(target=f, daemon=True)
654 t.start()
655 t.join()
656 except RuntimeError:
657 print('{expected}', end='')
658 """)
659 with file:
660 _interpreters.run_string(subinterp, script)
661 out = file.read()
662
663 self.assertEqual(out, expected)
664
665 with self.subTest('not isolated'):
666 subinterp = _interpreters.create('legacy')
667 script, file = _captured_script("""
668 import threading
669 def f():
670 print('it worked!', end='')
671
672 t = threading.Thread(target=f, daemon=True)
673 t.start()
674 t.join()
675 """)
676 with file:
677 _interpreters.run_string(subinterp, script)
678 out = file.read()
679
680 self.assertEqual(out, 'it worked!')
681
682 def test_shareable_types(self):
683 interp = _interpreters.create()
684 objects = [
685 None,
686 'spam',
687 b'spam',
688 42,
689 ]
690 for obj in objects:
691 with self.subTest(obj):
692 _interpreters.set___main___attrs(interp, dict(obj=obj))
693 _interpreters.run_string(
694 interp,
695 f'assert(obj == {obj!r})',
696 )
697
698 def test_os_exec(self):
699 expected = 'spam spam spam spam spam'
700 subinterp = _interpreters.create()
701 script, file = _captured_script(f"""
702 import os, sys
703 try:
704 os.execl(sys.executable)
705 except RuntimeError:
706 print('{expected}', end='')
707 """)
708 with file:
709 _interpreters.run_string(subinterp, script)
710 out = file.read()
711
712 self.assertEqual(out, expected)
713
714 @support.requires_fork()
715 def test_fork(self):
716 import tempfile
717 with tempfile.NamedTemporaryFile('w+', encoding="utf-8") as file:
718 file.write('')
719 file.flush()
720
721 expected = 'spam spam spam spam spam'
722 script = dedent(f"""
723 import os
724 try:
725 os.fork()
726 except RuntimeError:
727 with open('{file.name}', 'w', encoding='utf-8') as out:
728 out.write('{expected}')
729 """)
730 _interpreters.run_string(self.id, script)
731
732 file.seek(0)
733 content = file.read()
734 self.assertEqual(content, expected)
735
736 def test_already_running(self):
737 with _running(self.id):
738 with self.assertRaises(_interpreters.InterpreterError):
739 _interpreters.run_string(self.id, 'print("spam")')
740
741 def test_does_not_exist(self):
742 id = 0
743 while id in set(id for id, *_ in _interpreters.list_all()):
744 id += 1
745 with self.assertRaises(InterpreterNotFoundError):
746 _interpreters.run_string(id, 'print("spam")')
747
748 def test_error_id(self):
749 with self.assertRaises(ValueError):
750 _interpreters.run_string(-1, 'print("spam")')
751
752 def test_bad_id(self):
753 with self.assertRaises(TypeError):
754 _interpreters.run_string('spam', 'print("spam")')
755
756 def test_bad_script(self):
757 with self.assertRaises(TypeError):
758 _interpreters.run_string(self.id, 10)
759
760 def test_bytes_for_script(self):
761 with self.assertRaises(TypeError):
762 _interpreters.run_string(self.id, b'print("spam")')
763
764 def test_str_subclass_string(self):
765 class StrSubclass(str): pass
766
767 output = _run_output(self.id, StrSubclass('print(1 + 2)'))
768 self.assertEqual(output, '3\n')
769
770 def test_with_shared(self):
771 r, w = os.pipe()
772
773 shared = {
774 'spam': b'ham',
775 'eggs': b'-1',
776 'cheddar': None,
777 }
778 script = dedent(f"""
779 eggs = int(eggs)
780 spam = 42
781 result = spam + eggs
782
783 ns = dict(vars())
784 del ns['__builtins__']
785 import pickle
786 with open({w}, 'wb') as chan:
787 pickle.dump(ns, chan)
788 """)
789 _interpreters.set___main___attrs(self.id, shared)
790 _interpreters.run_string(self.id, script)
791 with open(r, 'rb') as chan:
792 ns = pickle.load(chan)
793
794 self.assertEqual(ns['spam'], 42)
795 self.assertEqual(ns['eggs'], -1)
796 self.assertEqual(ns['result'], 41)
797 self.assertIsNone(ns['cheddar'])
798
799 def test_shared_overwrites(self):
800 _interpreters.run_string(self.id, dedent("""
801 spam = 'eggs'
802 ns1 = dict(vars())
803 del ns1['__builtins__']
804 """))
805
806 shared = {'spam': b'ham'}
807 script = dedent("""
808 ns2 = dict(vars())
809 del ns2['__builtins__']
810 """)
811 _interpreters.set___main___attrs(self.id, shared)
812 _interpreters.run_string(self.id, script)
813
814 r, w = os.pipe()
815 script = dedent(f"""
816 ns = dict(vars())
817 del ns['__builtins__']
818 import pickle
819 with open({w}, 'wb') as chan:
820 pickle.dump(ns, chan)
821 """)
822 _interpreters.run_string(self.id, script)
823 with open(r, 'rb') as chan:
824 ns = pickle.load(chan)
825
826 self.assertEqual(ns['ns1']['spam'], 'eggs')
827 self.assertEqual(ns['ns2']['spam'], b'ham')
828 self.assertEqual(ns['spam'], b'ham')
829
830 def test_shared_overwrites_default_vars(self):
831 r, w = os.pipe()
832
833 shared = {'__name__': b'not __main__'}
834 script = dedent(f"""
835 spam = 42
836
837 ns = dict(vars())
838 del ns['__builtins__']
839 import pickle
840 with open({w}, 'wb') as chan:
841 pickle.dump(ns, chan)
842 """)
843 _interpreters.set___main___attrs(self.id, shared)
844 _interpreters.run_string(self.id, script)
845 with open(r, 'rb') as chan:
846 ns = pickle.load(chan)
847
848 self.assertEqual(ns['__name__'], b'not __main__')
849
850 def test_main_reused(self):
851 r, w = os.pipe()
852 _interpreters.run_string(self.id, dedent(f"""
853 spam = True
854
855 ns = dict(vars())
856 del ns['__builtins__']
857 import pickle
858 with open({w}, 'wb') as chan:
859 pickle.dump(ns, chan)
860 del ns, pickle, chan
861 """))
862 with open(r, 'rb') as chan:
863 ns1 = pickle.load(chan)
864
865 r, w = os.pipe()
866 _interpreters.run_string(self.id, dedent(f"""
867 eggs = False
868
869 ns = dict(vars())
870 del ns['__builtins__']
871 import pickle
872 with open({w}, 'wb') as chan:
873 pickle.dump(ns, chan)
874 """))
875 with open(r, 'rb') as chan:
876 ns2 = pickle.load(chan)
877
878 self.assertIn('spam', ns1)
879 self.assertNotIn('eggs', ns1)
880 self.assertIn('eggs', ns2)
881 self.assertIn('spam', ns2)
882
883 def test_execution_namespace_is_main(self):
884 r, w = os.pipe()
885
886 script = dedent(f"""
887 spam = 42
888
889 ns = dict(vars())
890 ns['__builtins__'] = str(ns['__builtins__'])
891 import pickle
892 with open({w}, 'wb') as chan:
893 pickle.dump(ns, chan)
894 """)
895 _interpreters.run_string(self.id, script)
896 with open(r, 'rb') as chan:
897 ns = pickle.load(chan)
898
899 ns.pop('__builtins__')
900 ns.pop('__loader__')
901 self.assertEqual(ns, {
902 '__name__': '__main__',
903 '__annotations__': {},
904 '__doc__': None,
905 '__package__': None,
906 '__spec__': None,
907 'spam': 42,
908 })
909
910 # XXX Fix this test!
911 @unittest.skip('blocking forever')
912 def test_still_running_at_exit(self):
913 script = dedent("""
914 from textwrap import dedent
915 import threading
916 import _interpreters
917 id = _interpreters.create()
918 def f():
919 _interpreters.run_string(id, dedent('''
920 import time
921 # Give plenty of time for the main interpreter to finish.
922 time.sleep(1_000_000)
923 '''))
924
925 t = threading.Thread(target=f)
926 t.start()
927 """)
928 with support.temp_dir() as dirname:
929 filename = script_helper.make_script(dirname, 'interp', script)
930 with script_helper.spawn_python(filename) as proc:
931 retcode = proc.wait()
932
933 self.assertEqual(retcode, 0)
934
935
936 class RunFailedTests(TestBase):
937
938 def setUp(self):
939 super().setUp()
940 self.id = _interpreters.create()
941
942 def add_module(self, modname, text):
943 import tempfile
944 tempdir = tempfile.mkdtemp()
945 self.addCleanup(lambda: os_helper.rmtree(tempdir))
946 _interpreters.run_string(self.id, dedent(f"""
947 import sys
948 sys.path.insert(0, {tempdir!r})
949 """))
950 return script_helper.make_script(tempdir, modname, text)
951
952 def run_script(self, text, *, fails=False):
953 r, w = os.pipe()
954 try:
955 script = dedent(f"""
956 import os, sys
957 os.write({w}, b'0')
958
959 # This raises an exception:
960 {{}}
961
962 # Nothing from here down should ever run.
963 os.write({w}, b'1')
964 class NeverError(Exception): pass
965 raise NeverError # never raised
966 """).format(dedent(text))
967 if fails:
968 err = _interpreters.run_string(self.id, script)
969 self.assertIsNot(err, None)
970 return err
971 else:
972 err = _interpreters.run_string(self.id, script)
973 self.assertIs(err, None)
974 return None
975 except:
976 raise # re-raise
977 else:
978 msg = os.read(r, 100)
979 self.assertEqual(msg, b'0')
980 finally:
981 os.close(r)
982 os.close(w)
983
984 def _assert_run_failed(self, exctype, msg, script):
985 if isinstance(exctype, str):
986 exctype_name = exctype
987 exctype = None
988 else:
989 exctype_name = exctype.__name__
990
991 # Run the script.
992 excinfo = self.run_script(script, fails=True)
993
994 # Check the wrapper exception.
995 self.assertEqual(excinfo.type.__name__, exctype_name)
996 if msg is None:
997 self.assertEqual(excinfo.formatted.split(':')[0],
998 exctype_name)
999 else:
1000 self.assertEqual(excinfo.formatted,
1001 '{}: {}'.format(exctype_name, msg))
1002
1003 return excinfo
1004
1005 def assert_run_failed(self, exctype, script):
1006 self._assert_run_failed(exctype, None, script)
1007
1008 def assert_run_failed_msg(self, exctype, msg, script):
1009 self._assert_run_failed(exctype, msg, script)
1010
1011 def test_exit(self):
1012 with self.subTest('sys.exit(0)'):
1013 # XXX Should an unhandled SystemExit(0) be handled as not-an-error?
1014 self.assert_run_failed(SystemExit, """
1015 sys.exit(0)
1016 """)
1017
1018 with self.subTest('sys.exit()'):
1019 self.assert_run_failed(SystemExit, """
1020 import sys
1021 sys.exit()
1022 """)
1023
1024 with self.subTest('sys.exit(42)'):
1025 self.assert_run_failed_msg(SystemExit, '42', """
1026 import sys
1027 sys.exit(42)
1028 """)
1029
1030 with self.subTest('SystemExit'):
1031 self.assert_run_failed_msg(SystemExit, '42', """
1032 raise SystemExit(42)
1033 """)
1034
1035 # XXX Also check os._exit() (via a subprocess)?
1036
1037 def test_plain_exception(self):
1038 self.assert_run_failed_msg(Exception, 'spam', """
1039 raise Exception("spam")
1040 """)
1041
1042 def test_invalid_syntax(self):
1043 script = dedent("""
1044 x = 1 + 2
1045 y = 2 + 4
1046 z = 4 + 8
1047
1048 # missing close paren
1049 print("spam"
1050
1051 if x + y + z < 20:
1052 ...
1053 """)
1054
1055 with self.subTest('script'):
1056 self.assert_run_failed(SyntaxError, script)
1057
1058 with self.subTest('module'):
1059 modname = 'spam_spam_spam'
1060 filename = self.add_module(modname, script)
1061 self.assert_run_failed(SyntaxError, f"""
1062 import {modname}
1063 """)
1064
1065 def test_NameError(self):
1066 self.assert_run_failed(NameError, """
1067 res = spam + eggs
1068 """)
1069 # XXX check preserved suggestions
1070
1071 def test_AttributeError(self):
1072 self.assert_run_failed(AttributeError, """
1073 object().spam
1074 """)
1075 # XXX check preserved suggestions
1076
1077 def test_ExceptionGroup(self):
1078 self.assert_run_failed(ExceptionGroup, """
1079 raise ExceptionGroup('exceptions', [
1080 Exception('spam'),
1081 ImportError('eggs'),
1082 ])
1083 """)
1084
1085 def test_user_defined_exception(self):
1086 self.assert_run_failed_msg('MyError', 'spam', """
1087 class MyError(Exception):
1088 pass
1089 raise MyError('spam')
1090 """)
1091
1092
1093 class RunFuncTests(TestBase):
1094
1095 def setUp(self):
1096 super().setUp()
1097 self.id = _interpreters.create()
1098
1099 def test_success(self):
1100 r, w = os.pipe()
1101 def script():
1102 global w
1103 import contextlib
1104 with open(w, 'w', encoding="utf-8") as spipe:
1105 with contextlib.redirect_stdout(spipe):
1106 print('it worked!', end='')
1107 _interpreters.set___main___attrs(self.id, dict(w=w))
1108 _interpreters.run_func(self.id, script)
1109
1110 with open(r, encoding="utf-8") as outfile:
1111 out = outfile.read()
1112
1113 self.assertEqual(out, 'it worked!')
1114
1115 def test_in_thread(self):
1116 r, w = os.pipe()
1117 def script():
1118 global w
1119 import contextlib
1120 with open(w, 'w', encoding="utf-8") as spipe:
1121 with contextlib.redirect_stdout(spipe):
1122 print('it worked!', end='')
1123 def f():
1124 _interpreters.set___main___attrs(self.id, dict(w=w))
1125 _interpreters.run_func(self.id, script)
1126 t = threading.Thread(target=f)
1127 t.start()
1128 t.join()
1129
1130 with open(r, encoding="utf-8") as outfile:
1131 out = outfile.read()
1132
1133 self.assertEqual(out, 'it worked!')
1134
1135 def test_code_object(self):
1136 r, w = os.pipe()
1137
1138 def script():
1139 global w
1140 import contextlib
1141 with open(w, 'w', encoding="utf-8") as spipe:
1142 with contextlib.redirect_stdout(spipe):
1143 print('it worked!', end='')
1144 code = script.__code__
1145 _interpreters.set___main___attrs(self.id, dict(w=w))
1146 _interpreters.run_func(self.id, code)
1147
1148 with open(r, encoding="utf-8") as outfile:
1149 out = outfile.read()
1150
1151 self.assertEqual(out, 'it worked!')
1152
1153 def test_closure(self):
1154 spam = True
1155 def script():
1156 assert spam
1157
1158 with self.assertRaises(ValueError):
1159 _interpreters.run_func(self.id, script)
1160
1161 # XXX This hasn't been fixed yet.
1162 @unittest.expectedFailure
1163 def test_return_value(self):
1164 def script():
1165 return 'spam'
1166 with self.assertRaises(ValueError):
1167 _interpreters.run_func(self.id, script)
1168
1169 def test_args(self):
1170 with self.subTest('args'):
1171 def script(a, b=0):
1172 assert a == b
1173 with self.assertRaises(ValueError):
1174 _interpreters.run_func(self.id, script)
1175
1176 with self.subTest('*args'):
1177 def script(*args):
1178 assert not args
1179 with self.assertRaises(ValueError):
1180 _interpreters.run_func(self.id, script)
1181
1182 with self.subTest('**kwargs'):
1183 def script(**kwargs):
1184 assert not kwargs
1185 with self.assertRaises(ValueError):
1186 _interpreters.run_func(self.id, script)
1187
1188 with self.subTest('kwonly'):
1189 def script(*, spam=True):
1190 assert spam
1191 with self.assertRaises(ValueError):
1192 _interpreters.run_func(self.id, script)
1193
1194 with self.subTest('posonly'):
1195 def script(spam, /):
1196 assert spam
1197 with self.assertRaises(ValueError):
1198 _interpreters.run_func(self.id, script)
1199
1200
1201 if __name__ == '__main__':
1202 unittest.main()