diff --git a/AUTHORS b/AUTHORS index f04403e2d5c..92d47f5bbac 100644 --- a/AUTHORS +++ b/AUTHORS @@ -467,6 +467,7 @@ Segev Finer SemTiOne Serhii Mozghovyi Seth Junot +Shahab Ahmed Shantanu Jain Sharad Nair Shaygan Hooshyari diff --git a/changelog/3649.bugfix.rst b/changelog/3649.bugfix.rst new file mode 100644 index 00000000000..77bb5fa4444 --- /dev/null +++ b/changelog/3649.bugfix.rst @@ -0,0 +1 @@ +The debugger is no longer entered when a collection error is caused by a syntax error, as the traceback would only show where the error is re-raised instead of the syntax error itself. diff --git a/src/_pytest/runner.py b/src/_pytest/runner.py index 629796598df..7e4f2dba74b 100644 --- a/src/_pytest/runner.py +++ b/src/_pytest/runner.py @@ -285,6 +285,15 @@ def check_interactive_exception(call: CallInfo[object], report: BaseReport) -> b return True +def is_syntax_error(exc: BaseException) -> bool: + """Check whether the exception was caused by a syntax error. + + A syntax error is re-raised as a ``CollectError`` which keeps the original + ``SyntaxError`` as its cause, so both are checked here. + """ + return isinstance(exc, SyntaxError) or isinstance(exc.__cause__, SyntaxError) + + TResult = TypeVar("TResult", covariant=True) @@ -610,5 +619,10 @@ def collect_one_node(collector: Collector) -> CollectReport: rep: CollectReport = ihook.pytest_make_collect_report(collector=collector) call = rep.__dict__.pop("call", None) if call and check_interactive_exception(call, rep): - ihook.pytest_exception_interact(node=collector, call=call, report=rep) + # The debugger is not entered for a syntax error: the traceback would + # point at the place where the error is re-raised instead of at the + # syntax error itself, which is not helpful (see #3649). + assert call.excinfo is not None + if not is_syntax_error(call.excinfo.value): + ihook.pytest_exception_interact(node=collector, call=call, report=rep) return rep diff --git a/testing/test_debugging.py b/testing/test_debugging.py index 3a67cfa8cd6..4034f7eb7ed 100644 --- a/testing/test_debugging.py +++ b/testing/test_debugging.py @@ -838,6 +838,17 @@ def test_pdb_collection_failure_is_shown(self, pytester: Pytester) -> None: ["E NameError: *xxx*", "*! *Exit: Quitting debugger !*"] # due to EOF ) + def test_pdb_not_entered_on_syntax_error(self, pytester: Pytester) -> None: + """The debugger is not entered for a syntax error (see #3649). + + The traceback of a syntax error is still reported, entering the + debugger would only show where the error is re-raised. + """ + p1 = pytester.makepyfile("syntax error") + result = pytester.runpytest_subprocess("--pdb", p1) + result.stdout.fnmatch_lines(["E SyntaxError: invalid syntax"]) + result.stdout.no_fnmatch_line("*entering PDB*") + @pytest.mark.parametrize("post_mortem", (False, True)) def test_enter_leave_pdb_hooks_are_called( self, post_mortem, pytester: Pytester