diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 05bdcad..80defc9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,9 +18,24 @@ jobs: - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} - - run: pip install ".[speedups,webhook-server,scrapy]" pytest + - run: pip install ".[speedups,webhook-server,scrapy]" sentry-sdk pytest - run: python -m pytest -q + # A client app brings its own sentry-sdk: SentryReporter runs on the newest of each major. The unit jobs run the newest. + sentry: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sentry-sdk: ['1.*', '2.*', '3.*'] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: '3.12' + - run: pip install . "sentry-sdk==${{ matrix.sentry-sdk }}" pytest + - run: python -m pytest -q tests/test_sentry_reporter.py + # The oldest Scrapy supported, the first with the async start() and handlers, and 2.19. The unit jobs run the newest. scrapy: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 90eb542..c4aabdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ To do: keep `web_scraping_api_read_timeout` above the scrape's `timeout`, or retry a `ReadTimeout` yourself if you need to. +### Fixed + +- `SentryReporter` works with sentry-sdk 3: it raised `ImportError: cannot import name 'push_scope'`, and the scrape + error never reached Sentry. It reports through `new_scope()` on sentry-sdk 2 and 3, and through `push_scope()` on + sentry-sdk 1.x, so an app keeps the sentry-sdk version it pins. On sentry-sdk 2 it no longer warns that + `push_scope` is deprecated. + ## 1.0.0 (2026-11-15) ### Breaking changes diff --git a/scrapfly/reporter/sentry.py b/scrapfly/reporter/sentry.py index b2aa487..d06edac 100644 --- a/scrapfly/reporter/sentry.py +++ b/scrapfly/reporter/sentry.py @@ -52,9 +52,9 @@ def __call__( scrape_api_response: Optional['ScrapeApiResponse'] = None, # noqa: F821 ): # Late import — already validated in __init__, safe to import here. - from sentry_sdk import capture_exception, push_scope + from sentry_sdk import capture_exception - with push_scope() as scope: + with self._new_scope() as scope: if scrape_api_response is not None: scope.set_tag('scrapfly_project', scrape_api_response.config['project']) scope.set_tag('scrapfly_env', scrape_api_response.config['env']) @@ -73,3 +73,18 @@ def __call__( if error is not None: capture_exception(error) + + @staticmethod + def _new_scope(): + """ + A scope forked from the current one, so the tags of a report stay on its own event. + + ``new_scope()`` exists since sentry-sdk 2.0 and ``push_scope()`` was removed in 3.0: + sentry-sdk 1.x takes ``push_scope()``. + """ + try: + from sentry_sdk import new_scope + except ImportError: + from sentry_sdk import push_scope as new_scope + + return new_scope() diff --git a/tests/test_sentry_reporter.py b/tests/test_sentry_reporter.py new file mode 100644 index 0000000..ae30eb9 --- /dev/null +++ b/tests/test_sentry_reporter.py @@ -0,0 +1,66 @@ +"""SentryReporter reports a scrape's tags and extras on its own event, on sentry-sdk 1.x, 2.x and 3.x, with no DeprecationWarning.""" + +import warnings + +import pytest + +sentry_sdk = pytest.importorskip("sentry_sdk") + +from scrapfly.reporter.sentry import SentryReporter + + +class FakeResponse: + config = {"project": "default", "env": "live", "url": "https://web-scraping.dev/products"} + scrape_result = { + "log_url": "https://scrapfly.io/dashboard/monitoring/log/01", + "url": "https://web-scraping.dev/products", + "status_code": 503, + } + error = {"code": "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE"} + + +@pytest.fixture +def events(): + captured = [] + # before_send returns None (the result of list.append), so no event leaves the process. + sentry_sdk.init( + dsn="https://key@localhost/1", + default_integrations=False, + before_send=lambda event, hint: captured.append(event), + ) + yield captured + sentry_sdk.init() + + +def test_a_report_carries_the_scrape_tags_and_extras_with_its_exception(events): + SentryReporter()(error=ValueError("boom"), scrape_api_response=FakeResponse()) + + [event] = events + assert event["exception"]["values"][-1]["type"] == "ValueError" + assert event["tags"] == { + "scrapfly_project": "default", + "scrapfly_env": "live", + "scrapfly_upstream_status_code": 503, + "scrapfly_error_code": "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE", + } + assert event["extra"]["scrape_config"] == FakeResponse.config + assert event["extra"]["log_url"] == "https://scrapfly.io/dashboard/monitoring/log/01" + assert event["extra"]["upstream_url"] == "https://web-scraping.dev/products" + + +def test_the_tags_of_a_report_stay_on_its_own_event(events): + SentryReporter()(error=ValueError("boom"), scrape_api_response=FakeResponse()) + sentry_sdk.capture_message("after the report") + + report, after = events + assert "scrapfly_error_code" in report["tags"] + assert "scrapfly_error_code" not in after.get("tags", {}) + assert "log_url" not in after.get("extra", {}) + + +def test_a_report_emits_no_deprecation_warning(events): + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + SentryReporter()(error=ValueError("boom"), scrape_api_response=FakeResponse()) + + assert len(events) == 1