Debian Codegraph @

Lib/test/test_support.py

raw
1 import contextlib
2 import errno
3 import importlib
4 import io
5 import logging
6 import os
7 import shutil
8 import socket
9 import stat
10 import subprocess
11 import sys
12 import sysconfig
13 import tempfile
14 import textwrap
15 import unittest
16 import warnings
17
18 from test import support
19 from test.support import import_helper
20 from test.support import os_helper
21 from test.support import script_helper
22 from test.support import socket_helper
23 from test.support import warnings_helper
24 from test.support.testcase import ExtraAssertions
25
26 TESTFN = os_helper.TESTFN
27
28
29 class LogCaptureHandler(logging.StreamHandler):
30 # Inspired by pytest's caplog
31 def __init__(self):
32 super().__init__(io.StringIO())
33 self.records = []
34
35 def emit(self, record) -> None:
36 self.records.append(record)
37 super().emit(record)
38
39 def handleError(self, record):
40 raise
41
42
43 @contextlib.contextmanager
44 def _caplog():
45 handler = LogCaptureHandler()
46 root_logger = logging.getLogger()
47 root_logger.addHandler(handler)
48 try:
49 yield handler
50 finally:
51 root_logger.removeHandler(handler)
52
53
54 class TestSupport(unittest.TestCase, ExtraAssertions):
55 @classmethod
56 def setUpClass(cls):
57 orig_filter_len = len(warnings.filters)
58 cls._warnings_helper_token = support.ignore_deprecations_from(
59 "test.support.warnings_helper", like=".*used in test_support.*"
60 )
61 cls._test_support_token = support.ignore_deprecations_from(
62 __name__, like=".*You should NOT be seeing this.*"
63 )
64 assert len(warnings.filters) == orig_filter_len + 2
65
66 @classmethod
67 def tearDownClass(cls):
68 orig_filter_len = len(warnings.filters)
69 support.clear_ignored_deprecations(
70 cls._warnings_helper_token,
71 cls._test_support_token,
72 )
73 assert len(warnings.filters) == orig_filter_len - 2
74
75 def test_ignored_deprecations_are_silent(self):
76 """Test support.ignore_deprecations_from() silences warnings"""
77 with warnings.catch_warnings(record=True) as warning_objs:
78 warnings_helper._warn_about_deprecation()
79 warnings.warn("You should NOT be seeing this.", DeprecationWarning)
80 messages = [str(w.message) for w in warning_objs]
81 self.assertEqual(len(messages), 0, messages)
82
83 def test_import_module(self):
84 import_helper.import_module("ftplib")
85 self.assertRaises(unittest.SkipTest,
86 import_helper.import_module, "foo")
87
88 def test_import_fresh_module(self):
89 import_helper.import_fresh_module("ftplib")
90
91 def test_get_attribute(self):
92 self.assertEqual(support.get_attribute(self, "test_get_attribute"),
93 self.test_get_attribute)
94 self.assertRaises(unittest.SkipTest, support.get_attribute, self, "foo")
95
96 @unittest.skip("failing buildbots")
97 def test_get_original_stdout(self):
98 self.assertEqual(support.get_original_stdout(), sys.stdout)
99
100 def test_unload(self):
101 import sched
102 self.assertIn("sched", sys.modules)
103 import_helper.unload("sched")
104 self.assertNotIn("sched", sys.modules)
105
106 def test_unlink(self):
107 with open(TESTFN, "w", encoding="utf-8") as f:
108 pass
109 os_helper.unlink(TESTFN)
110 self.assertFalse(os.path.exists(TESTFN))
111 os_helper.unlink(TESTFN)
112
113 def test_rmtree(self):
114 dirpath = os_helper.TESTFN + 'd'
115 subdirpath = os.path.join(dirpath, 'subdir')
116 os.mkdir(dirpath)
117 os.mkdir(subdirpath)
118 os_helper.rmtree(dirpath)
119 self.assertFalse(os.path.exists(dirpath))
120 with support.swap_attr(support, 'verbose', 0):
121 os_helper.rmtree(dirpath)
122
123 os.mkdir(dirpath)
124 os.mkdir(subdirpath)
125 os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR)
126 with support.swap_attr(support, 'verbose', 0):
127 os_helper.rmtree(dirpath)
128 self.assertFalse(os.path.exists(dirpath))
129
130 os.mkdir(dirpath)
131 os.mkdir(subdirpath)
132 os.chmod(dirpath, 0)
133 with support.swap_attr(support, 'verbose', 0):
134 os_helper.rmtree(dirpath)
135 self.assertFalse(os.path.exists(dirpath))
136
137 def test_forget(self):
138 mod_filename = TESTFN + '.py'
139 with open(mod_filename, 'w', encoding="utf-8") as f:
140 print('foo = 1', file=f)
141 sys.path.insert(0, os.curdir)
142 importlib.invalidate_caches()
143 try:
144 mod = __import__(TESTFN)
145 self.assertIn(TESTFN, sys.modules)
146
147 import_helper.forget(TESTFN)
148 self.assertNotIn(TESTFN, sys.modules)
149 finally:
150 del sys.path[0]
151 os_helper.unlink(mod_filename)
152 os_helper.rmtree('__pycache__')
153
154 @support.requires_working_socket()
155 def test_HOST(self):
156 s = socket.create_server((socket_helper.HOST, 0))
157 s.close()
158
159 @support.requires_working_socket()
160 def test_find_unused_port(self):
161 port = socket_helper.find_unused_port()
162 s = socket.create_server((socket_helper.HOST, port))
163 s.close()
164
165 @support.requires_working_socket()
166 def test_bind_port(self):
167 s = socket.socket()
168 socket_helper.bind_port(s)
169 s.listen()
170 s.close()
171
172 # Tests for temp_dir()
173
174 def test_temp_dir(self):
175 """Test that temp_dir() creates and destroys its directory."""
176 parent_dir = tempfile.mkdtemp()
177 parent_dir = os.path.realpath(parent_dir)
178
179 try:
180 path = os.path.join(parent_dir, 'temp')
181 self.assertFalse(os.path.isdir(path))
182 with os_helper.temp_dir(path) as temp_path:
183 self.assertEqual(temp_path, path)
184 self.assertTrue(os.path.isdir(path))
185 self.assertFalse(os.path.isdir(path))
186 finally:
187 os_helper.rmtree(parent_dir)
188
189 def test_temp_dir__path_none(self):
190 """Test passing no path."""
191 with os_helper.temp_dir() as temp_path:
192 self.assertTrue(os.path.isdir(temp_path))
193 self.assertFalse(os.path.isdir(temp_path))
194
195 def test_temp_dir__existing_dir__quiet_default(self):
196 """Test passing a directory that already exists."""
197 def call_temp_dir(path):
198 with os_helper.temp_dir(path) as temp_path:
199 raise Exception("should not get here")
200
201 path = tempfile.mkdtemp()
202 path = os.path.realpath(path)
203 try:
204 self.assertTrue(os.path.isdir(path))
205 self.assertRaises(FileExistsError, call_temp_dir, path)
206 # Make sure temp_dir did not delete the original directory.
207 self.assertTrue(os.path.isdir(path))
208 finally:
209 shutil.rmtree(path)
210
211 def test_temp_dir__existing_dir__quiet_true(self):
212 """Test passing a directory that already exists with quiet=True."""
213 path = tempfile.mkdtemp()
214 path = os.path.realpath(path)
215
216 try:
217 with warnings_helper.check_warnings() as recorder, _caplog() as caplog:
218 with os_helper.temp_dir(path, quiet=True) as temp_path:
219 self.assertEqual(path, temp_path)
220 warnings = [str(w.message) for w in recorder.warnings]
221 # Make sure temp_dir did not delete the original directory.
222 self.assertTrue(os.path.isdir(path))
223 finally:
224 shutil.rmtree(path)
225
226 self.assertListEqual(warnings, [])
227 self.assertEqual(len(caplog.records), 1)
228 record = caplog.records[0]
229 self.assertStartsWith(
230 record.getMessage(),
231 f'tests may fail, unable to create '
232 f'temporary directory {path!r}: '
233 )
234
235 @support.requires_fork()
236 def test_temp_dir__forked_child(self):
237 """Test that a forked child process does not remove the directory."""
238 # See bpo-30028 for details.
239 # Run the test as an external script, because it uses fork.
240 script_helper.assert_python_ok("-c", textwrap.dedent("""
241 import os
242 from test import support
243 from test.support import os_helper
244 with os_helper.temp_cwd() as temp_path:
245 pid = os.fork()
246 if pid != 0:
247 # parent process
248
249 # wait for the child to terminate
250 support.wait_process(pid, exitcode=0)
251
252 # Make sure that temp_path is still present. When the child
253 # process leaves the 'temp_cwd'-context, the __exit__()-
254 # method of the context must not remove the temporary
255 # directory.
256 if not os.path.isdir(temp_path):
257 raise AssertionError("Child removed temp_path.")
258 """))
259
260 # Tests for change_cwd()
261
262 def test_change_cwd(self):
263 original_cwd = os.getcwd()
264
265 with os_helper.temp_dir() as temp_path:
266 with os_helper.change_cwd(temp_path) as new_cwd:
267 self.assertEqual(new_cwd, temp_path)
268 self.assertEqual(os.getcwd(), new_cwd)
269
270 self.assertEqual(os.getcwd(), original_cwd)
271
272 def test_change_cwd__non_existent_dir(self):
273 """Test passing a non-existent directory."""
274 original_cwd = os.getcwd()
275
276 def call_change_cwd(path):
277 with os_helper.change_cwd(path) as new_cwd:
278 raise Exception("should not get here")
279
280 with os_helper.temp_dir() as parent_dir:
281 non_existent_dir = os.path.join(parent_dir, 'does_not_exist')
282 self.assertRaises(FileNotFoundError, call_change_cwd,
283 non_existent_dir)
284
285 self.assertEqual(os.getcwd(), original_cwd)
286
287 def test_change_cwd__non_existent_dir__quiet_true(self):
288 """Test passing a non-existent directory with quiet=True."""
289 original_cwd = os.getcwd()
290
291 with os_helper.temp_dir() as parent_dir:
292 bad_dir = os.path.join(parent_dir, 'does_not_exist')
293 with warnings_helper.check_warnings() as recorder, _caplog() as caplog:
294 with os_helper.change_cwd(bad_dir, quiet=True) as new_cwd:
295 self.assertEqual(new_cwd, original_cwd)
296 self.assertEqual(os.getcwd(), new_cwd)
297 warnings = [str(w.message) for w in recorder.warnings]
298
299 self.assertListEqual(warnings, [])
300 self.assertEqual(len(caplog.records), 1)
301 record = caplog.records[0]
302 self.assertStartsWith(
303 record.getMessage(),
304 f'tests may fail, unable to change '
305 f'the current working directory '
306 f'to {bad_dir!r}: '
307 )
308
309 # Tests for change_cwd()
310
311 def test_change_cwd__chdir_warning(self):
312 """Check the warning message when os.chdir() fails."""
313 path = TESTFN + '_does_not_exist'
314 with warnings_helper.check_warnings() as recorder, _caplog() as caplog:
315 with os_helper.change_cwd(path=path, quiet=True):
316 pass
317 messages = [str(w.message) for w in recorder.warnings]
318
319 self.assertListEqual(messages, [])
320 self.assertEqual(len(caplog.records), 1)
321 record = caplog.records[0]
322 self.assertStartsWith(
323 record.getMessage(),
324 f'tests may fail, unable to change '
325 f'the current working directory '
326 f'to {path!r}: ',
327 )
328
329 # Tests for temp_cwd()
330
331 def test_temp_cwd(self):
332 here = os.getcwd()
333 with os_helper.temp_cwd(name=TESTFN):
334 self.assertEqual(os.path.basename(os.getcwd()), TESTFN)
335 self.assertFalse(os.path.exists(TESTFN))
336 self.assertEqual(os.getcwd(), here)
337
338
339 def test_temp_cwd__name_none(self):
340 """Test passing None to temp_cwd()."""
341 original_cwd = os.getcwd()
342 with os_helper.temp_cwd(name=None) as new_cwd:
343 self.assertNotEqual(new_cwd, original_cwd)
344 self.assertTrue(os.path.isdir(new_cwd))
345 self.assertEqual(os.getcwd(), new_cwd)
346 self.assertEqual(os.getcwd(), original_cwd)
347
348 def test_sortdict(self):
349 self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}")
350
351 def test_make_bad_fd(self):
352 fd = os_helper.make_bad_fd()
353 with self.assertRaises(OSError) as cm:
354 os.write(fd, b"foo")
355 self.assertEqual(cm.exception.errno, errno.EBADF)
356
357 def test_check_syntax_error(self):
358 support.check_syntax_error(self, "def class", lineno=1, offset=5)
359 with self.assertRaises(AssertionError):
360 support.check_syntax_error(self, "x=1")
361
362 def test_CleanImport(self):
363 import importlib
364 with import_helper.CleanImport("pprint"):
365 importlib.import_module("pprint")
366
367 def test_DirsOnSysPath(self):
368 with import_helper.DirsOnSysPath('foo', 'bar'):
369 self.assertIn("foo", sys.path)
370 self.assertIn("bar", sys.path)
371 self.assertNotIn("foo", sys.path)
372 self.assertNotIn("bar", sys.path)
373
374 def test_captured_stdout(self):
375 with support.captured_stdout() as stdout:
376 print("hello")
377 self.assertEqual(stdout.getvalue(), "hello\n")
378
379 def test_captured_stderr(self):
380 with support.captured_stderr() as stderr:
381 print("hello", file=sys.stderr)
382 self.assertEqual(stderr.getvalue(), "hello\n")
383
384 def test_captured_stdin(self):
385 with support.captured_stdin() as stdin:
386 stdin.write('hello\n')
387 stdin.seek(0)
388 # call test code that consumes from sys.stdin
389 captured = input()
390 self.assertEqual(captured, "hello")
391
392 def test_gc_collect(self):
393 support.gc_collect()
394
395 def test_python_is_optimized(self):
396 self.assertIsInstance(support.python_is_optimized(), bool)
397
398 def test_swap_attr(self):
399 class Obj:
400 pass
401 obj = Obj()
402 obj.x = 1
403 with support.swap_attr(obj, "x", 5) as x:
404 self.assertEqual(obj.x, 5)
405 self.assertEqual(x, 1)
406 self.assertEqual(obj.x, 1)
407 with support.swap_attr(obj, "y", 5) as y:
408 self.assertEqual(obj.y, 5)
409 self.assertIsNone(y)
410 self.assertFalse(hasattr(obj, 'y'))
411 with support.swap_attr(obj, "y", 5):
412 del obj.y
413 self.assertFalse(hasattr(obj, 'y'))
414
415 def test_swap_item(self):
416 D = {"x":1}
417 with support.swap_item(D, "x", 5) as x:
418 self.assertEqual(D["x"], 5)
419 self.assertEqual(x, 1)
420 self.assertEqual(D["x"], 1)
421 with support.swap_item(D, "y", 5) as y:
422 self.assertEqual(D["y"], 5)
423 self.assertIsNone(y)
424 self.assertNotIn("y", D)
425 with support.swap_item(D, "y", 5):
426 del D["y"]
427 self.assertNotIn("y", D)
428
429 class RefClass:
430 attribute1 = None
431 attribute2 = None
432 _hidden_attribute1 = None
433 __magic_1__ = None
434
435 class OtherClass:
436 attribute2 = None
437 attribute3 = None
438 __magic_1__ = None
439 __magic_2__ = None
440
441 def test_detect_api_mismatch(self):
442 missing_items = support.detect_api_mismatch(self.RefClass,
443 self.OtherClass)
444 self.assertEqual({'attribute1'}, missing_items)
445
446 missing_items = support.detect_api_mismatch(self.OtherClass,
447 self.RefClass)
448 self.assertEqual({'attribute3', '__magic_2__'}, missing_items)
449
450 def test_detect_api_mismatch__ignore(self):
451 ignore = ['attribute1', 'attribute3', '__magic_2__', 'not_in_either']
452
453 missing_items = support.detect_api_mismatch(
454 self.RefClass, self.OtherClass, ignore=ignore)
455 self.assertEqual(set(), missing_items)
456
457 missing_items = support.detect_api_mismatch(
458 self.OtherClass, self.RefClass, ignore=ignore)
459 self.assertEqual(set(), missing_items)
460
461 def test_check__all__(self):
462 extra = {'tempdir'}
463 not_exported = {'template'}
464 support.check__all__(self,
465 tempfile,
466 extra=extra,
467 not_exported=not_exported)
468
469 extra = {
470 'TextTestResult',
471 'installHandler',
472 }
473 not_exported = {'load_tests', "TestProgram", "BaseTestSuite"}
474 support.check__all__(self,
475 unittest,
476 ("unittest.result", "unittest.case",
477 "unittest.suite", "unittest.loader",
478 "unittest.main", "unittest.runner",
479 "unittest.signals", "unittest.async_case"),
480 extra=extra,
481 not_exported=not_exported)
482
483 self.assertRaises(AssertionError, support.check__all__, self, unittest)
484
485 @unittest.skipUnless(hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG'),
486 'need os.waitpid() and os.WNOHANG')
487 @support.requires_fork()
488 def test_reap_children(self):
489 # Make sure that there is no other pending child process
490 support.reap_children()
491
492 # Create a child process
493 pid = os.fork()
494 if pid == 0:
495 # child process: do nothing, just exit
496 os._exit(0)
497
498 was_altered = support.environment_altered
499 try:
500 support.environment_altered = False
501 stderr = io.StringIO()
502
503 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
504 with support.swap_attr(support.print_warning, 'orig_stderr', stderr):
505 support.reap_children()
506
507 # Use environment_altered to check if reap_children() found
508 # the child process
509 if support.environment_altered:
510 break
511
512 msg = "Warning -- reap_children() reaped child process %s" % pid
513 self.assertIn(msg, stderr.getvalue())
514 self.assertTrue(support.environment_altered)
515 finally:
516 support.environment_altered = was_altered
517
518 # Just in case, check again that there is no other
519 # pending child process
520 support.reap_children()
521
522 @support.requires_subprocess()
523 def check_options(self, args, func, expected=None):
524 code = f'from test.support import {func}; print(repr({func}()))'
525 cmd = [sys.executable, *args, '-c', code]
526 env = {key: value for key, value in os.environ.items()
527 if not key.startswith('PYTHON')}
528 proc = subprocess.run(cmd,
529 stdout=subprocess.PIPE,
530 stderr=subprocess.DEVNULL,
531 universal_newlines=True,
532 env=env)
533 if expected is None:
534 expected = args
535 self.assertEqual(proc.stdout.rstrip(), repr(expected))
536 self.assertEqual(proc.returncode, 0)
537
538 @support.requires_resource('cpu')
539 def test_args_from_interpreter_flags(self):
540 # Test test.support.args_from_interpreter_flags()
541 for opts in (
542 # no option
543 [],
544 # single option
545 ['-B'],
546 ['-s'],
547 ['-S'],
548 ['-E'],
549 ['-v'],
550 ['-b'],
551 ['-P'],
552 ['-q'],
553 ['-I'],
554 # same option multiple times
555 ['-bb'],
556 ['-vvv'],
557 # -W options
558 ['-Wignore'],
559 # -X options
560 ['-X', 'dev'],
561 ['-Wignore', '-X', 'dev'],
562 ['-X', 'faulthandler'],
563 ['-X', 'importtime'],
564 ['-X', 'showrefcount'],
565 ['-X', 'tracemalloc'],
566 ['-X', 'tracemalloc=3'],
567 ):
568 with self.subTest(opts=opts):
569 self.check_options(opts, 'args_from_interpreter_flags')
570
571 self.check_options(['-I', '-E', '-s', '-P'],
572 'args_from_interpreter_flags',
573 ['-I'])
574
575 def test_optim_args_from_interpreter_flags(self):
576 # Test test.support.optim_args_from_interpreter_flags()
577 for opts in (
578 # no option
579 [],
580 ['-O'],
581 ['-OO'],
582 ['-OOOO'],
583 ):
584 with self.subTest(opts=opts):
585 self.check_options(opts, 'optim_args_from_interpreter_flags')
586
587 @unittest.skipIf(support.is_apple_mobile, "Unstable on Apple Mobile")
588 @unittest.skipIf(support.is_emscripten, "Unstable in Emscripten")
589 @unittest.skipIf(support.is_wasi, "Unavailable on WASI")
590 def test_fd_count(self):
591 # We cannot test the absolute value of fd_count(): on old Linux kernel
592 # or glibc versions, os.urandom() keeps a FD open on /dev/urandom
593 # device and Python has 4 FD opens instead of 3. Test is unstable on
594 # Emscripten and Apple Mobile platforms; these platforms start and stop
595 # background threads that use pipes and epoll fds.
596 start = os_helper.fd_count()
597 fd = os.open(__file__, os.O_RDONLY)
598 try:
599 more = os_helper.fd_count()
600 finally:
601 os.close(fd)
602 self.assertEqual(more - start, 1)
603
604 def check_print_warning(self, msg, expected):
605 stderr = io.StringIO()
606 with support.swap_attr(support.print_warning, 'orig_stderr', stderr):
607 support.print_warning(msg)
608 self.assertEqual(stderr.getvalue(), expected)
609
610 def test_print_warning(self):
611 self.check_print_warning("msg",
612 "Warning -- msg\n")
613 self.check_print_warning("a\nb",
614 'Warning -- a\nWarning -- b\n')
615
616 def test_has_strftime_extensions(self):
617 if support.is_emscripten or sys.platform == "win32":
618 self.assertFalse(support.has_strftime_extensions)
619 else:
620 self.assertTrue(support.has_strftime_extensions)
621
622 def test_get_recursion_depth(self):
623 # test support.get_recursion_depth()
624 code = textwrap.dedent("""
625 from test import support
626 import sys
627
628 def check(cond):
629 if not cond:
630 raise AssertionError("test failed")
631
632 # depth 1
633 check(support.get_recursion_depth() == 1)
634
635 # depth 2
636 def test_func():
637 check(support.get_recursion_depth() == 2)
638 test_func()
639
640 def test_recursive(depth, limit):
641 if depth >= limit:
642 # cannot call get_recursion_depth() at this depth,
643 # it can raise RecursionError
644 return
645 get_depth = support.get_recursion_depth()
646 print(f"test_recursive: {depth}/{limit}: "
647 f"get_recursion_depth() says {get_depth}")
648 check(get_depth == depth)
649 test_recursive(depth + 1, limit)
650
651 # depth up to 25
652 with support.infinite_recursion(max_depth=25):
653 limit = sys.getrecursionlimit()
654 print(f"test with sys.getrecursionlimit()={limit}")
655 test_recursive(2, limit)
656
657 # depth up to 500
658 with support.infinite_recursion(max_depth=500):
659 limit = sys.getrecursionlimit()
660 print(f"test with sys.getrecursionlimit()={limit}")
661 test_recursive(2, limit)
662 """)
663 script_helper.assert_python_ok("-c", code)
664
665 def test_recursion(self):
666 # Test infinite_recursion() and get_recursion_available() functions.
667 def recursive_function(depth):
668 if depth:
669 recursive_function(depth - 1)
670
671 for max_depth in (5, 25, 250, 2500):
672 with support.infinite_recursion(max_depth):
673 available = support.get_recursion_available()
674
675 # Recursion up to 'available' additional frames should be OK.
676 recursive_function(available)
677
678 # Recursion up to 'available+1' additional frames must raise
679 # RecursionError. Avoid self.assertRaises(RecursionError) which
680 # can consume more than 3 frames and so raises RecursionError.
681 try:
682 recursive_function(available + 1)
683 except RecursionError:
684 pass
685 else:
686 self.fail("RecursionError was not raised")
687
688 # Test the bare minimumum: max_depth=3
689 with support.infinite_recursion(3):
690 try:
691 recursive_function(3)
692 except RecursionError:
693 pass
694 else:
695 self.fail("RecursionError was not raised")
696
697 def test_parse_memlimit(self):
698 parse = support._parse_memlimit
699 KiB = 1024
700 MiB = KiB * 1024
701 GiB = MiB * 1024
702 TiB = GiB * 1024
703 self.assertEqual(parse('0k'), 0)
704 self.assertEqual(parse('3k'), 3 * KiB)
705 self.assertEqual(parse('2.4m'), int(2.4 * MiB))
706 self.assertEqual(parse('4g'), int(4 * GiB))
707 self.assertEqual(parse('1t'), TiB)
708
709 for limit in ('', '3', '3.5.10k', '10x'):
710 with self.subTest(limit=limit):
711 with self.assertRaises(ValueError):
712 parse(limit)
713
714 def test_set_memlimit(self):
715 _4GiB = 4 * 1024 ** 3
716 TiB = 1024 ** 4
717 old_max_memuse = support.max_memuse
718 old_real_max_memuse = support.real_max_memuse
719 try:
720 if sys.maxsize > 2**32:
721 support.set_memlimit('4g')
722 self.assertEqual(support.max_memuse, _4GiB)
723 self.assertEqual(support.real_max_memuse, _4GiB)
724
725 big = 2**100 // TiB
726 support.set_memlimit(f'{big}t')
727 self.assertEqual(support.max_memuse, sys.maxsize)
728 self.assertEqual(support.real_max_memuse, big * TiB)
729 else:
730 support.set_memlimit('4g')
731 self.assertEqual(support.max_memuse, sys.maxsize)
732 self.assertEqual(support.real_max_memuse, _4GiB)
733 finally:
734 support.max_memuse = old_max_memuse
735 support.real_max_memuse = old_real_max_memuse
736
737 def test_copy_python_src_ignore(self):
738 # Get source directory
739 src_dir = sysconfig.get_config_var('abs_srcdir')
740 if not src_dir:
741 src_dir = sysconfig.get_config_var('srcdir')
742 src_dir = os.path.abspath(src_dir)
743
744 # Check that the source code is available
745 if not os.path.exists(src_dir):
746 self.skipTest(f"cannot access Python source code directory:"
747 f" {src_dir!r}")
748 # Check that the landmark copy_python_src_ignore() expects is available
749 # (Previously we looked for 'Lib\os.py', which is always present on Windows.)
750 landmark = os.path.join(src_dir, 'Modules')
751 if not os.path.exists(landmark):
752 self.skipTest(f"cannot access Python source code directory:"
753 f" {landmark!r} landmark is missing")
754
755 # Test support.copy_python_src_ignore()
756
757 # Source code directory
758 ignored = {'.git', '__pycache__'}
759 names = os.listdir(src_dir)
760 self.assertEqual(support.copy_python_src_ignore(src_dir, names),
761 ignored | {'build'})
762
763 # Doc/ directory
764 path = os.path.join(src_dir, 'Doc')
765 self.assertEqual(support.copy_python_src_ignore(path, os.listdir(path)),
766 ignored | {'build', 'venv'})
767
768 # Another directory
769 path = os.path.join(src_dir, 'Objects')
770 self.assertEqual(support.copy_python_src_ignore(path, os.listdir(path)),
771 ignored)
772
773 def test_linked_to_musl(self):
774 linked = support.linked_to_musl()
775 self.assertIsInstance(linked, bool)
776
777 # XXX -follows a list of untested API
778 # make_legacy_pyc
779 # is_resource_enabled
780 # requires
781 # fcmp
782 # umaks
783 # findfile
784 # check_warnings
785 # EnvironmentVarGuard
786 # transient_internet
787 # run_with_locale
788 # bigmemtest
789 # precisionbigmemtest
790 # bigaddrspacetest
791 # requires_resource
792 # threading_cleanup
793 # reap_threads
794 # can_symlink
795 # skip_unless_symlink
796 # SuppressCrashReport
797
798
799 if __name__ == '__main__':
800 unittest.main()