Skip to content

gh-108791: Fix pdb CLI invalid argument handling #108816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Oct 16, 2023
6 changes: 6 additions & 0 deletions Lib/pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ def check(self):
if not os.path.exists(self):
print('Error:', self.orig, 'does not exist')
sys.exit(1)
if os.path.isdir(self):
print('Error:', self.orig, 'is a directory')
sys.exit(1)

# Replace pdb's dir with script's dir in front of module search path.
sys.path[0] = os.path.dirname(self)
Expand All @@ -164,6 +167,9 @@ class _ModuleTarget(str):
def check(self):
try:
self._details
except ImportError as e:
print(f"ImportError: {e}")
sys.exit(1)
except Exception:
traceback.print_exc()
sys.exit(1)
Expand Down
19 changes: 17 additions & 2 deletions Lib/test/test_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2758,8 +2758,7 @@ def test_module_without_a_main(self):
stdout, stderr = self._run_pdb(
['-m', module_name], "", expected_returncode=1
)
self.assertIn("ImportError: No module named t_main.__main__",
stdout.splitlines())
self.assertIn("ImportError: No module named t_main.__main__;", stdout)

def test_package_without_a_main(self):
pkg_name = 't_pkg'
Expand All @@ -2777,6 +2776,22 @@ def test_package_without_a_main(self):
"'t_pkg.t_main' is a package and cannot be directly executed",
stdout)

def test_nonexistent_module(self):
assert not os.path.exists(os_helper.TESTFN)
stdout, stderr = self._run_pdb(["-m", os_helper.TESTFN], "", expected_returncode=1)
self.assertIn(f"ImportError: No module named {os_helper.TESTFN}", stdout)

def test_dir_as_script(self):
with os_helper.temp_dir() as temp_dir:
stdout, stderr = self._run_pdb([temp_dir], "", expected_returncode=1)
self.assertIn(f"Error: {temp_dir} is a directory", stdout)

def test_invalid_cmd_line_options(self):
stdout, stderr = self._run_pdb(["-c"], "", expected_returncode=2)
self.assertIn(f"pdb: error: argument -c/--command: expected one argument", stdout.split('\n')[1])
stdout, stderr = self._run_pdb(["--spam", "-m", "pdb"], "", expected_returncode=2)
self.assertIn(f"pdb: error: unrecognized arguments: --spam", stdout.split('\n')[1])

def test_blocks_at_first_code_line(self):
script = """
#This is a comment, on line 2
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved error handling in :mod:`pdb` command line interface, making it produce more concise error messages.