From 148af38cd0adc1c2dde3c937ebbda4ee60b27b33 Mon Sep 17 00:00:00 2001 From: Tian Gao Date: Fri, 10 Nov 2023 13:13:29 -0800 Subject: gh-80731: Avoid executing code in except block in cmd (GH-111740) --- Lib/cmd.py | 5 ++--- Lib/test/test_cmd.py | 15 +++++++++++++ Lib/test/test_pdb.py | 25 ++++++++++++++++++++++ .../2023-11-04-21-12-27.gh-issue-80731.Wq51xg.rst | 1 + 4 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-11-04-21-12-27.gh-issue-80731.Wq51xg.rst diff --git a/Lib/cmd.py b/Lib/cmd.py index 88ee7d3..e933b8d 100644 --- a/Lib/cmd.py +++ b/Lib/cmd.py @@ -210,9 +210,8 @@ class Cmd: if cmd == '': return self.default(line) else: - try: - func = getattr(self, 'do_' + cmd) - except AttributeError: + func = getattr(self, 'do_' + cmd, None) + if func is None: return self.default(line) return func(arg) diff --git a/Lib/test/test_cmd.py b/Lib/test/test_cmd.py index 28f8076..951336f 100644 --- a/Lib/test/test_cmd.py +++ b/Lib/test/test_cmd.py @@ -244,6 +244,21 @@ class TestAlternateInput(unittest.TestCase): "(Cmd) *** Unknown syntax: EOF\n")) +class CmdPrintExceptionClass(cmd.Cmd): + """ + GH-80731 + cmd.Cmd should print the correct exception in default() + >>> mycmd = CmdPrintExceptionClass() + >>> try: + ... raise ValueError("test") + ... except ValueError: + ... mycmd.onecmd("not important") + (, ValueError('test')) + """ + + def default(self, line): + print(sys.exc_info()[:2]) + def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_pdb.py b/Lib/test/test_pdb.py index 5508f7b..7cd5ae3 100644 --- a/Lib/test/test_pdb.py +++ b/Lib/test/test_pdb.py @@ -2349,6 +2349,31 @@ def test_pdb_issue_gh_108976(): (Pdb) continue """ + +def test_pdb_issue_gh_80731(): + """See GH-80731 + + pdb should correctly print exception info if in an except block. + + >>> with PdbTestInput([ # doctest: +ELLIPSIS + ... 'import sys', + ... 'sys.exc_info()', + ... 'continue' + ... ]): + ... try: + ... raise ValueError('Correct') + ... except ValueError: + ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() + ... pass + > (10)() + -> pass + (Pdb) import sys + (Pdb) sys.exc_info() + (, ValueError('Correct'), ) + (Pdb) continue + """ + + def test_pdb_ambiguous_statements(): """See GH-104301 diff --git a/Misc/NEWS.d/next/Library/2023-11-04-21-12-27.gh-issue-80731.Wq51xg.rst b/Misc/NEWS.d/next/Library/2023-11-04-21-12-27.gh-issue-80731.Wq51xg.rst new file mode 100644 index 0000000..5f957a3 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-11-04-21-12-27.gh-issue-80731.Wq51xg.rst @@ -0,0 +1 @@ +Avoid executing the default function in :class:`cmd.Cmd` in an except block -- cgit v0.12