| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import os |
| 6 |
import subprocess |
| 7 |
import sys |
| 8 |
import tempfile |
| 9 |
import textwrap |
| 10 |
import unittest |
| 11 |
from test import support |
| 12 |
from test.support import os_helper |
| 13 |
from test.support.script_helper import ( |
| 14 |
spawn_python, kill_python, assert_python_ok, assert_python_failure, |
| 15 |
interpreter_requires_environment |
| 16 |
) |
| 17 |
|
| 18 |
if not support.has_subprocess_support: |
| 19 |
raise unittest.SkipTest("test module requires subprocess") |
| 20 |
|
| 21 |
|
| 22 |
Py_DEBUG = hasattr(sys, "gettotalrefcount") |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
def _kill_python_and_exit_code(p): |
| 27 |
data = kill_python(p) |
| 28 |
returncode = p.wait() |
| 29 |
return data, returncode |
| 30 |
|
| 31 |
|
| 32 |
class CmdLineTest(unittest.TestCase): |
| 33 |
def test_directories(self): |
| 34 |
assert_python_failure('.') |
| 35 |
assert_python_failure('< .') |
| 36 |
|
| 37 |
def verify_valid_flag(self, cmd_line): |
| 38 |
rc, out, err = assert_python_ok(cmd_line) |
| 39 |
self.assertTrue(out == b'' or out.endswith(b'\n')) |
| 40 |
self.assertNotIn(b'Traceback', out) |
| 41 |
self.assertNotIn(b'Traceback', err) |
| 42 |
return out |
| 43 |
|
| 44 |
@support.cpython_only |
| 45 |
def test_help(self): |
| 46 |
self.verify_valid_flag('-h') |
| 47 |
self.verify_valid_flag('-?') |
| 48 |
out = self.verify_valid_flag('--help') |
| 49 |
lines = out.splitlines() |
| 50 |
self.assertIn(b'usage', lines[0]) |
| 51 |
self.assertNotIn(b'PYTHONHOME', out) |
| 52 |
self.assertNotIn(b'-X dev', out) |
| 53 |
self.assertLess(len(lines), 50) |
| 54 |
|
| 55 |
@support.cpython_only |
| 56 |
def test_help_env(self): |
| 57 |
out = self.verify_valid_flag('--help-env') |
| 58 |
self.assertIn(b'PYTHONHOME', out) |
| 59 |
|
| 60 |
@support.cpython_only |
| 61 |
def test_help_xoptions(self): |
| 62 |
out = self.verify_valid_flag('--help-xoptions') |
| 63 |
self.assertIn(b'-X dev', out) |
| 64 |
|
| 65 |
@support.cpython_only |
| 66 |
def test_help_all(self): |
| 67 |
out = self.verify_valid_flag('--help-all') |
| 68 |
lines = out.splitlines() |
| 69 |
self.assertIn(b'usage', lines[0]) |
| 70 |
self.assertIn(b'PYTHONHOME', out) |
| 71 |
self.assertIn(b'-X dev', out) |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
b''.join(lines[1:]).decode('ascii') |
| 76 |
|
| 77 |
def test_optimize(self): |
| 78 |
self.verify_valid_flag('-O') |
| 79 |
self.verify_valid_flag('-OO') |
| 80 |
|
| 81 |
def test_site_flag(self): |
| 82 |
self.verify_valid_flag('-S') |
| 83 |
|
| 84 |
@support.cpython_only |
| 85 |
def test_version(self): |
| 86 |
version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii") |
| 87 |
for switch in '-V', '--version', '-VV': |
| 88 |
rc, out, err = assert_python_ok(switch) |
| 89 |
self.assertFalse(err.startswith(version)) |
| 90 |
self.assertTrue(out.startswith(version)) |
| 91 |
|
| 92 |
def test_verbose(self): |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
rc, out, err = assert_python_ok('-v') |
| 97 |
self.assertNotIn(b'stack overflow', err) |
| 98 |
rc, out, err = assert_python_ok('-vv') |
| 99 |
self.assertNotIn(b'stack overflow', err) |
| 100 |
|
| 101 |
@unittest.skipIf(interpreter_requires_environment(), |
| 102 |
'Cannot run -E tests when PYTHON env vars are required.') |
| 103 |
def test_xoptions(self): |
| 104 |
def get_xoptions(*args): |
| 105 |
|
| 106 |
|
| 107 |
args = (sys.executable, '-E') + args |
| 108 |
args += ('-c', 'import sys; print(sys._xoptions)') |
| 109 |
out = subprocess.check_output(args) |
| 110 |
opts = eval(out.splitlines()[0]) |
| 111 |
return opts |
| 112 |
|
| 113 |
opts = get_xoptions() |
| 114 |
self.assertEqual(opts, {}) |
| 115 |
|
| 116 |
opts = get_xoptions('-Xa', '-Xb=c,d=e') |
| 117 |
self.assertEqual(opts, {'a': True, 'b': 'c,d=e'}) |
| 118 |
|
| 119 |
def test_showrefcount(self): |
| 120 |
def run_python(*args): |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
cmd = [sys.executable] |
| 125 |
cmd.extend(args) |
| 126 |
PIPE = subprocess.PIPE |
| 127 |
p = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE) |
| 128 |
out, err = p.communicate() |
| 129 |
p.stdout.close() |
| 130 |
p.stderr.close() |
| 131 |
rc = p.returncode |
| 132 |
self.assertEqual(rc, 0) |
| 133 |
return rc, out, err |
| 134 |
code = 'import sys; print(sys._xoptions)' |
| 135 |
|
| 136 |
rc, out, err = run_python('-c', code) |
| 137 |
self.assertEqual(out.rstrip(), b'{}') |
| 138 |
self.assertEqual(err, b'') |
| 139 |
|
| 140 |
rc, out, err = run_python('-I', '-X', 'showrefcount', '-c', code) |
| 141 |
self.assertEqual(out.rstrip(), b"{'showrefcount': True}") |
| 142 |
if Py_DEBUG: |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
self.assertRegex(err, br'^\[-?\d+ refs, \d+ blocks\]') |
| 147 |
else: |
| 148 |
self.assertEqual(err, b'') |
| 149 |
|
| 150 |
@support.cpython_only |
| 151 |
def test_xoption_frozen_modules(self): |
| 152 |
tests = { |
| 153 |
('=on', 'FrozenImporter'), |
| 154 |
('=off', 'SourceFileLoader'), |
| 155 |
('=', 'FrozenImporter'), |
| 156 |
('', 'FrozenImporter'), |
| 157 |
} |
| 158 |
for raw, expected in tests: |
| 159 |
cmd = ['-X', f'frozen_modules{raw}', |
| 160 |
'-c', 'import os; print(os.__spec__.loader, end="")'] |
| 161 |
with self.subTest(raw): |
| 162 |
res = assert_python_ok(*cmd) |
| 163 |
self.assertRegex(res.out.decode('utf-8'), expected) |
| 164 |
|
| 165 |
def test_run_module(self): |
| 166 |
|
| 167 |
|
| 168 |
assert_python_failure('-m') |
| 169 |
|
| 170 |
assert_python_failure('-m', 'fnord43520xyz') |
| 171 |
|
| 172 |
|
| 173 |
assert_python_failure('-m', 'runpy', 'fnord43520xyz') |
| 174 |
|
| 175 |
assert_python_ok('-m', 'timeit', '-n', '1') |
| 176 |
|
| 177 |
def test_run_module_bug1764407(self): |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
p = spawn_python('-i', '-m', 'timeit', '-n', '1') |
| 182 |
p.stdin.write(b'Timer\n') |
| 183 |
p.stdin.write(b'exit()\n') |
| 184 |
data = kill_python(p) |
| 185 |
self.assertTrue(data.find(b'1 loop') != -1) |
| 186 |
self.assertTrue(data.find(b'__main__.Timer') != -1) |
| 187 |
|
| 188 |
def test_relativedir_bug46421(self): |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
projectlibpath = os.path.dirname(__file__).removesuffix("test") |
| 193 |
with os_helper.change_cwd(projectlibpath): |
| 194 |
|
| 195 |
assert_python_ok('-m', 'unittest', "test/test_longexp.py") |
| 196 |
assert_python_ok('-m', 'unittest', "./test/test_longexp.py") |
| 197 |
|
| 198 |
def test_run_code(self): |
| 199 |
|
| 200 |
|
| 201 |
assert_python_failure('-c') |
| 202 |
|
| 203 |
assert_python_failure('-c', 'raise Exception') |
| 204 |
|
| 205 |
assert_python_ok('-c', 'pass') |
| 206 |
|
| 207 |
@unittest.skipUnless(os_helper.FS_NONASCII, 'need os_helper.FS_NONASCII') |
| 208 |
def test_non_ascii(self): |
| 209 |
|
| 210 |
command = ("assert(ord(%r) == %s)" |
| 211 |
% (os_helper.FS_NONASCII, ord(os_helper.FS_NONASCII))) |
| 212 |
assert_python_ok('-c', command) |
| 213 |
|
| 214 |
@unittest.skipUnless(os_helper.FS_NONASCII, 'need os_helper.FS_NONASCII') |
| 215 |
def test_coding(self): |
| 216 |
|
| 217 |
ch = os_helper.FS_NONASCII |
| 218 |
cmd = f"# coding: latin1\nprint(ascii('{ch}'))" |
| 219 |
res = assert_python_ok('-c', cmd) |
| 220 |
self.assertEqual(res.out.rstrip(), ascii(ch).encode('ascii')) |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
@unittest.skipIf(sys.platform == 'win32', |
| 227 |
'Windows has a native unicode API') |
| 228 |
def test_undecodable_code(self): |
| 229 |
undecodable = b"\xff" |
| 230 |
env = os.environ.copy() |
| 231 |
|
| 232 |
env['LC_ALL'] = 'C' |
| 233 |
env['PYTHONCOERCECLOCALE'] = '0' |
| 234 |
code = ( |
| 235 |
b'import locale; ' |
| 236 |
b'print(ascii("' + undecodable + b'"), ' |
| 237 |
b'locale.getencoding())') |
| 238 |
p = subprocess.Popen( |
| 239 |
[sys.executable, "-c", code], |
| 240 |
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, |
| 241 |
env=env) |
| 242 |
stdout, stderr = p.communicate() |
| 243 |
if p.returncode == 1: |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
pattern = b"Unable to decode the command from the command line:" |
| 249 |
elif p.returncode == 0: |
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
pattern = b"'\\xff' " |
| 254 |
|
| 255 |
|
| 256 |
else: |
| 257 |
raise AssertionError("Unknown exit code: %s, output=%a" % (p.returncode, stdout)) |
| 258 |
if not stdout.startswith(pattern): |
| 259 |
raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) |
| 260 |
|
| 261 |
@unittest.skipIf(sys.platform == 'win32', |
| 262 |
'Windows has a native unicode API') |
| 263 |
def test_invalid_utf8_arg(self): |
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
code = 'import sys, os; s=os.fsencode(sys.argv[1]); print(ascii(s))' |
| 271 |
|
| 272 |
def run_default(arg): |
| 273 |
cmd = [sys.executable, '-c', code, arg] |
| 274 |
return subprocess.run(cmd, stdout=subprocess.PIPE, text=True) |
| 275 |
|
| 276 |
def run_c_locale(arg): |
| 277 |
cmd = [sys.executable, '-c', code, arg] |
| 278 |
env = dict(os.environ) |
| 279 |
env['LC_ALL'] = 'C' |
| 280 |
return subprocess.run(cmd, stdout=subprocess.PIPE, |
| 281 |
text=True, env=env) |
| 282 |
|
| 283 |
def run_utf8_mode(arg): |
| 284 |
cmd = [sys.executable, '-X', 'utf8', '-c', code, arg] |
| 285 |
return subprocess.run(cmd, stdout=subprocess.PIPE, text=True) |
| 286 |
|
| 287 |
valid_utf8 = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8') |
| 288 |
|
| 289 |
|
| 290 |
invalid_utf8 = ( |
| 291 |
b'\xff' |
| 292 |
b'\xc3\xff' |
| 293 |
b'\xc3\xa9' |
| 294 |
b'\xed\xa0\x80' |
| 295 |
b'\xfd\xbf\xbf\xbb\xba\xba' |
| 296 |
) |
| 297 |
test_args = [valid_utf8, invalid_utf8] |
| 298 |
|
| 299 |
for run_cmd in (run_default, run_c_locale, run_utf8_mode): |
| 300 |
with self.subTest(run_cmd=run_cmd): |
| 301 |
for arg in test_args: |
| 302 |
proc = run_cmd(arg) |
| 303 |
self.assertEqual(proc.stdout.rstrip(), ascii(arg)) |
| 304 |
|
| 305 |
@unittest.skipUnless((sys.platform == 'darwin' or |
| 306 |
support.is_android), 'test specific to Mac OS X and Android') |
| 307 |
def test_osx_android_utf8(self): |
| 308 |
text = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8') |
| 309 |
code = "import sys; print(ascii(sys.argv[1]))" |
| 310 |
|
| 311 |
decoded = text.decode('utf-8', 'surrogateescape') |
| 312 |
expected = ascii(decoded).encode('ascii') + b'\n' |
| 313 |
|
| 314 |
env = os.environ.copy() |
| 315 |
|
| 316 |
|
| 317 |
env['LC_ALL'] = 'C' |
| 318 |
|
| 319 |
p = subprocess.Popen( |
| 320 |
(sys.executable, "-c", code, text), |
| 321 |
stdout=subprocess.PIPE, |
| 322 |
env=env) |
| 323 |
stdout, stderr = p.communicate() |
| 324 |
self.assertEqual(stdout, expected) |
| 325 |
self.assertEqual(p.returncode, 0) |
| 326 |
|
| 327 |
def test_non_interactive_output_buffering(self): |
| 328 |
code = textwrap.dedent(""" |
| 329 |
import sys |
| 330 |
out = sys.stdout |
| 331 |
print(out.isatty(), out.write_through, out.line_buffering) |
| 332 |
err = sys.stderr |
| 333 |
print(err.isatty(), err.write_through, err.line_buffering) |
| 334 |
""") |
| 335 |
args = [sys.executable, '-c', code] |
| 336 |
proc = subprocess.run(args, stdout=subprocess.PIPE, |
| 337 |
stderr=subprocess.PIPE, text=True, check=True) |
| 338 |
self.assertEqual(proc.stdout, |
| 339 |
'False False False\n' |
| 340 |
'False False True\n') |
| 341 |
|
| 342 |
def test_unbuffered_output(self): |
| 343 |
|
| 344 |
for stream in ('stdout', 'stderr'): |
| 345 |
|
| 346 |
code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)" |
| 347 |
% stream) |
| 348 |
rc, out, err = assert_python_ok('-u', '-c', code) |
| 349 |
data = err if stream == 'stderr' else out |
| 350 |
self.assertEqual(data, b'x', "binary %s not unbuffered" % stream) |
| 351 |
|
| 352 |
code = ("import os, sys; sys.%s.write('x'); os._exit(0)" |
| 353 |
% stream) |
| 354 |
rc, out, err = assert_python_ok('-u', '-c', code) |
| 355 |
data = err if stream == 'stderr' else out |
| 356 |
self.assertEqual(data, b'x', "text %s not unbuffered" % stream) |
| 357 |
|
| 358 |
def test_unbuffered_input(self): |
| 359 |
|
| 360 |
code = ("import sys; sys.stdout.write(sys.stdin.read(1))") |
| 361 |
p = spawn_python('-u', '-c', code) |
| 362 |
p.stdin.write(b'x') |
| 363 |
p.stdin.flush() |
| 364 |
data, rc = _kill_python_and_exit_code(p) |
| 365 |
self.assertEqual(rc, 0) |
| 366 |
self.assertTrue(data.startswith(b'x'), data) |
| 367 |
|
| 368 |
def test_large_PYTHONPATH(self): |
| 369 |
path1 = "ABCDE" * 100 |
| 370 |
path2 = "FGHIJ" * 100 |
| 371 |
path = path1 + os.pathsep + path2 |
| 372 |
|
| 373 |
code = """if 1: |
| 374 |
import sys |
| 375 |
path = ":".join(sys.path) |
| 376 |
path = path.encode("ascii", "backslashreplace") |
| 377 |
sys.stdout.buffer.write(path)""" |
| 378 |
rc, out, err = assert_python_ok('-S', '-c', code, |
| 379 |
PYTHONPATH=path) |
| 380 |
self.assertIn(path1.encode('ascii'), out) |
| 381 |
self.assertIn(path2.encode('ascii'), out) |
| 382 |
|
| 383 |
@unittest.skipIf(sys.flags.safe_path, |
| 384 |
'PYTHONSAFEPATH changes default sys.path') |
| 385 |
def test_empty_PYTHONPATH_issue16309(self): |
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
code = """if 1: |
| 392 |
import sys |
| 393 |
path = ":".join(sys.path) |
| 394 |
path = path.encode("ascii", "backslashreplace") |
| 395 |
sys.stdout.buffer.write(path)""" |
| 396 |
rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="") |
| 397 |
rc2, out2, err2 = assert_python_ok('-c', code, __isolated=False) |
| 398 |
|
| 399 |
|
| 400 |
self.assertEqual(out1, out2) |
| 401 |
|
| 402 |
def test_displayhook_unencodable(self): |
| 403 |
for encoding in ('ascii', 'latin-1', 'utf-8'): |
| 404 |
env = os.environ.copy() |
| 405 |
env['PYTHONIOENCODING'] = encoding |
| 406 |
p = subprocess.Popen( |
| 407 |
[sys.executable, '-i'], |
| 408 |
stdin=subprocess.PIPE, |
| 409 |
stdout=subprocess.PIPE, |
| 410 |
stderr=subprocess.STDOUT, |
| 411 |
env=env) |
| 412 |
|
| 413 |
text = "a=\xe9 b=\uDC80 c=\U00010000 d=\U0010FFFF" |
| 414 |
p.stdin.write(ascii(text).encode('ascii') + b"\n") |
| 415 |
p.stdin.write(b'exit()\n') |
| 416 |
data = kill_python(p) |
| 417 |
escaped = repr(text).encode(encoding, 'backslashreplace') |
| 418 |
self.assertIn(escaped, data) |
| 419 |
|
| 420 |
def check_input(self, code, expected): |
| 421 |
with tempfile.NamedTemporaryFile("wb+") as stdin: |
| 422 |
sep = os.linesep.encode('ASCII') |
| 423 |
stdin.write(sep.join((b'abc', b'def'))) |
| 424 |
stdin.flush() |
| 425 |
stdin.seek(0) |
| 426 |
with subprocess.Popen( |
| 427 |
(sys.executable, "-c", code), |
| 428 |
stdin=stdin, stdout=subprocess.PIPE) as proc: |
| 429 |
stdout, stderr = proc.communicate() |
| 430 |
self.assertEqual(stdout.rstrip(), expected) |
| 431 |
|
| 432 |
def test_stdin_readline(self): |
| 433 |
|
| 434 |
|
| 435 |
self.check_input( |
| 436 |
"import sys; print(repr(sys.stdin.readline()))", |
| 437 |
b"'abc\\n'") |
| 438 |
|
| 439 |
def test_builtin_input(self): |
| 440 |
|
| 441 |
self.check_input( |
| 442 |
"print(repr(input()))", |
| 443 |
b"'abc'") |
| 444 |
|
| 445 |
def test_output_newline(self): |
| 446 |
|
| 447 |
code = """if 1: |
| 448 |
import sys |
| 449 |
print(1) |
| 450 |
print(2) |
| 451 |
print(3, file=sys.stderr) |
| 452 |
print(4, file=sys.stderr)""" |
| 453 |
rc, out, err = assert_python_ok('-c', code) |
| 454 |
|
| 455 |
if sys.platform == 'win32': |
| 456 |
self.assertEqual(b'1\r\n2\r\n', out) |
| 457 |
self.assertEqual(b'3\r\n4\r\n', err) |
| 458 |
else: |
| 459 |
self.assertEqual(b'1\n2\n', out) |
| 460 |
self.assertEqual(b'3\n4\n', err) |
| 461 |
|
| 462 |
def test_unmached_quote(self): |
| 463 |
|
| 464 |
|
| 465 |
rc, out, err = assert_python_failure('-c', "'") |
| 466 |
self.assertRegex(err.decode('ascii', 'ignore'), 'SyntaxError') |
| 467 |
self.assertEqual(b'', out) |
| 468 |
|
| 469 |
def test_stdout_flush_at_shutdown(self): |
| 470 |
|
| 471 |
|
| 472 |
code = """if 1: |
| 473 |
import os, sys, test.support |
| 474 |
test.support.SuppressCrashReport().__enter__() |
| 475 |
sys.stdout.write('x') |
| 476 |
os.close(sys.stdout.fileno())""" |
| 477 |
rc, out, err = assert_python_failure('-c', code) |
| 478 |
self.assertEqual(b'', out) |
| 479 |
self.assertEqual(120, rc) |
| 480 |
self.assertRegex(err.decode('ascii', 'ignore'), |
| 481 |
'Exception ignored in.*\nOSError: .*') |
| 482 |
|
| 483 |
def test_closed_stdout(self): |
| 484 |
|
| 485 |
|
| 486 |
code = "import sys; sys.stdout.close()" |
| 487 |
rc, out, err = assert_python_ok('-c', code) |
| 488 |
self.assertEqual(b'', err) |
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
@unittest.skipIf(os.name != 'posix', "test needs POSIX semantics") |
| 493 |
@unittest.skipIf(sys.platform == "vxworks", |
| 494 |
"test needs preexec support in subprocess.Popen") |
| 495 |
def _test_no_stdio(self, streams): |
| 496 |
code = """if 1: |
| 497 |
import os, sys |
| 498 |
for i, s in enumerate({streams}): |
| 499 |
if getattr(sys, s) is not None: |
| 500 |
os._exit(i + 1) |
| 501 |
os._exit(42)""".format(streams=streams) |
| 502 |
def preexec(): |
| 503 |
if 'stdin' in streams: |
| 504 |
os.close(0) |
| 505 |
if 'stdout' in streams: |
| 506 |
os.close(1) |
| 507 |
if 'stderr' in streams: |
| 508 |
os.close(2) |
| 509 |
p = subprocess.Popen( |
| 510 |
[sys.executable, "-E", "-c", code], |
| 511 |
stdin=subprocess.PIPE, |
| 512 |
stdout=subprocess.PIPE, |
| 513 |
stderr=subprocess.PIPE, |
| 514 |
preexec_fn=preexec) |
| 515 |
out, err = p.communicate() |
| 516 |
self.assertEqual(err, b'') |
| 517 |
self.assertEqual(p.returncode, 42) |
| 518 |
|
| 519 |
def test_no_stdin(self): |
| 520 |
self._test_no_stdio(['stdin']) |
| 521 |
|
| 522 |
def test_no_stdout(self): |
| 523 |
self._test_no_stdio(['stdout']) |
| 524 |
|
| 525 |
def test_no_stderr(self): |
| 526 |
self._test_no_stdio(['stderr']) |
| 527 |
|
| 528 |
def test_no_std_streams(self): |
| 529 |
self._test_no_stdio(['stdin', 'stdout', 'stderr']) |
| 530 |
|
| 531 |
@support.impl_detail('no hash randomization on PyPy', pypy=False) |
| 532 |
def test_hash_randomization(self): |
| 533 |
|
| 534 |
self.verify_valid_flag('-R') |
| 535 |
hashes = [] |
| 536 |
if os.environ.get('PYTHONHASHSEED', 'random') != 'random': |
| 537 |
env = dict(os.environ) |
| 538 |
|
| 539 |
|
| 540 |
del env['PYTHONHASHSEED'] |
| 541 |
env['__cleanenv'] = '1' |
| 542 |
else: |
| 543 |
env = {} |
| 544 |
for i in range(3): |
| 545 |
code = 'print(hash("spam"))' |
| 546 |
rc, out, err = assert_python_ok('-c', code, **env) |
| 547 |
self.assertEqual(rc, 0) |
| 548 |
hashes.append(out) |
| 549 |
hashes = sorted(set(hashes)) |
| 550 |
|
| 551 |
self.assertGreater(len(hashes), 1, |
| 552 |
msg='3 runs produced an identical random hash ' |
| 553 |
' for "spam": {}'.format(hashes)) |
| 554 |
|
| 555 |
|
| 556 |
code = 'import sys; print("random is", sys.flags.hash_randomization)' |
| 557 |
rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='') |
| 558 |
self.assertIn(b'random is 1', out) |
| 559 |
|
| 560 |
rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='random') |
| 561 |
self.assertIn(b'random is 1', out) |
| 562 |
|
| 563 |
rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='0') |
| 564 |
self.assertIn(b'random is 0', out) |
| 565 |
|
| 566 |
rc, out, err = assert_python_ok('-R', '-c', code, PYTHONHASHSEED='0') |
| 567 |
self.assertIn(b'random is 1', out) |
| 568 |
|
| 569 |
def test_del___main__(self): |
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
filename = os_helper.TESTFN |
| 574 |
self.addCleanup(os_helper.unlink, filename) |
| 575 |
with open(filename, "w", encoding="utf-8") as script: |
| 576 |
print("import sys", file=script) |
| 577 |
print("del sys.modules['__main__']", file=script) |
| 578 |
assert_python_ok(filename) |
| 579 |
|
| 580 |
@support.cpython_only |
| 581 |
def test_unknown_options(self): |
| 582 |
rc, out, err = assert_python_failure('-E', '-z') |
| 583 |
self.assertIn(b'Unknown option: -z', err) |
| 584 |
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1) |
| 585 |
self.assertEqual(b'', out) |
| 586 |
|
| 587 |
|
| 588 |
rc, out, err = assert_python_failure('-z', without='-E') |
| 589 |
self.assertIn(b'Unknown option: -z', err) |
| 590 |
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1) |
| 591 |
self.assertEqual(b'', out) |
| 592 |
rc, out, err = assert_python_failure('-a', '-z', without='-E') |
| 593 |
self.assertIn(b'Unknown option: -a', err) |
| 594 |
|
| 595 |
self.assertNotIn(b'Unknown option: -z', err) |
| 596 |
self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1) |
| 597 |
self.assertEqual(b'', out) |
| 598 |
|
| 599 |
@unittest.skipIf(interpreter_requires_environment(), |
| 600 |
'Cannot run -I tests when PYTHON env vars are required.') |
| 601 |
def test_isolatedmode(self): |
| 602 |
self.verify_valid_flag('-I') |
| 603 |
self.verify_valid_flag('-IEPs') |
| 604 |
rc, out, err = assert_python_ok('-I', '-c', |
| 605 |
'from sys import flags as f; ' |
| 606 |
'print(f.no_user_site, f.ignore_environment, f.isolated, f.safe_path)', |
| 607 |
|
| 608 |
dummyvar="") |
| 609 |
self.assertEqual(out.strip(), b'1 1 1 True') |
| 610 |
with os_helper.temp_cwd() as tmpdir: |
| 611 |
fake = os.path.join(tmpdir, "uuid.py") |
| 612 |
main = os.path.join(tmpdir, "main.py") |
| 613 |
with open(fake, "w", encoding="utf-8") as f: |
| 614 |
f.write("raise RuntimeError('isolated mode test')\n") |
| 615 |
with open(main, "w", encoding="utf-8") as f: |
| 616 |
f.write("import uuid\n") |
| 617 |
f.write("print('ok')\n") |
| 618 |
|
| 619 |
self.assertRaises(subprocess.CalledProcessError, |
| 620 |
subprocess.check_output, |
| 621 |
[sys.executable, '-E', main], cwd=tmpdir, |
| 622 |
stderr=subprocess.DEVNULL) |
| 623 |
out = subprocess.check_output([sys.executable, "-I", main], |
| 624 |
cwd=tmpdir) |
| 625 |
self.assertEqual(out.strip(), b"ok") |
| 626 |
|
| 627 |
def test_sys_flags_set(self): |
| 628 |
|
| 629 |
for value, expected in (("", 0), ("1", 1), ("text", 1), ("2", 2)): |
| 630 |
env_vars = dict( |
| 631 |
PYTHONDEBUG=value, |
| 632 |
PYTHONOPTIMIZE=value, |
| 633 |
PYTHONDONTWRITEBYTECODE=value, |
| 634 |
PYTHONVERBOSE=value, |
| 635 |
) |
| 636 |
dont_write_bytecode = int(bool(value)) |
| 637 |
code = ( |
| 638 |
"import sys; " |
| 639 |
"sys.stderr.write(str(sys.flags)); " |
| 640 |
f"""sys.exit(not ( |
| 641 |
sys.flags.debug == sys.flags.optimize == |
| 642 |
sys.flags.verbose == |
| 643 |
{expected} |
| 644 |
and sys.flags.dont_write_bytecode == {dont_write_bytecode} |
| 645 |
))""" |
| 646 |
) |
| 647 |
with self.subTest(envar_value=value): |
| 648 |
assert_python_ok('-c', code, **env_vars) |
| 649 |
|
| 650 |
def test_set_pycache_prefix(self): |
| 651 |
|
| 652 |
|
| 653 |
NO_VALUE = object() |
| 654 |
cases = [ |
| 655 |
|
| 656 |
(None, None, None), |
| 657 |
('foo', None, 'foo'), |
| 658 |
(None, 'bar', 'bar'), |
| 659 |
('foo', 'bar', 'bar'), |
| 660 |
('foo', '', None), |
| 661 |
('foo', NO_VALUE, None), |
| 662 |
] |
| 663 |
for envval, opt, expected in cases: |
| 664 |
exp_clause = "is None" if expected is None else f'== "{expected}"' |
| 665 |
code = f"import sys; sys.exit(not sys.pycache_prefix {exp_clause})" |
| 666 |
args = ['-c', code] |
| 667 |
env = {} if envval is None else {'PYTHONPYCACHEPREFIX': envval} |
| 668 |
if opt is NO_VALUE: |
| 669 |
args[:0] = ['-X', 'pycache_prefix'] |
| 670 |
elif opt is not None: |
| 671 |
args[:0] = ['-X', f'pycache_prefix={opt}'] |
| 672 |
with self.subTest(envval=envval, opt=opt): |
| 673 |
with os_helper.temp_cwd(): |
| 674 |
assert_python_ok(*args, **env) |
| 675 |
|
| 676 |
def run_xdev(self, *args, check_exitcode=True, xdev=True): |
| 677 |
env = dict(os.environ) |
| 678 |
env.pop('PYTHONWARNINGS', None) |
| 679 |
env.pop('PYTHONDEVMODE', None) |
| 680 |
env.pop('PYTHONMALLOC', None) |
| 681 |
|
| 682 |
if xdev: |
| 683 |
args = (sys.executable, '-X', 'dev', *args) |
| 684 |
else: |
| 685 |
args = (sys.executable, *args) |
| 686 |
proc = subprocess.run(args, |
| 687 |
stdout=subprocess.PIPE, |
| 688 |
stderr=subprocess.STDOUT, |
| 689 |
universal_newlines=True, |
| 690 |
env=env) |
| 691 |
if check_exitcode: |
| 692 |
self.assertEqual(proc.returncode, 0, proc) |
| 693 |
return proc.stdout.rstrip() |
| 694 |
|
| 695 |
@support.cpython_only |
| 696 |
def test_xdev(self): |
| 697 |
|
| 698 |
code = "import sys; print(sys.flags.dev_mode)" |
| 699 |
out = self.run_xdev("-c", code, xdev=False) |
| 700 |
self.assertEqual(out, "False") |
| 701 |
out = self.run_xdev("-c", code) |
| 702 |
self.assertEqual(out, "True") |
| 703 |
|
| 704 |
|
| 705 |
code = ("import warnings; " |
| 706 |
"print(' '.join('%s::%s' % (f[0], f[2].__name__) " |
| 707 |
"for f in warnings.filters))") |
| 708 |
if Py_DEBUG: |
| 709 |
expected_filters = "default::Warning" |
| 710 |
else: |
| 711 |
expected_filters = ("default::Warning " |
| 712 |
"default::DeprecationWarning " |
| 713 |
"ignore::DeprecationWarning " |
| 714 |
"ignore::PendingDeprecationWarning " |
| 715 |
"ignore::ImportWarning " |
| 716 |
"ignore::ResourceWarning") |
| 717 |
|
| 718 |
out = self.run_xdev("-c", code) |
| 719 |
self.assertEqual(out, expected_filters) |
| 720 |
|
| 721 |
out = self.run_xdev("-b", "-c", code) |
| 722 |
self.assertEqual(out, f"default::BytesWarning {expected_filters}") |
| 723 |
|
| 724 |
out = self.run_xdev("-bb", "-c", code) |
| 725 |
self.assertEqual(out, f"error::BytesWarning {expected_filters}") |
| 726 |
|
| 727 |
out = self.run_xdev("-Werror", "-c", code) |
| 728 |
self.assertEqual(out, f"error::Warning {expected_filters}") |
| 729 |
|
| 730 |
|
| 731 |
try: |
| 732 |
import _testcapi |
| 733 |
except ImportError: |
| 734 |
pass |
| 735 |
else: |
| 736 |
code = "import _testcapi; print(_testcapi.pymem_getallocatorsname())" |
| 737 |
with support.SuppressCrashReport(): |
| 738 |
out = self.run_xdev("-c", code, check_exitcode=False) |
| 739 |
if support.with_pymalloc(): |
| 740 |
alloc_name = "pymalloc_debug" |
| 741 |
else: |
| 742 |
alloc_name = "malloc_debug" |
| 743 |
self.assertEqual(out, alloc_name) |
| 744 |
|
| 745 |
|
| 746 |
try: |
| 747 |
import faulthandler |
| 748 |
except ImportError: |
| 749 |
pass |
| 750 |
else: |
| 751 |
code = "import faulthandler; print(faulthandler.is_enabled())" |
| 752 |
out = self.run_xdev("-c", code) |
| 753 |
self.assertEqual(out, "True") |
| 754 |
|
| 755 |
def check_warnings_filters(self, cmdline_option, envvar, use_pywarning=False): |
| 756 |
if use_pywarning: |
| 757 |
code = ("import sys; from test.support.import_helper import " |
| 758 |
"import_fresh_module; " |
| 759 |
"warnings = import_fresh_module('warnings', blocked=['_warnings']); ") |
| 760 |
else: |
| 761 |
code = "import sys, warnings; " |
| 762 |
code += ("print(' '.join('%s::%s' % (f[0], f[2].__name__) " |
| 763 |
"for f in warnings.filters))") |
| 764 |
args = (sys.executable, '-W', cmdline_option, '-bb', '-c', code) |
| 765 |
env = dict(os.environ) |
| 766 |
env.pop('PYTHONDEVMODE', None) |
| 767 |
env["PYTHONWARNINGS"] = envvar |
| 768 |
proc = subprocess.run(args, |
| 769 |
stdout=subprocess.PIPE, |
| 770 |
stderr=subprocess.STDOUT, |
| 771 |
universal_newlines=True, |
| 772 |
env=env) |
| 773 |
self.assertEqual(proc.returncode, 0, proc) |
| 774 |
return proc.stdout.rstrip() |
| 775 |
|
| 776 |
def test_warnings_filter_precedence(self): |
| 777 |
expected_filters = ("error::BytesWarning " |
| 778 |
"once::UserWarning " |
| 779 |
"always::UserWarning") |
| 780 |
if not Py_DEBUG: |
| 781 |
expected_filters += (" " |
| 782 |
"default::DeprecationWarning " |
| 783 |
"ignore::DeprecationWarning " |
| 784 |
"ignore::PendingDeprecationWarning " |
| 785 |
"ignore::ImportWarning " |
| 786 |
"ignore::ResourceWarning") |
| 787 |
|
| 788 |
out = self.check_warnings_filters("once::UserWarning", |
| 789 |
"always::UserWarning") |
| 790 |
self.assertEqual(out, expected_filters) |
| 791 |
|
| 792 |
out = self.check_warnings_filters("once::UserWarning", |
| 793 |
"always::UserWarning", |
| 794 |
use_pywarning=True) |
| 795 |
self.assertEqual(out, expected_filters) |
| 796 |
|
| 797 |
def check_pythonmalloc(self, env_var, name): |
| 798 |
code = 'import _testcapi; print(_testcapi.pymem_getallocatorsname())' |
| 799 |
env = dict(os.environ) |
| 800 |
env.pop('PYTHONDEVMODE', None) |
| 801 |
if env_var is not None: |
| 802 |
env['PYTHONMALLOC'] = env_var |
| 803 |
else: |
| 804 |
env.pop('PYTHONMALLOC', None) |
| 805 |
args = (sys.executable, '-c', code) |
| 806 |
proc = subprocess.run(args, |
| 807 |
stdout=subprocess.PIPE, |
| 808 |
stderr=subprocess.STDOUT, |
| 809 |
universal_newlines=True, |
| 810 |
env=env) |
| 811 |
self.assertEqual(proc.stdout.rstrip(), name) |
| 812 |
self.assertEqual(proc.returncode, 0) |
| 813 |
|
| 814 |
@support.impl_detail('no malloc options on PyPy', pypy=False) |
| 815 |
def test_pythonmalloc(self): |
| 816 |
|
| 817 |
try: |
| 818 |
pymalloc = support.with_pymalloc() |
| 819 |
except AtributeError: |
| 820 |
pymalloc = None |
| 821 |
if pymalloc: |
| 822 |
default_name = 'pymalloc_debug' if Py_DEBUG else 'pymalloc' |
| 823 |
default_name_debug = 'pymalloc_debug' |
| 824 |
else: |
| 825 |
default_name = 'malloc_debug' if Py_DEBUG else 'malloc' |
| 826 |
default_name_debug = 'malloc_debug' |
| 827 |
|
| 828 |
tests = [ |
| 829 |
(None, default_name), |
| 830 |
('debug', default_name_debug), |
| 831 |
('malloc', 'malloc'), |
| 832 |
('malloc_debug', 'malloc_debug'), |
| 833 |
] |
| 834 |
if pymalloc: |
| 835 |
tests.extend(( |
| 836 |
('pymalloc', 'pymalloc'), |
| 837 |
('pymalloc_debug', 'pymalloc_debug'), |
| 838 |
)) |
| 839 |
|
| 840 |
for env_var, name in tests: |
| 841 |
with self.subTest(env_var=env_var, name=name): |
| 842 |
self.check_pythonmalloc(env_var, name) |
| 843 |
|
| 844 |
def test_pythondevmode_env(self): |
| 845 |
|
| 846 |
code = "import sys; print(sys.flags.dev_mode)" |
| 847 |
env = dict(os.environ) |
| 848 |
env.pop('PYTHONDEVMODE', None) |
| 849 |
args = (sys.executable, '-c', code) |
| 850 |
|
| 851 |
proc = subprocess.run(args, stdout=subprocess.PIPE, |
| 852 |
universal_newlines=True, env=env) |
| 853 |
self.assertEqual(proc.stdout.rstrip(), 'False') |
| 854 |
self.assertEqual(proc.returncode, 0, proc) |
| 855 |
|
| 856 |
env['PYTHONDEVMODE'] = '1' |
| 857 |
proc = subprocess.run(args, stdout=subprocess.PIPE, |
| 858 |
universal_newlines=True, env=env) |
| 859 |
self.assertEqual(proc.stdout.rstrip(), 'True') |
| 860 |
self.assertEqual(proc.returncode, 0, proc) |
| 861 |
|
| 862 |
@unittest.skipUnless(sys.platform == 'win32', |
| 863 |
'bpo-32457 only applies on Windows') |
| 864 |
def test_argv0_normalization(self): |
| 865 |
args = sys.executable, '-c', 'print(0)' |
| 866 |
prefix, exe = os.path.split(sys.executable) |
| 867 |
executable = prefix + '\\.\\.\\.\\' + exe |
| 868 |
|
| 869 |
proc = subprocess.run(args, stdout=subprocess.PIPE, |
| 870 |
executable=executable) |
| 871 |
self.assertEqual(proc.returncode, 0, proc) |
| 872 |
self.assertEqual(proc.stdout.strip(), b'0') |
| 873 |
|
| 874 |
@support.cpython_only |
| 875 |
def test_parsing_error(self): |
| 876 |
args = [sys.executable, '-I', '--unknown-option'] |
| 877 |
proc = subprocess.run(args, |
| 878 |
stdout=subprocess.PIPE, |
| 879 |
stderr=subprocess.PIPE, |
| 880 |
text=True) |
| 881 |
err_msg = "unknown option --unknown-option\nusage: " |
| 882 |
self.assertTrue(proc.stderr.startswith(err_msg), proc.stderr) |
| 883 |
self.assertNotEqual(proc.returncode, 0) |
| 884 |
|
| 885 |
def test_int_max_str_digits(self): |
| 886 |
code = "import sys; print(sys.flags.int_max_str_digits, sys.get_int_max_str_digits())" |
| 887 |
|
| 888 |
assert_python_failure('-X', 'int_max_str_digits', '-c', code) |
| 889 |
assert_python_failure('-X', 'int_max_str_digits=foo', '-c', code) |
| 890 |
assert_python_failure('-X', 'int_max_str_digits=100', '-c', code) |
| 891 |
assert_python_failure('-X', 'int_max_str_digits', '-c', code, |
| 892 |
PYTHONINTMAXSTRDIGITS='4000') |
| 893 |
|
| 894 |
assert_python_failure('-c', code, PYTHONINTMAXSTRDIGITS='foo') |
| 895 |
assert_python_failure('-c', code, PYTHONINTMAXSTRDIGITS='100') |
| 896 |
|
| 897 |
def res2int(res): |
| 898 |
out = res.out.strip().decode("utf-8") |
| 899 |
return tuple(int(i) for i in out.split()) |
| 900 |
|
| 901 |
res = assert_python_ok('-c', code) |
| 902 |
self.assertEqual(res2int(res), (-1, sys.get_int_max_str_digits())) |
| 903 |
res = assert_python_ok('-X', 'int_max_str_digits=0', '-c', code) |
| 904 |
self.assertEqual(res2int(res), (0, 0)) |
| 905 |
res = assert_python_ok('-X', 'int_max_str_digits=4000', '-c', code) |
| 906 |
self.assertEqual(res2int(res), (4000, 4000)) |
| 907 |
res = assert_python_ok('-X', 'int_max_str_digits=100000', '-c', code) |
| 908 |
self.assertEqual(res2int(res), (100000, 100000)) |
| 909 |
|
| 910 |
res = assert_python_ok('-c', code, PYTHONINTMAXSTRDIGITS='0') |
| 911 |
self.assertEqual(res2int(res), (0, 0)) |
| 912 |
res = assert_python_ok('-c', code, PYTHONINTMAXSTRDIGITS='4000') |
| 913 |
self.assertEqual(res2int(res), (4000, 4000)) |
| 914 |
res = assert_python_ok( |
| 915 |
'-X', 'int_max_str_digits=6000', '-c', code, |
| 916 |
PYTHONINTMAXSTRDIGITS='4000' |
| 917 |
) |
| 918 |
self.assertEqual(res2int(res), (6000, 6000)) |
| 919 |
|
| 920 |
|
| 921 |
@unittest.skipIf(interpreter_requires_environment(), |
| 922 |
'Cannot run -I tests when PYTHON env vars are required.') |
| 923 |
class IgnoreEnvironmentTest(unittest.TestCase): |
| 924 |
|
| 925 |
def run_ignoring_vars(self, predicate, **env_vars): |
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
code = "import sys; sys.stderr.write(str(sys.flags)); sys.exit(not ({}))".format(predicate) |
| 931 |
return assert_python_ok('-E', '-c', code, **env_vars) |
| 932 |
|
| 933 |
def test_ignore_PYTHONPATH(self): |
| 934 |
path = "should_be_ignored" |
| 935 |
self.run_ignoring_vars("'{}' not in sys.path".format(path), |
| 936 |
PYTHONPATH=path) |
| 937 |
|
| 938 |
@support.impl_detail('no hash randomization on PyPy', pypy=False) |
| 939 |
def test_ignore_PYTHONHASHSEED(self): |
| 940 |
self.run_ignoring_vars("sys.flags.hash_randomization == 1", |
| 941 |
PYTHONHASHSEED="0") |
| 942 |
|
| 943 |
def test_sys_flags_not_set(self): |
| 944 |
|
| 945 |
expected_outcome = """ |
| 946 |
(sys.flags.debug == sys.flags.optimize == |
| 947 |
sys.flags.dont_write_bytecode == |
| 948 |
sys.flags.verbose == sys.flags.safe_path == 0) |
| 949 |
""" |
| 950 |
self.run_ignoring_vars( |
| 951 |
expected_outcome, |
| 952 |
PYTHONDEBUG="1", |
| 953 |
PYTHONOPTIMIZE="1", |
| 954 |
PYTHONDONTWRITEBYTECODE="1", |
| 955 |
PYTHONVERBOSE="1", |
| 956 |
PYTHONSAFEPATH="1", |
| 957 |
) |
| 958 |
|
| 959 |
|
| 960 |
class SyntaxErrorTests(unittest.TestCase): |
| 961 |
def check_string(self, code): |
| 962 |
proc = subprocess.run([sys.executable, "-"], input=code, |
| 963 |
stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 964 |
self.assertNotEqual(proc.returncode, 0) |
| 965 |
self.assertNotEqual(proc.stderr, None) |
| 966 |
self.assertIn(b"\nSyntaxError", proc.stderr) |
| 967 |
|
| 968 |
def test_tokenizer_error_with_stdin(self): |
| 969 |
self.check_string(b"(1+2+3") |
| 970 |
|
| 971 |
def test_decoding_error_at_the_end_of_the_line(self): |
| 972 |
self.check_string(br"'\u1f'") |
| 973 |
|
| 974 |
|
| 975 |
def tearDownModule(): |
| 976 |
support.reap_children() |
| 977 |
|
| 978 |
|
| 979 |
if __name__ == "__main__": |
| 980 |
unittest.main() |