Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(169200)

Delta Between Two Patch Sets: Lib/test/test_cmd_line.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 6 years, 3 months ago
Right Patch Set: Created 5 years, 10 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_capi.py ('k') | Lib/test/test_codeop.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 # Tests invocation of the interpreter with various command line arguments 1 # Tests invocation of the interpreter with various command line arguments
2 # Most tests are executed with environment variables ignored 2 # Most tests are executed with environment variables ignored
3 # See test_cmd_line_script.py for testing of script execution 3 # See test_cmd_line_script.py for testing of script execution
4 4
5 import test.support, unittest 5 import test.support, unittest
6 import os 6 import os
7 import shutil
7 import sys 8 import sys
8 import subprocess 9 import subprocess
9 import tempfile 10 import tempfile
10 from test.script_helper import (spawn_python, kill_python, assert_python_ok, 11 from test.script_helper import (spawn_python, kill_python, assert_python_ok,
11 assert_python_failure) 12 assert_python_failure)
12 13
13 14
14 # XXX (ncoghlan): Move to script_helper and make consistent with run_python 15 # XXX (ncoghlan): Move to script_helper and make consistent with run_python
15 def _kill_python_and_exit_code(p): 16 def _kill_python_and_exit_code(p):
16 data = kill_python(p) 17 data = kill_python(p)
(...skipping 17 matching lines...) Expand all
34 35
35 def test_site_flag(self): 36 def test_site_flag(self):
36 self.verify_valid_flag('-S') 37 self.verify_valid_flag('-S')
37 38
38 def test_usage(self): 39 def test_usage(self):
39 rc, out, err = assert_python_ok('-h') 40 rc, out, err = assert_python_ok('-h')
40 self.assertIn(b'usage', out) 41 self.assertIn(b'usage', out)
41 42
42 def test_version(self): 43 def test_version(self):
43 version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii") 44 version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii")
44 rc, out, err = assert_python_ok('-V') 45 for switch in '-V', '--version':
45 self.assertTrue(err.startswith(version)) 46 rc, out, err = assert_python_ok(switch)
47 self.assertFalse(err.startswith(version))
48 self.assertTrue(out.startswith(version))
46 49
47 def test_verbose(self): 50 def test_verbose(self):
48 # -v causes imports to write to stderr. If the write to 51 # -v causes imports to write to stderr. If the write to
49 # stderr itself causes an import to happen (for the output 52 # stderr itself causes an import to happen (for the output
50 # codec), a recursion loop can occur. 53 # codec), a recursion loop can occur.
51 rc, out, err = assert_python_ok('-v') 54 rc, out, err = assert_python_ok('-v')
52 self.assertNotIn(b'stack overflow', err) 55 self.assertNotIn(b'stack overflow', err)
53 rc, out, err = assert_python_ok('-vv') 56 rc, out, err = assert_python_ok('-vv')
54 self.assertNotIn(b'stack overflow', err) 57 self.assertNotIn(b'stack overflow', err)
55 58
56 def test_xoptions(self): 59 def test_xoptions(self):
57 rc, out, err = assert_python_ok('-c', 'import sys; print(sys._xoptions)' ) 60 def get_xoptions(*args):
58 opts = eval(out.splitlines()[0]) 61 # use subprocess module directly because test.script_helper adds
62 # "-X faulthandler" to the command line
63 args = (sys.executable, '-E') + args
64 args += ('-c', 'import sys; print(sys._xoptions)')
65 out = subprocess.check_output(args)
66 opts = eval(out.splitlines()[0])
67 return opts
68
69 opts = get_xoptions()
59 self.assertEqual(opts, {}) 70 self.assertEqual(opts, {})
60 rc, out, err = assert_python_ok( 71
61 '-Xa', '-Xb=c,d=e', '-c', 'import sys; print(sys._xoptions)') 72 opts = get_xoptions('-Xa', '-Xb=c,d=e')
62 opts = eval(out.splitlines()[0])
63 self.assertEqual(opts, {'a': True, 'b': 'c,d=e'}) 73 self.assertEqual(opts, {'a': True, 'b': 'c,d=e'})
74
75 def test_showrefcount(self):
76 def run_python(*args):
77 # this is similar to assert_python_ok but doesn't strip
78 # the refcount from stderr. It can be replaced once
79 # assert_python_ok stops doing that.
80 cmd = [sys.executable]
81 cmd.extend(args)
82 PIPE = subprocess.PIPE
83 p = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE)
84 out, err = p.communicate()
85 p.stdout.close()
86 p.stderr.close()
87 rc = p.returncode
88 self.assertEqual(rc, 0)
89 return rc, out, err
90 code = 'import sys; print(sys._xoptions)'
91 # normally the refcount is hidden
92 rc, out, err = run_python('-c', code)
93 self.assertEqual(out.rstrip(), b'{}')
94 self.assertEqual(err, b'')
95 # "-X showrefcount" shows the refcount, but only in debug builds
96 rc, out, err = run_python('-X', 'showrefcount', '-c', code)
97 self.assertEqual(out.rstrip(), b"{'showrefcount': True}")
98 if hasattr(sys, 'gettotalrefcount'): # debug build
99 self.assertRegex(err, br'^\[\d+ refs, \d+ blocks\]')
100 else:
101 self.assertEqual(err, b'')
64 102
65 def test_run_module(self): 103 def test_run_module(self):
66 # Test expected operation of the '-m' switch 104 # Test expected operation of the '-m' switch
67 # Switch needs an argument 105 # Switch needs an argument
68 assert_python_failure('-m') 106 assert_python_failure('-m')
69 # Check we get an error for a nonexistent module 107 # Check we get an error for a nonexistent module
70 assert_python_failure('-m', 'fnord43520xyz') 108 assert_python_failure('-m', 'fnord43520xyz')
71 # Check the runpy module also gives an error for 109 # Check the runpy module also gives an error for
72 # a nonexistent module 110 # a nonexistent module
73 assert_python_failure('-m', 'runpy', 'fnord43520xyz'), 111 assert_python_failure('-m', 'runpy', 'fnord43520xyz')
74 # All good if module is located and run successfully 112 # All good if module is located and run successfully
75 assert_python_ok('-m', 'timeit', '-n', '1'), 113 assert_python_ok('-m', 'timeit', '-n', '1')
76 114
77 def test_run_module_bug1764407(self): 115 def test_run_module_bug1764407(self):
78 # -m and -i need to play well together 116 # -m and -i need to play well together
79 # Runs the timeit module and checks the __main__ 117 # Runs the timeit module and checks the __main__
80 # namespace has been populated appropriately 118 # namespace has been populated appropriately
81 p = spawn_python('-i', '-m', 'timeit', '-n', '1') 119 p = spawn_python('-i', '-m', 'timeit', '-n', '1')
82 p.stdin.write(b'Timer\n') 120 p.stdin.write(b'Timer\n')
83 p.stdin.write(b'exit()\n') 121 p.stdin.write(b'exit()\n')
84 data = kill_python(p) 122 data = kill_python(p)
85 self.assertNotEqual(data.find(b'1 loop'), -1) 123 self.assertNotEqual(data.find(b'1 loop'), -1)
(...skipping 132 matching lines...) Expand 10 before | Expand all | Expand 10 after
218 # empty string is equivalent to not setting PATH at all, 256 # empty string is equivalent to not setting PATH at all,
219 # which is an exception to the rule that in a string like 257 # which is an exception to the rule that in a string like
220 # "/bin::/usr/bin" the empty string in the middle gets 258 # "/bin::/usr/bin" the empty string in the middle gets
221 # interpreted as '.' 259 # interpreted as '.'
222 code = """if 1: 260 code = """if 1:
223 import sys 261 import sys
224 path = ":".join(sys.path) 262 path = ":".join(sys.path)
225 path = path.encode("ascii", "backslashreplace") 263 path = path.encode("ascii", "backslashreplace")
226 sys.stdout.buffer.write(path)""" 264 sys.stdout.buffer.write(path)"""
227 rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="") 265 rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="")
228 rc2, out2, err2 = assert_python_ok('-c', code) 266 rc2, out2, err2 = assert_python_ok('-c', code, __isolated=False)
229 # regarding to Posix specification, outputs should be equal 267 # regarding to Posix specification, outputs should be equal
230 # for empty and unset PYTHONPATH 268 # for empty and unset PYTHONPATH
231 self.assertEqual(out1, out2) 269 self.assertEqual(out1, out2)
232 270
233 def test_displayhook_unencodable(self): 271 def test_displayhook_unencodable(self):
234 for encoding in ('ascii', 'latin-1', 'utf-8'): 272 for encoding in ('ascii', 'latin-1', 'utf-8'):
235 env = os.environ.copy() 273 env = os.environ.copy()
236 env['PYTHONIOENCODING'] = encoding 274 env['PYTHONIOENCODING'] = encoding
237 p = subprocess.Popen( 275 p = subprocess.Popen(
238 [sys.executable, '-i'], 276 [sys.executable, '-i'],
(...skipping 156 matching lines...) Expand 10 before | Expand all | Expand 10 after
395 self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1) 433 self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1)
396 self.assertEqual(b'', out) 434 self.assertEqual(b'', out)
397 rc, out, err = assert_python_failure('-a', '-z', without='-E') 435 rc, out, err = assert_python_failure('-a', '-z', without='-E')
398 self.assertIn(b'Unknown option: -a', err) 436 self.assertIn(b'Unknown option: -a', err)
399 # only the first unknown option is reported 437 # only the first unknown option is reported
400 self.assertNotIn(b'Unknown option: -z', err) 438 self.assertNotIn(b'Unknown option: -z', err)
401 self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1) 439 self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1)
402 self.assertEqual(b'', out) 440 self.assertEqual(b'', out)
403 441
404 442
443 def test_isolatedmode(self):
444 self.verify_valid_flag('-I')
445 self.verify_valid_flag('-IEs')
446 rc, out, err = assert_python_ok('-I', '-c',
447 'from sys import flags as f; '
448 'print(f.no_user_site, f.ignore_environment, f.isolated)',
449 # dummyvar to prevent extranous -E
450 dummyvar="")
451 self.assertEqual(out.strip(), b'1 1 1')
452 with test.support.temp_cwd() as tmpdir:
453 fake = os.path.join(tmpdir, "uuid.py")
454 main = os.path.join(tmpdir, "main.py")
455 with open(fake, "w") as f:
456 f.write("raise RuntimeError('isolated mode test')\n")
457 with open(main, "w") as f:
458 f.write("import uuid\n")
459 f.write("print('ok')\n")
460 self.assertRaises(subprocess.CalledProcessError,
461 subprocess.check_output,
462 [sys.executable, main], cwd=tmpdir,
463 stderr=subprocess.DEVNULL)
464 out = subprocess.check_output([sys.executable, "-I", main],
465 cwd=tmpdir)
466 self.assertEqual(out.strip(), b"ok")
467
405 def test_main(): 468 def test_main():
406 test.support.run_unittest(CmdLineTest) 469 test.support.run_unittest(CmdLineTest)
407 test.support.reap_children() 470 test.support.reap_children()
408 471
409 if __name__ == "__main__": 472 if __name__ == "__main__":
410 test_main() 473 test_main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+