From 34ff721d9da025b3bad03fe4190f7578b16b1739 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Sun, 4 Nov 2018 13:38:02 +0100 Subject: [PATCH] fix: Dont crash when client is bound inside of push_scope See #159 --- sentry_sdk/hub.py | 11 ++++++++++- tests/test_basics.py | 13 +++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/sentry_sdk/hub.py b/sentry_sdk/hub.py index cf8cf64537..42f0be04bd 100644 --- a/sentry_sdk/hub.py +++ b/sentry_sdk/hub.py @@ -90,7 +90,16 @@ def __enter__(self): return scope def __exit__(self, exc_type, exc_value, tb): - assert self._hub.pop_scope_unsafe() == self._layer, "popped wrong scope" + layer = self._hub.pop_scope_unsafe() + assert layer[1] == self._layer[1], "popped wrong scope" + if layer[0] != self._layer[0]: + warning = ( + "init() called inside of pushed scope. This might be entirely " + "legitimate but usually occurs when initializing the SDK inside " + "a request handler or task/job function. Try to initialize the " + "SDK as early as possible instead." + ) + logger.warning(warning) class Hub(with_metaclass(HubMeta)): diff --git a/tests/test_basics.py b/tests/test_basics.py index 8daa2a5b83..26a18f2276 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -224,3 +224,16 @@ def test_integration_scoping(): logger.warning("This is not a warning") assert len(events) == 1 + + +def test_client_initialized_within_scope(sentry_init, capture_events, caplog): + caplog.set_level(logging.WARNING) + + sentry_init(debug=True) + + with push_scope(): + sentry_init() + + record, = (x for x in caplog.records if x.levelname == "WARNING") + + assert record.msg.startswith("init() called inside of pushed scope.")