| 1 |
import contextlib |
| 2 |
import errno |
| 3 |
import importlib |
| 4 |
import io |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import shutil |
| 8 |
import signal |
| 9 |
import socket |
| 10 |
import stat |
| 11 |
import subprocess |
| 12 |
import sys |
| 13 |
import sysconfig |
| 14 |
import tempfile |
| 15 |
import textwrap |
| 16 |
import unittest |
| 17 |
import warnings |
| 18 |
|
| 19 |
from test import support |
| 20 |
from test.support import import_helper |
| 21 |
from test.support import os_helper |
| 22 |
from test.support import script_helper |
| 23 |
from test.support import socket_helper |
| 24 |
from test.support import warnings_helper |
| 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): |
| 55 |
@classmethod |
| 56 |
def setUpClass(cls): |
| 57 |
orig_filter_len = len(warnings._get_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._get_filters()) == orig_filter_len + 2 |
| 65 |
|
| 66 |
@classmethod |
| 67 |
def tearDownClass(cls): |
| 68 |
orig_filter_len = len(warnings._get_filters()) |
| 69 |
support.clear_ignored_deprecations( |
| 70 |
cls._warnings_helper_token, |
| 71 |
cls._test_support_token, |
| 72 |
) |
| 73 |
assert len(warnings._get_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 # noqa: F401 |
| 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.assertNotHasAttr(obj, 'y') |
| 411 |
with support.swap_attr(obj, "y", 5): |
| 412 |
del obj.y |
| 413 |
self.assertNotHasAttr(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', 'cpu_count=4'], |
| 563 |
['-X', 'disable-remote-debug'], |
| 564 |
['-X', 'faulthandler'], |
| 565 |
['-X', 'importtime'], |
| 566 |
['-X', 'importtime=2'], |
| 567 |
['-X', 'int_max_str_digits=1000'], |
| 568 |
['-X', 'lazy_imports=all'], |
| 569 |
['-X', 'no_debug_ranges'], |
| 570 |
['-X', 'showrefcount'], |
| 571 |
['-X', 'tracemalloc'], |
| 572 |
['-X', 'tracemalloc=3'], |
| 573 |
['-X', 'warn_default_encoding'], |
| 574 |
): |
| 575 |
with self.subTest(opts=opts): |
| 576 |
self.check_options(opts, 'args_from_interpreter_flags') |
| 577 |
|
| 578 |
with os_helper.temp_dir() as temp_path: |
| 579 |
prefix = os.path.join(temp_path, 'pycache') |
| 580 |
opts = ['-X', f'pycache_prefix={prefix}'] |
| 581 |
with self.subTest(opts=opts): |
| 582 |
self.check_options(opts, 'args_from_interpreter_flags') |
| 583 |
|
| 584 |
self.check_options(['-I', '-E', '-s', '-P'], |
| 585 |
'args_from_interpreter_flags', |
| 586 |
['-I']) |
| 587 |
|
| 588 |
def test_optim_args_from_interpreter_flags(self): |
| 589 |
# Test test.support.optim_args_from_interpreter_flags() |
| 590 |
for opts in ( |
| 591 |
# no option |
| 592 |
[], |
| 593 |
['-O'], |
| 594 |
['-OO'], |
| 595 |
['-OOOO'], |
| 596 |
): |
| 597 |
with self.subTest(opts=opts): |
| 598 |
self.check_options(opts, 'optim_args_from_interpreter_flags') |
| 599 |
|
| 600 |
@unittest.skipIf(support.is_apple_mobile, "Unstable on Apple Mobile") |
| 601 |
@unittest.skipIf(support.is_wasi, "Unavailable on WASI") |
| 602 |
def test_fd_count(self): |
| 603 |
# We cannot test the absolute value of fd_count(): on old Linux kernel |
| 604 |
# or glibc versions, os.urandom() keeps a FD open on /dev/urandom |
| 605 |
# device and Python has 4 FD opens instead of 3. Test is unstable on |
| 606 |
# Emscripten and Apple Mobile platforms; these platforms start and stop |
| 607 |
# background threads that use pipes and epoll fds. |
| 608 |
start = os_helper.fd_count() |
| 609 |
fd = os.open(__file__, os.O_RDONLY) |
| 610 |
try: |
| 611 |
more = os_helper.fd_count() |
| 612 |
finally: |
| 613 |
os.close(fd) |
| 614 |
self.assertEqual(more - start, 1) |
| 615 |
|
| 616 |
def check_print_warning(self, msg, expected): |
| 617 |
stderr = io.StringIO() |
| 618 |
with support.swap_attr(support.print_warning, 'orig_stderr', stderr): |
| 619 |
support.print_warning(msg) |
| 620 |
self.assertEqual(stderr.getvalue(), expected) |
| 621 |
|
| 622 |
def test_print_warning(self): |
| 623 |
self.check_print_warning("msg", |
| 624 |
"Warning -- msg\n") |
| 625 |
self.check_print_warning("a\nb", |
| 626 |
'Warning -- a\nWarning -- b\n') |
| 627 |
|
| 628 |
def test_has_strftime_extensions(self): |
| 629 |
if sys.platform == "win32": |
| 630 |
self.assertFalse(support.has_strftime_extensions) |
| 631 |
else: |
| 632 |
self.assertTrue(support.has_strftime_extensions) |
| 633 |
|
| 634 |
def test_get_recursion_depth(self): |
| 635 |
# test support.get_recursion_depth() |
| 636 |
code = textwrap.dedent(""" |
| 637 |
from test import support |
| 638 |
import sys |
| 639 |
|
| 640 |
def check(cond): |
| 641 |
if not cond: |
| 642 |
raise AssertionError("test failed") |
| 643 |
|
| 644 |
# depth 1 |
| 645 |
check(support.get_recursion_depth() == 1) |
| 646 |
|
| 647 |
# depth 2 |
| 648 |
def test_func(): |
| 649 |
check(support.get_recursion_depth() == 2) |
| 650 |
test_func() |
| 651 |
|
| 652 |
def test_recursive(depth, limit): |
| 653 |
if depth >= limit: |
| 654 |
# cannot call get_recursion_depth() at this depth, |
| 655 |
# it can raise RecursionError |
| 656 |
return |
| 657 |
get_depth = support.get_recursion_depth() |
| 658 |
print(f"test_recursive: {depth}/{limit}: " |
| 659 |
f"get_recursion_depth() says {get_depth}") |
| 660 |
check(get_depth == depth) |
| 661 |
test_recursive(depth + 1, limit) |
| 662 |
|
| 663 |
# depth up to 25 |
| 664 |
with support.infinite_recursion(max_depth=25): |
| 665 |
limit = sys.getrecursionlimit() |
| 666 |
print(f"test with sys.getrecursionlimit()={limit}") |
| 667 |
test_recursive(2, limit) |
| 668 |
|
| 669 |
# depth up to 500 |
| 670 |
with support.infinite_recursion(max_depth=500): |
| 671 |
limit = sys.getrecursionlimit() |
| 672 |
print(f"test with sys.getrecursionlimit()={limit}") |
| 673 |
test_recursive(2, limit) |
| 674 |
""") |
| 675 |
script_helper.assert_python_ok("-c", code) |
| 676 |
|
| 677 |
@support.skip_if_unlimited_stack_size |
| 678 |
def test_recursion(self): |
| 679 |
# Test infinite_recursion() and get_recursion_available() functions. |
| 680 |
def recursive_function(depth): |
| 681 |
if depth: |
| 682 |
recursive_function(depth - 1) |
| 683 |
|
| 684 |
for max_depth in (5, 25, 250, 2500): |
| 685 |
with support.infinite_recursion(max_depth): |
| 686 |
available = support.get_recursion_available() |
| 687 |
|
| 688 |
# Recursion up to 'available' additional frames should be OK. |
| 689 |
recursive_function(available) |
| 690 |
|
| 691 |
# Recursion up to 'available+1' additional frames must raise |
| 692 |
# RecursionError. Avoid self.assertRaises(RecursionError) which |
| 693 |
# can consume more than 3 frames and so raises RecursionError. |
| 694 |
try: |
| 695 |
recursive_function(available + 1) |
| 696 |
except RecursionError: |
| 697 |
pass |
| 698 |
else: |
| 699 |
self.fail("RecursionError was not raised") |
| 700 |
|
| 701 |
# Test the bare minimumum: max_depth=3 |
| 702 |
with support.infinite_recursion(3): |
| 703 |
try: |
| 704 |
recursive_function(3) |
| 705 |
except RecursionError: |
| 706 |
pass |
| 707 |
else: |
| 708 |
self.fail("RecursionError was not raised") |
| 709 |
|
| 710 |
def test_parse_memlimit(self): |
| 711 |
parse = support._parse_memlimit |
| 712 |
KiB = 1024 |
| 713 |
MiB = KiB * 1024 |
| 714 |
GiB = MiB * 1024 |
| 715 |
TiB = GiB * 1024 |
| 716 |
self.assertEqual(parse('0k'), 0) |
| 717 |
self.assertEqual(parse('3k'), 3 * KiB) |
| 718 |
self.assertEqual(parse('2.4m'), int(2.4 * MiB)) |
| 719 |
self.assertEqual(parse('4g'), int(4 * GiB)) |
| 720 |
self.assertEqual(parse('1t'), TiB) |
| 721 |
|
| 722 |
for limit in ('', '3', '3.5.10k', '10x'): |
| 723 |
with self.subTest(limit=limit): |
| 724 |
with self.assertRaises(ValueError): |
| 725 |
parse(limit) |
| 726 |
|
| 727 |
def test_set_memlimit(self): |
| 728 |
_4GiB = 4 * 1024 ** 3 |
| 729 |
TiB = 1024 ** 4 |
| 730 |
old_max_memuse = support.max_memuse |
| 731 |
old_real_max_memuse = support.real_max_memuse |
| 732 |
try: |
| 733 |
if sys.maxsize > 2**32: |
| 734 |
support.set_memlimit('4g') |
| 735 |
self.assertEqual(support.max_memuse, _4GiB) |
| 736 |
self.assertEqual(support.real_max_memuse, _4GiB) |
| 737 |
|
| 738 |
big = 2**100 // TiB |
| 739 |
support.set_memlimit(f'{big}t') |
| 740 |
self.assertEqual(support.max_memuse, sys.maxsize) |
| 741 |
self.assertEqual(support.real_max_memuse, big * TiB) |
| 742 |
else: |
| 743 |
support.set_memlimit('4g') |
| 744 |
self.assertEqual(support.max_memuse, sys.maxsize) |
| 745 |
self.assertEqual(support.real_max_memuse, _4GiB) |
| 746 |
finally: |
| 747 |
support.max_memuse = old_max_memuse |
| 748 |
support.real_max_memuse = old_real_max_memuse |
| 749 |
|
| 750 |
def test_copy_python_src_ignore(self): |
| 751 |
# Get source directory |
| 752 |
src_dir = sysconfig.get_config_var('abs_srcdir') |
| 753 |
if not src_dir: |
| 754 |
src_dir = sysconfig.get_config_var('srcdir') |
| 755 |
src_dir = os.path.abspath(src_dir) |
| 756 |
|
| 757 |
# Check that the source code is available |
| 758 |
if not os.path.exists(src_dir): |
| 759 |
self.skipTest(f"cannot access Python source code directory:" |
| 760 |
f" {src_dir!r}") |
| 761 |
# Check that the landmark copy_python_src_ignore() expects is available |
| 762 |
# (Previously we looked for 'Lib\os.py', which is always present on Windows.) |
| 763 |
landmark = os.path.join(src_dir, 'Modules') |
| 764 |
if not os.path.exists(landmark): |
| 765 |
self.skipTest(f"cannot access Python source code directory:" |
| 766 |
f" {landmark!r} landmark is missing") |
| 767 |
|
| 768 |
# Test support.copy_python_src_ignore() |
| 769 |
|
| 770 |
# Source code directory |
| 771 |
ignored = {'.git', '__pycache__'} |
| 772 |
names = os.listdir(src_dir) |
| 773 |
self.assertEqual(support.copy_python_src_ignore(src_dir, names), |
| 774 |
ignored | {'build'}) |
| 775 |
|
| 776 |
# Doc/ directory |
| 777 |
path = os.path.join(src_dir, 'Doc') |
| 778 |
self.assertEqual(support.copy_python_src_ignore(path, os.listdir(path)), |
| 779 |
ignored | {'build', 'venv'}) |
| 780 |
|
| 781 |
# Another directory |
| 782 |
path = os.path.join(src_dir, 'Objects') |
| 783 |
self.assertEqual(support.copy_python_src_ignore(path, os.listdir(path)), |
| 784 |
ignored) |
| 785 |
|
| 786 |
def test_get_signal_name(self): |
| 787 |
for exitcode, expected in ( |
| 788 |
(-int(signal.SIGINT), 'SIGINT'), |
| 789 |
(-int(signal.SIGSEGV), 'SIGSEGV'), |
| 790 |
(128 + int(signal.SIGABRT), 'SIGABRT'), |
| 791 |
(3221225477, "STATUS_ACCESS_VIOLATION"), |
| 792 |
(0xC00000FD, "STATUS_STACK_OVERFLOW"), |
| 793 |
(0xC0000906, "0xC0000906"), |
| 794 |
): |
| 795 |
self.assertEqual(support.get_signal_name(exitcode), expected, |
| 796 |
exitcode) |
| 797 |
|
| 798 |
def test_linked_to_musl(self): |
| 799 |
linked = support.linked_to_musl() |
| 800 |
self.assertIsNotNone(linked) |
| 801 |
if support.is_wasm32: |
| 802 |
self.assertTrue(linked) |
| 803 |
# The value is cached, so make sure it returns the same value again. |
| 804 |
self.assertIs(linked, support.linked_to_musl()) |
| 805 |
# The musl version is either triple or just a major version number. |
| 806 |
if linked: |
| 807 |
self.assertIsInstance(linked, tuple) |
| 808 |
self.assertIn(len(linked), (1, 3)) |
| 809 |
for v in linked: |
| 810 |
self.assertIsInstance(v, int) |
| 811 |
|
| 812 |
|
| 813 |
# XXX -follows a list of untested API |
| 814 |
# make_legacy_pyc |
| 815 |
# is_resource_enabled |
| 816 |
# requires |
| 817 |
# fcmp |
| 818 |
# umaks |
| 819 |
# findfile |
| 820 |
# check_warnings |
| 821 |
# EnvironmentVarGuard |
| 822 |
# transient_internet |
| 823 |
# run_with_locale |
| 824 |
# bigmemtest |
| 825 |
# precisionbigmemtest |
| 826 |
# bigaddrspacetest |
| 827 |
# requires_resource |
| 828 |
# threading_cleanup |
| 829 |
# reap_threads |
| 830 |
# can_symlink |
| 831 |
# skip_unless_symlink |
| 832 |
# SuppressCrashReport |
| 833 |
|
| 834 |
|
| 835 |
if __name__ == '__main__': |
| 836 |
unittest.main() |