diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index cec5e767c3..4fd22714cf 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -891,6 +891,7 @@ def user(self, value: "Optional[Dict[str, Any]]") -> None: def set_user(self, value: "Optional[Dict[str, Any]]") -> None: """Sets a user for the scope.""" self._user = value + session = self.get_isolation_scope()._session if session is not None: session.update(user=value) @@ -1753,7 +1754,11 @@ def _apply_user_attributes_to_telemetry( ("user.email", "email"), ("user.ip_address", "ip_address"), ): - if user_attribute in self._user and attribute_name not in attributes: + if ( + user_attribute in self._user + and attribute_name not in attributes + and self._user[user_attribute] is not None + ): attributes[attribute_name] = self._user[user_attribute] def _drop(self, cause: "Any", ty: str) -> "Optional[Any]": diff --git a/tests/test_scope.py b/tests/test_scope.py index 39a162be18..d7ce1f1ff8 100644 --- a/tests/test_scope.py +++ b/tests/test_scope.py @@ -68,6 +68,43 @@ def test_scope_flags_copy(): ] +def test_set_user(sentry_init, capture_events): + sentry_init() + events = capture_events() + + sentry_sdk.get_isolation_scope().set_user({"id": "42", "email": "bob@example.com"}) + capture_exception(NameError()) + assert events[-1]["user"] == {"id": "42", "email": "bob@example.com"} + + sentry_sdk.get_isolation_scope().set_user(None) + capture_exception(NameError()) + assert "user" not in events[-1] + + +def test_set_user_none_values_are_dropped_when_copying_to_attributes( + sentry_init, capture_items +): + sentry_init( + traces_sample_rate=1.0, + send_default_pii=True, + _experiments={"trace_lifecycle": "stream"}, + ) + items = capture_items("span") + + with sentry_sdk.traces.start_span(name="test_segment"): + sentry_sdk.get_isolation_scope().set_user( + {"email": "ada@beans.com", "username": None} + ) + capture_exception(NameError()) + + sentry_sdk.flush() + + segment = items[0].payload + + assert "user.name" not in segment["attributes"] + assert segment["attributes"]["user.email"] == "ada@beans.com" + + def test_merging(sentry_init, capture_events): sentry_init()