Scrapy, a fast high-level web crawling & scraping framework for Python.
Make --pdb break on reported errors instead of on every Failure (#8037)
Adrian8a0e394f16e6
diff --git a/scrapy/commands/__init__.py b/scrapy/commands/__init__.pyindex 9d0f405d2..e8e446ba4 100644--- a/scrapy/commands/__init__.py+++ b/scrapy/commands/__init__.py@@ -14,8 +14,6 @@ from abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar-from twisted.python import failure-from scrapy import signalsfrom scrapy.exceptions import ScrapyDeprecationWarning, UsageErrorfrom scrapy.extensions.feedexport import FeedExporter@@ -34,6 +32,17 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+class _PdbHandler(logging.Handler):+ """Start a post-mortem debugging session on every logged record that comes+ with an exception traceback."""++ def emit(self, record: logging.LogRecord) -> None:+ if record.exc_info and record.exc_info[2]:+ import pdb # noqa: T100,PLC0415++ pdb.post_mortem(record.exc_info[2])++class ScrapyCommand(ABC):"""Base class for all Scrapy commands."""@@ -162,7 +171,7 @@ class ScrapyCommand(ABC):passelse:sys.modules["pdb"] = ipdb- failure.startDebugMode()+ logging.root.addHandler(_PdbHandler(level=logging.ERROR))@abstractmethoddef run(self, args: list[str], opts: argparse.Namespace) -> None:diff --git a/tests/test_commands.py b/tests/test_commands.pyindex 08882fd52..8b3e8b7c6 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -2,13 +2,13 @@ from __future__ import annotationsimport argparseimport json+import loggingimport pdb # noqa: T100import sysfrom pathlib import Pathfrom typing import TYPE_CHECKING, Anyimport pytest-from twisted.python import failureimport scrapyfrom scrapy.cmdline import _pop_command_name, execute@@ -100,13 +100,16 @@ class TestCommandSettings:assert dict(self.command.settings["FEEDS"]) == json.loads(feeds_json)def test_pdb_uses_ipdb_if_installed(self, monkeypatch):- monkeypatch.setattr(failure, "startDebugMode", lambda: None)fake_ipdb: Any = argparse.Namespace(post_mortem=lambda tb: None)monkeypatch.setitem(sys.modules, "pdb", pdb)monkeypatch.setitem(sys.modules, "ipdb", fake_ipdb)opts, args = self.parser.parse_known_args(args=["--pdb", "spider.py"])- self.command.process_options(args, opts)- assert sys.modules["pdb"] is fake_ipdb+ handlers = logging.root.handlers[:]+ try:+ self.command.process_options(args, opts)+ assert sys.modules["pdb"] is fake_ipdb+ finally:+ logging.root.handlers[:] = handlersdef test_help_formatter(self):formatter = ScrapyHelpFormatter(prog="scrapy")@@ -184,9 +187,75 @@ class MySpider(scrapy.Spider):assert pidfile.read_text(encoding="utf-8").strip().isdigit()def test_pdb(self, spider_path: Path) -> None:- returncode, _, err = proc("runspider", str(spider_path), "--pdb")+ returncode, out, err = proc("runspider", str(spider_path), "--pdb", input="")assert returncode == 0, errassert "It works!" in err+ assert "(Pdb)" not in out++ def test_pdb_on_logged_error(self, tmp_path: Path) -> None:+ path = tmp_path / "myspider.py"+ path.write_text(+ """+import scrapy++class MySpider(scrapy.Spider):+ name = "myspider"++ async def start(self):+ raise ValueError("boom")+ yield+""",+ encoding="utf-8",+ )+ _, out, err = proc("runspider", str(path), "--pdb", input="")+ assert "(Pdb)" in out, err++ def test_pdb_on_logged_error_without_exception(self, tmp_path: Path) -> None:+ path = tmp_path / "myspider.py"+ path.write_text(+ """+import logging+import scrapy++logger = logging.getLogger(__name__)++class MySpider(scrapy.Spider):+ name = "myspider"++ async def start(self):+ logger.error("boom")+ return+ yield+""",+ encoding="utf-8",+ )+ returncode, out, err = proc("runspider", str(path), "--pdb", input="")+ assert returncode == 0, err+ assert "(Pdb)" not in out++ def test_pdb_on_handled_failure(self, tmp_path: Path) -> None:+ path = tmp_path / "myspider.py"+ path.write_text(+ """+import scrapy+from scrapy.exceptions import IgnoreRequest++class IgnoreEverything:+ def process_request(self, request, spider):+ raise IgnoreRequest++class MySpider(scrapy.Spider):+ name = "myspider"+ custom_settings = {"DOWNLOADER_MIDDLEWARES": {IgnoreEverything: 500}}++ async def start(self):+ yield scrapy.Request("https://example.com")+""",+ encoding="utf-8",+ )+ returncode, out, err = proc("runspider", str(path), "--pdb", input="")+ assert returncode == 0, err+ assert "(Pdb)" not in outclass TestSettingsCommand: