aminghadersohi commented on code in PR #40746:
URL: https://github.com/apache/superset/pull/40746#discussion_r3368405068


##########
superset/mcp_service/user/schemas.py:
##########
@@ -104,6 +104,27 @@ class UserInfo(BaseModel):
         "access via get_user_info; not available in list_users because roles "
         "is a relationship, not a selectable column)",
     )
+
+    @field_validator("roles", mode="before")
+    @classmethod
+    def _extract_role_names(cls, v: Any) -> list[str] | None:
+        """Coerce Role ORM objects to their .name strings."""
+        if v is None:
+            return None
+        if isinstance(v, str):
+            # Preserve Pydantic's default rejection of bare strings for 
list[str].
+            raise ValueError("roles must be a list, not a string")
+        result: list[str] = []
+        for item in v:
+            if isinstance(item, str):
+                result.append(item)
+            elif hasattr(item, "name"):
+                try:
+                    result.append(str(item.name))
+                except DetachedInstanceError:
+                    continue

Review Comment:
   `hasattr` is outside the `try` block. Python 3 `hasattr` only suppresses 
`AttributeError` — not `DetachedInstanceError`. If `item` is a real detached 
SQLAlchemy `Role` with `name` expired (e.g., after `session.commit()` with the 
default `expire_on_commit=True`), `hasattr(item, "name")` raises before the 
`try` block ever runs.
   
   The existing `serialize_user_object` wraps both the `hasattr` call and the 
attribute access in `try/except (AttributeError, DetachedInstanceError)`. The 
validator should follow the same pattern:
   
   ```suggestion
               else:
                   try:
                       if hasattr(item, "name"):
                           result.append(str(item.name))
                   except DetachedInstanceError:
                       continue
   ```



##########
tests/unit_tests/mcp_service/user/test_schemas.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Unit tests for user-related MCP schemas."""
+
+from unittest.mock import MagicMock
+
+import pytest
+from pydantic import ValidationError
+from sqlalchemy.orm.exc import DetachedInstanceError
+
+from superset.mcp_service.user.schemas import UserInfo, serialize_user_object
+
+
+def test_user_info_rejects_bare_string_for_roles() -> None:
+    """A plain string must not be silently split into individual characters."""
+    with pytest.raises(ValidationError):
+        UserInfo(roles="Admin")
+
+
+def test_user_info_preserves_empty_roles_list() -> None:
+    """Empty roles should remain [] so callers can distinguish it from None."""
+    info = UserInfo(roles=[])
+    assert info.roles == []
+
+
+def test_user_info_coerces_role_objects_to_names() -> None:
+    """Role-like ORM objects must be converted to their .name strings."""
+    role_admin = MagicMock()
+    role_admin.name = "Admin"
+    role_alpha = MagicMock()
+    role_alpha.name = "Alpha"
+
+    info = UserInfo(roles=[role_admin, role_alpha])
+
+    assert info.roles == ["Admin", "Alpha"]
+
+
+def test_user_info_ignores_role_with_detached_instance() -> None:
+    """Detached ORM roles must not blow up serialization."""
+    role_good = MagicMock()
+    role_good.name = "Admin"
+    role_detached = MagicMock()
+    role_detached.name = MagicMock(side_effect=DetachedInstanceError())

Review Comment:
   This mock fires the error at `str(item.name)` — MagicMock's `__str__` goes 
through `_mock_call` which checks `side_effect`, so that branch is exercised. 
For a real detached SQLAlchemy instance, the error fires at `hasattr(item, 
"name")` before the `try` block (Python 3 `hasattr` only catches 
`AttributeError`). A property-based stub or `__getattribute__` override raising 
`DetachedInstanceError` would cover the actual production failure point.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to