ยปCore Development>Code coverage>Lib/test/test_cmd_line_script.py

Python code coverage for Lib/test/test_cmd_line_script.py

#countcontent
1n/a# tests command line execution of scripts
2n/a
3n/aimport contextlib
4n/aimport importlib
5n/aimport importlib.machinery
6n/aimport zipimport
7n/aimport unittest
8n/aimport sys
9n/aimport os
10n/aimport os.path
11n/aimport py_compile
12n/aimport subprocess
13n/aimport io
14n/a
15n/aimport textwrap
16n/afrom test import support
17n/afrom test.support.script_helper import (
18n/a make_pkg, make_script, make_zip_pkg, make_zip_script,
19n/a assert_python_ok, assert_python_failure, spawn_python, kill_python)
20n/a
21n/averbose = support.verbose
22n/a
23n/aexample_args = ['test1', 'test2', 'test3']
24n/a
25n/atest_source = """\
26n/a# Script may be run with optimisation enabled, so don't rely on assert
27n/a# statements being executed
28n/adef assertEqual(lhs, rhs):
29n/a if lhs != rhs:
30n/a raise AssertionError('%r != %r' % (lhs, rhs))
31n/adef assertIdentical(lhs, rhs):
32n/a if lhs is not rhs:
33n/a raise AssertionError('%r is not %r' % (lhs, rhs))
34n/a# Check basic code execution
35n/aresult = ['Top level assignment']
36n/adef f():
37n/a result.append('Lower level reference')
38n/af()
39n/aassertEqual(result, ['Top level assignment', 'Lower level reference'])
40n/a# Check population of magic variables
41n/aassertEqual(__name__, '__main__')
42n/afrom importlib.machinery import BuiltinImporter
43n/a_loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__)
44n/aprint('__loader__==%a' % _loader)
45n/aprint('__file__==%a' % __file__)
46n/aprint('__cached__==%a' % __cached__)
47n/aprint('__package__==%r' % __package__)
48n/a# Check PEP 451 details
49n/aimport os.path
50n/aif __package__ is not None:
51n/a print('__main__ was located through the import system')
52n/a assertIdentical(__spec__.loader, __loader__)
53n/a expected_spec_name = os.path.splitext(os.path.basename(__file__))[0]
54n/a if __package__:
55n/a expected_spec_name = __package__ + "." + expected_spec_name
56n/a assertEqual(__spec__.name, expected_spec_name)
57n/a assertEqual(__spec__.parent, __package__)
58n/a assertIdentical(__spec__.submodule_search_locations, None)
59n/a assertEqual(__spec__.origin, __file__)
60n/a if __spec__.cached is not None:
61n/a assertEqual(__spec__.cached, __cached__)
62n/a# Check the sys module
63n/aimport sys
64n/aassertIdentical(globals(), sys.modules[__name__].__dict__)
65n/aif __spec__ is not None:
66n/a # XXX: We're not currently making __main__ available under its real name
67n/a pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__)
68n/afrom test import test_cmd_line_script
69n/aexample_args_list = test_cmd_line_script.example_args
70n/aassertEqual(sys.argv[1:], example_args_list)
71n/aprint('sys.argv[0]==%a' % sys.argv[0])
72n/aprint('sys.path[0]==%a' % sys.path[0])
73n/a# Check the working directory
74n/aimport os
75n/aprint('cwd==%a' % os.getcwd())
76n/a"""
77n/a
78n/adef _make_test_script(script_dir, script_basename, source=test_source):
79n/a to_return = make_script(script_dir, script_basename, source)
80n/a importlib.invalidate_caches()
81n/a return to_return
82n/a
83n/adef _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
84n/a source=test_source, depth=1):
85n/a to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
86n/a source, depth)
87n/a importlib.invalidate_caches()
88n/a return to_return
89n/a
90n/a# There's no easy way to pass the script directory in to get
91n/a# -m to work (avoiding that is the whole point of making
92n/a# directories and zipfiles executable!)
93n/a# So we fake it for testing purposes with a custom launch script
94n/alaunch_source = """\
95n/aimport sys, os.path, runpy
96n/asys.path.insert(0, %s)
97n/arunpy._run_module_as_main(%r)
98n/a"""
99n/a
100n/adef _make_launch_script(script_dir, script_basename, module_name, path=None):
101n/a if path is None:
102n/a path = "os.path.dirname(__file__)"
103n/a else:
104n/a path = repr(path)
105n/a source = launch_source % (path, module_name)
106n/a to_return = make_script(script_dir, script_basename, source)
107n/a importlib.invalidate_caches()
108n/a return to_return
109n/a
110n/aclass CmdLineTest(unittest.TestCase):
111n/a def _check_output(self, script_name, exit_code, data,
112n/a expected_file, expected_argv0,
113n/a expected_path0, expected_package,
114n/a expected_loader):
115n/a if verbose > 1:
116n/a print("Output from test script %r:" % script_name)
117n/a print(repr(data))
118n/a self.assertEqual(exit_code, 0)
119n/a printed_loader = '__loader__==%a' % expected_loader
120n/a printed_file = '__file__==%a' % expected_file
121n/a printed_package = '__package__==%r' % expected_package
122n/a printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
123n/a printed_path0 = 'sys.path[0]==%a' % expected_path0
124n/a printed_cwd = 'cwd==%a' % os.getcwd()
125n/a if verbose > 1:
126n/a print('Expected output:')
127n/a print(printed_file)
128n/a print(printed_package)
129n/a print(printed_argv0)
130n/a print(printed_cwd)
131n/a self.assertIn(printed_loader.encode('utf-8'), data)
132n/a self.assertIn(printed_file.encode('utf-8'), data)
133n/a self.assertIn(printed_package.encode('utf-8'), data)
134n/a self.assertIn(printed_argv0.encode('utf-8'), data)
135n/a self.assertIn(printed_path0.encode('utf-8'), data)
136n/a self.assertIn(printed_cwd.encode('utf-8'), data)
137n/a
138n/a def _check_script(self, script_name, expected_file,
139n/a expected_argv0, expected_path0,
140n/a expected_package, expected_loader,
141n/a *cmd_line_switches):
142n/a run_args = [*support.optim_args_from_interpreter_flags(),
143n/a *cmd_line_switches, script_name, *example_args]
144n/a rc, out, err = assert_python_ok(*run_args, __isolated=False)
145n/a self._check_output(script_name, rc, out + err, expected_file,
146n/a expected_argv0, expected_path0,
147n/a expected_package, expected_loader)
148n/a
149n/a def _check_import_error(self, script_name, expected_msg,
150n/a *cmd_line_switches):
151n/a run_args = cmd_line_switches + (script_name,)
152n/a rc, out, err = assert_python_failure(*run_args)
153n/a if verbose > 1:
154n/a print('Output from test script %r:' % script_name)
155n/a print(repr(err))
156n/a print('Expected output: %r' % expected_msg)
157n/a self.assertIn(expected_msg.encode('utf-8'), err)
158n/a
159n/a def test_dash_c_loader(self):
160n/a rc, out, err = assert_python_ok("-c", "print(__loader__)")
161n/a expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
162n/a self.assertIn(expected, out)
163n/a
164n/a def test_stdin_loader(self):
165n/a # Unfortunately, there's no way to automatically test the fully
166n/a # interactive REPL, since that code path only gets executed when
167n/a # stdin is an interactive tty.
168n/a p = spawn_python()
169n/a try:
170n/a p.stdin.write(b"print(__loader__)\n")
171n/a p.stdin.flush()
172n/a finally:
173n/a out = kill_python(p)
174n/a expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
175n/a self.assertIn(expected, out)
176n/a
177n/a @contextlib.contextmanager
178n/a def interactive_python(self, separate_stderr=False):
179n/a if separate_stderr:
180n/a p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE)
181n/a stderr = p.stderr
182n/a else:
183n/a p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT)
184n/a stderr = p.stdout
185n/a try:
186n/a # Drain stderr until prompt
187n/a while True:
188n/a data = stderr.read(4)
189n/a if data == b">>> ":
190n/a break
191n/a stderr.readline()
192n/a yield p
193n/a finally:
194n/a kill_python(p)
195n/a stderr.close()
196n/a
197n/a def check_repl_stdout_flush(self, separate_stderr=False):
198n/a with self.interactive_python(separate_stderr) as p:
199n/a p.stdin.write(b"print('foo')\n")
200n/a p.stdin.flush()
201n/a self.assertEqual(b'foo', p.stdout.readline().strip())
202n/a
203n/a def check_repl_stderr_flush(self, separate_stderr=False):
204n/a with self.interactive_python(separate_stderr) as p:
205n/a p.stdin.write(b"1/0\n")
206n/a p.stdin.flush()
207n/a stderr = p.stderr if separate_stderr else p.stdout
208n/a self.assertIn(b'Traceback ', stderr.readline())
209n/a self.assertIn(b'File "<stdin>"', stderr.readline())
210n/a self.assertIn(b'ZeroDivisionError', stderr.readline())
211n/a
212n/a def test_repl_stdout_flush(self):
213n/a self.check_repl_stdout_flush()
214n/a
215n/a def test_repl_stdout_flush_separate_stderr(self):
216n/a self.check_repl_stdout_flush(True)
217n/a
218n/a def test_repl_stderr_flush(self):
219n/a self.check_repl_stderr_flush()
220n/a
221n/a def test_repl_stderr_flush_separate_stderr(self):
222n/a self.check_repl_stderr_flush(True)
223n/a
224n/a def test_basic_script(self):
225n/a with support.temp_dir() as script_dir:
226n/a script_name = _make_test_script(script_dir, 'script')
227n/a self._check_script(script_name, script_name, script_name,
228n/a script_dir, None,
229n/a importlib.machinery.SourceFileLoader)
230n/a
231n/a def test_script_compiled(self):
232n/a with support.temp_dir() as script_dir:
233n/a script_name = _make_test_script(script_dir, 'script')
234n/a py_compile.compile(script_name, doraise=True)
235n/a os.remove(script_name)
236n/a pyc_file = support.make_legacy_pyc(script_name)
237n/a self._check_script(pyc_file, pyc_file,
238n/a pyc_file, script_dir, None,
239n/a importlib.machinery.SourcelessFileLoader)
240n/a
241n/a def test_directory(self):
242n/a with support.temp_dir() as script_dir:
243n/a script_name = _make_test_script(script_dir, '__main__')
244n/a self._check_script(script_dir, script_name, script_dir,
245n/a script_dir, '',
246n/a importlib.machinery.SourceFileLoader)
247n/a
248n/a def test_directory_compiled(self):
249n/a with support.temp_dir() as script_dir:
250n/a script_name = _make_test_script(script_dir, '__main__')
251n/a py_compile.compile(script_name, doraise=True)
252n/a os.remove(script_name)
253n/a pyc_file = support.make_legacy_pyc(script_name)
254n/a self._check_script(script_dir, pyc_file, script_dir,
255n/a script_dir, '',
256n/a importlib.machinery.SourcelessFileLoader)
257n/a
258n/a def test_directory_error(self):
259n/a with support.temp_dir() as script_dir:
260n/a msg = "can't find '__main__' module in %r" % script_dir
261n/a self._check_import_error(script_dir, msg)
262n/a
263n/a def test_zipfile(self):
264n/a with support.temp_dir() as script_dir:
265n/a script_name = _make_test_script(script_dir, '__main__')
266n/a zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
267n/a self._check_script(zip_name, run_name, zip_name, zip_name, '',
268n/a zipimport.zipimporter)
269n/a
270n/a def test_zipfile_compiled(self):
271n/a with support.temp_dir() as script_dir:
272n/a script_name = _make_test_script(script_dir, '__main__')
273n/a compiled_name = py_compile.compile(script_name, doraise=True)
274n/a zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
275n/a self._check_script(zip_name, run_name, zip_name, zip_name, '',
276n/a zipimport.zipimporter)
277n/a
278n/a def test_zipfile_error(self):
279n/a with support.temp_dir() as script_dir:
280n/a script_name = _make_test_script(script_dir, 'not_main')
281n/a zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
282n/a msg = "can't find '__main__' module in %r" % zip_name
283n/a self._check_import_error(zip_name, msg)
284n/a
285n/a def test_module_in_package(self):
286n/a with support.temp_dir() as script_dir:
287n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
288n/a make_pkg(pkg_dir)
289n/a script_name = _make_test_script(pkg_dir, 'script')
290n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
291n/a self._check_script(launch_name, script_name, script_name,
292n/a script_dir, 'test_pkg',
293n/a importlib.machinery.SourceFileLoader)
294n/a
295n/a def test_module_in_package_in_zipfile(self):
296n/a with support.temp_dir() as script_dir:
297n/a zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
298n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
299n/a self._check_script(launch_name, run_name, run_name,
300n/a zip_name, 'test_pkg', zipimport.zipimporter)
301n/a
302n/a def test_module_in_subpackage_in_zipfile(self):
303n/a with support.temp_dir() as script_dir:
304n/a zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
305n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
306n/a self._check_script(launch_name, run_name, run_name,
307n/a zip_name, 'test_pkg.test_pkg',
308n/a zipimport.zipimporter)
309n/a
310n/a def test_package(self):
311n/a with support.temp_dir() as script_dir:
312n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
313n/a make_pkg(pkg_dir)
314n/a script_name = _make_test_script(pkg_dir, '__main__')
315n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
316n/a self._check_script(launch_name, script_name,
317n/a script_name, script_dir, 'test_pkg',
318n/a importlib.machinery.SourceFileLoader)
319n/a
320n/a def test_package_compiled(self):
321n/a with support.temp_dir() as script_dir:
322n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
323n/a make_pkg(pkg_dir)
324n/a script_name = _make_test_script(pkg_dir, '__main__')
325n/a compiled_name = py_compile.compile(script_name, doraise=True)
326n/a os.remove(script_name)
327n/a pyc_file = support.make_legacy_pyc(script_name)
328n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
329n/a self._check_script(launch_name, pyc_file,
330n/a pyc_file, script_dir, 'test_pkg',
331n/a importlib.machinery.SourcelessFileLoader)
332n/a
333n/a def test_package_error(self):
334n/a with support.temp_dir() as script_dir:
335n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
336n/a make_pkg(pkg_dir)
337n/a msg = ("'test_pkg' is a package and cannot "
338n/a "be directly executed")
339n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
340n/a self._check_import_error(launch_name, msg)
341n/a
342n/a def test_package_recursion(self):
343n/a with support.temp_dir() as script_dir:
344n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
345n/a make_pkg(pkg_dir)
346n/a main_dir = os.path.join(pkg_dir, '__main__')
347n/a make_pkg(main_dir)
348n/a msg = ("Cannot use package as __main__ module; "
349n/a "'test_pkg' is a package and cannot "
350n/a "be directly executed")
351n/a launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
352n/a self._check_import_error(launch_name, msg)
353n/a
354n/a def test_issue8202(self):
355n/a # Make sure package __init__ modules see "-m" in sys.argv0 while
356n/a # searching for the module to execute
357n/a with support.temp_dir() as script_dir:
358n/a with support.change_cwd(path=script_dir):
359n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
360n/a make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
361n/a script_name = _make_test_script(pkg_dir, 'script')
362n/a rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
363n/a if verbose > 1:
364n/a print(repr(out))
365n/a expected = "init_argv0==%r" % '-m'
366n/a self.assertIn(expected.encode('utf-8'), out)
367n/a self._check_output(script_name, rc, out,
368n/a script_name, script_name, '', 'test_pkg',
369n/a importlib.machinery.SourceFileLoader)
370n/a
371n/a def test_issue8202_dash_c_file_ignored(self):
372n/a # Make sure a "-c" file in the current directory
373n/a # does not alter the value of sys.path[0]
374n/a with support.temp_dir() as script_dir:
375n/a with support.change_cwd(path=script_dir):
376n/a with open("-c", "w") as f:
377n/a f.write("data")
378n/a rc, out, err = assert_python_ok('-c',
379n/a 'import sys; print("sys.path[0]==%r" % sys.path[0])',
380n/a __isolated=False)
381n/a if verbose > 1:
382n/a print(repr(out))
383n/a expected = "sys.path[0]==%r" % ''
384n/a self.assertIn(expected.encode('utf-8'), out)
385n/a
386n/a def test_issue8202_dash_m_file_ignored(self):
387n/a # Make sure a "-m" file in the current directory
388n/a # does not alter the value of sys.path[0]
389n/a with support.temp_dir() as script_dir:
390n/a script_name = _make_test_script(script_dir, 'other')
391n/a with support.change_cwd(path=script_dir):
392n/a with open("-m", "w") as f:
393n/a f.write("data")
394n/a rc, out, err = assert_python_ok('-m', 'other', *example_args,
395n/a __isolated=False)
396n/a self._check_output(script_name, rc, out,
397n/a script_name, script_name, '', '',
398n/a importlib.machinery.SourceFileLoader)
399n/a
400n/a @contextlib.contextmanager
401n/a def setup_test_pkg(self, *args):
402n/a with support.temp_dir() as script_dir, \
403n/a support.change_cwd(path=script_dir):
404n/a pkg_dir = os.path.join(script_dir, 'test_pkg')
405n/a make_pkg(pkg_dir, *args)
406n/a yield pkg_dir
407n/a
408n/a def check_dash_m_failure(self, *args):
409n/a rc, out, err = assert_python_failure('-m', *args, __isolated=False)
410n/a if verbose > 1:
411n/a print(repr(out))
412n/a self.assertEqual(rc, 1)
413n/a return err
414n/a
415n/a def test_dash_m_error_code_is_one(self):
416n/a # If a module is invoked with the -m command line flag
417n/a # and results in an error that the return code to the
418n/a # shell is '1'
419n/a with self.setup_test_pkg() as pkg_dir:
420n/a script_name = _make_test_script(pkg_dir, 'other',
421n/a "if __name__ == '__main__': raise ValueError")
422n/a err = self.check_dash_m_failure('test_pkg.other', *example_args)
423n/a self.assertIn(b'ValueError', err)
424n/a
425n/a def test_dash_m_errors(self):
426n/a # Exercise error reporting for various invalid package executions
427n/a tests = (
428n/a ('builtins', br'No code object available'),
429n/a ('builtins.x', br'Error while finding module specification.*'
430n/a br'AttributeError'),
431n/a ('builtins.x.y', br'Error while finding module specification.*'
432n/a br'ModuleNotFoundError.*No module named.*not a package'),
433n/a ('os.path', br'loader.*cannot handle'),
434n/a ('importlib', br'No module named.*'
435n/a br'is a package and cannot be directly executed'),
436n/a ('importlib.nonexistant', br'No module named'),
437n/a ('.unittest', br'Relative module names not supported'),
438n/a )
439n/a for name, regex in tests:
440n/a with self.subTest(name):
441n/a rc, _, err = assert_python_failure('-m', name)
442n/a self.assertEqual(rc, 1)
443n/a self.assertRegex(err, regex)
444n/a self.assertNotIn(b'Traceback', err)
445n/a
446n/a def test_dash_m_bad_pyc(self):
447n/a with support.temp_dir() as script_dir, \
448n/a support.change_cwd(path=script_dir):
449n/a os.mkdir('test_pkg')
450n/a # Create invalid *.pyc as empty file
451n/a with open('test_pkg/__init__.pyc', 'wb'):
452n/a pass
453n/a err = self.check_dash_m_failure('test_pkg')
454n/a self.assertRegex(err,
455n/a br'Error while finding module specification.*'
456n/a br'ImportError.*bad magic number')
457n/a self.assertNotIn(b'is a package', err)
458n/a self.assertNotIn(b'Traceback', err)
459n/a
460n/a def test_dash_m_init_traceback(self):
461n/a # These were wrapped in an ImportError and tracebacks were
462n/a # suppressed; see Issue 14285
463n/a exceptions = (ImportError, AttributeError, TypeError, ValueError)
464n/a for exception in exceptions:
465n/a exception = exception.__name__
466n/a init = "raise {0}('Exception in __init__.py')".format(exception)
467n/a with self.subTest(exception), \
468n/a self.setup_test_pkg(init) as pkg_dir:
469n/a err = self.check_dash_m_failure('test_pkg')
470n/a self.assertIn(exception.encode('ascii'), err)
471n/a self.assertIn(b'Exception in __init__.py', err)
472n/a self.assertIn(b'Traceback', err)
473n/a
474n/a def test_dash_m_main_traceback(self):
475n/a # Ensure that an ImportError's traceback is reported
476n/a with self.setup_test_pkg() as pkg_dir:
477n/a main = "raise ImportError('Exception in __main__ module')"
478n/a _make_test_script(pkg_dir, '__main__', main)
479n/a err = self.check_dash_m_failure('test_pkg')
480n/a self.assertIn(b'ImportError', err)
481n/a self.assertIn(b'Exception in __main__ module', err)
482n/a self.assertIn(b'Traceback', err)
483n/a
484n/a def test_pep_409_verbiage(self):
485n/a # Make sure PEP 409 syntax properly suppresses
486n/a # the context of an exception
487n/a script = textwrap.dedent("""\
488n/a try:
489n/a raise ValueError
490n/a except:
491n/a raise NameError from None
492n/a """)
493n/a with support.temp_dir() as script_dir:
494n/a script_name = _make_test_script(script_dir, 'script', script)
495n/a exitcode, stdout, stderr = assert_python_failure(script_name)
496n/a text = stderr.decode('ascii').split('\n')
497n/a self.assertEqual(len(text), 4)
498n/a self.assertTrue(text[0].startswith('Traceback'))
499n/a self.assertTrue(text[1].startswith(' File '))
500n/a self.assertTrue(text[3].startswith('NameError'))
501n/a
502n/a def test_non_ascii(self):
503n/a # Mac OS X denies the creation of a file with an invalid UTF-8 name.
504n/a # Windows allows creating a name with an arbitrary bytes name, but
505n/a # Python cannot a undecodable bytes argument to a subprocess.
506n/a if (support.TESTFN_UNDECODABLE
507n/a and sys.platform not in ('win32', 'darwin')):
508n/a name = os.fsdecode(support.TESTFN_UNDECODABLE)
509n/a elif support.TESTFN_NONASCII:
510n/a name = support.TESTFN_NONASCII
511n/a else:
512n/a self.skipTest("need support.TESTFN_NONASCII")
513n/a
514n/a # Issue #16218
515n/a source = 'print(ascii(__file__))\n'
516n/a script_name = _make_test_script(os.curdir, name, source)
517n/a self.addCleanup(support.unlink, script_name)
518n/a rc, stdout, stderr = assert_python_ok(script_name)
519n/a self.assertEqual(
520n/a ascii(script_name),
521n/a stdout.rstrip().decode('ascii'),
522n/a 'stdout=%r stderr=%r' % (stdout, stderr))
523n/a self.assertEqual(0, rc)
524n/a
525n/a def test_issue20500_exit_with_exception_value(self):
526n/a script = textwrap.dedent("""\
527n/a import sys
528n/a error = None
529n/a try:
530n/a raise ValueError('some text')
531n/a except ValueError as err:
532n/a error = err
533n/a
534n/a if error:
535n/a sys.exit(error)
536n/a """)
537n/a with support.temp_dir() as script_dir:
538n/a script_name = _make_test_script(script_dir, 'script', script)
539n/a exitcode, stdout, stderr = assert_python_failure(script_name)
540n/a text = stderr.decode('ascii')
541n/a self.assertEqual(text, "some text")
542n/a
543n/a def test_syntaxerror_unindented_caret_position(self):
544n/a script = "1 + 1 = 2\n"
545n/a with support.temp_dir() as script_dir:
546n/a script_name = _make_test_script(script_dir, 'script', script)
547n/a exitcode, stdout, stderr = assert_python_failure(script_name)
548n/a text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
549n/a # Confirm that the caret is located under the first 1 character
550n/a self.assertIn("\n 1 + 1 = 2\n ^", text)
551n/a
552n/a def test_syntaxerror_indented_caret_position(self):
553n/a script = textwrap.dedent("""\
554n/a if True:
555n/a 1 + 1 = 2
556n/a """)
557n/a with support.temp_dir() as script_dir:
558n/a script_name = _make_test_script(script_dir, 'script', script)
559n/a exitcode, stdout, stderr = assert_python_failure(script_name)
560n/a text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
561n/a # Confirm that the caret is located under the first 1 character
562n/a self.assertIn("\n 1 + 1 = 2\n ^", text)
563n/a
564n/a # Try the same with a form feed at the start of the indented line
565n/a script = (
566n/a "if True:\n"
567n/a "\f 1 + 1 = 2\n"
568n/a )
569n/a script_name = _make_test_script(script_dir, "script", script)
570n/a exitcode, stdout, stderr = assert_python_failure(script_name)
571n/a text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
572n/a self.assertNotIn("\f", text)
573n/a self.assertIn("\n 1 + 1 = 2\n ^", text)
574n/a
575n/a
576n/adef test_main():
577n/a support.run_unittest(CmdLineTest)
578n/a support.reap_children()
579n/a
580n/aif __name__ == '__main__':
581n/a test_main()