diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 7936fa52bf..04a9a3d4e5 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -8,6 +8,7 @@ Looking to upgrade from Sentry SDK 1.x to 2.x? Here's a comprehensive list of wh ## Changed +- Subsequent calls to `sentry_sdk.set_user` will now update existing user data instead of overwriting it. To reset user data, call the function with an empty dictionary: `sentry_sdk.set_user({})` - The `BackgroundWorker` thread used to process events was renamed from `raven-sentry.BackgroundWorker` to `sentry-sdk.BackgroundWorker`. - The `reraise` function was moved from `sentry_sdk._compat` to `sentry_sdk.utils`. - Moved the contents of `tracing_utils_py3.py` to `tracing_utils.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`. diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index f1ce6890e5..c5d6019111 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -518,7 +518,12 @@ def user(self, value): def set_user(self, value): # type: (Optional[Dict[str, Any]]) -> None """Sets a user for the scope.""" - self._user = value + if value: + self._user = self._user or {} + self._user.update(value) + else: + self._user = None + if self._session is not None: self._session.update(user=value) diff --git a/tests/test_scope.py b/tests/test_scope.py index 88022e3920..dfa5fc2fa0 100644 --- a/tests/test_scope.py +++ b/tests/test_scope.py @@ -154,3 +154,41 @@ def test_load_trace_data_from_env(env, excepted_value): s = Scope() incoming_trace_data = s._load_trace_data_from_env() assert incoming_trace_data == excepted_value + + +def test_user_update(sentry_init, capture_events): + sentry_init() + events = capture_events() + + scope = Scope() + assert scope._user is None + + scope.set_user({"id": 23}) + assert scope._user == {"id": 23} + + scope.set_user({"email": "lucy@dogs.com"}) + assert scope._user == {"id": 23, "email": "lucy@dogs.com"} + + capture_exception(NameError(), scope=scope) + + (event,) = events + assert event["user"] == {"id": 23, "email": "lucy@dogs.com"} + + +def test_user_reset(sentry_init, capture_events): + sentry_init() + events = capture_events() + + scope = Scope() + assert scope._user is None + + scope.set_user({"id": 23, "email": "dottie@dogs.com"}) + assert scope._user == {"id": 23, "email": "dottie@dogs.com"} + + scope.set_user({}) + assert scope._user is None + + capture_exception(NameError(), scope=scope) + + (event,) = events + assert "user" not in event