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


##########
tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:
##########
@@ -0,0 +1,364 @@
+# 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.
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.theme.schemas import CreateThemeRequest, 
UpdateThemeRequest
+from superset.utils import json
+
+
[email protected]
+def mcp_server():
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth():
+    from unittest.mock import Mock, patch as _patch
+
+    with _patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
+# ---------------------------------------------------------------------------
+# Schema tests
+# ---------------------------------------------------------------------------
+
+
+def test_create_theme_request_string_json_data() -> None:
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data='{"token": {"colorPrimary": "#1677ff"}}',
+    )
+    assert req.theme_name == "Blue Theme"
+    assert '"colorPrimary"' in req.json_data
+
+
+def test_create_theme_request_dict_json_data() -> None:
+    """json_data accepts a native dict and serializes it to a JSON string."""
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data={"token": {"colorPrimary": "#1677ff"}},
+    )
+    assert isinstance(req.json_data, str)
+    parsed = json.loads(req.json_data)
+    assert parsed["token"]["colorPrimary"] == "#1677ff"
+
+
+def test_create_theme_request_missing_name_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(json_data='{"token": {}}')
+
+
+def test_create_theme_request_missing_json_data_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(theme_name="My Theme")
+
+
+# ---------------------------------------------------------------------------
+# Tool logic tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_theme(id: int = 42, theme_name: str = "Blue Theme") -> 
MagicMock:
+    theme = MagicMock()
+    theme.id = id
+    theme.theme_name = theme_name
+    theme.json_data = '{"token": {"colorPrimary": "#1677ff"}}'
+    return theme
+
+
[email protected]
+async def test_create_theme_success(mcp_server: object) -> None:
+    """Happy path: theme created and ID returned."""
+    mock_theme = _make_mock_theme()
+
+    with (
+        patch("superset.mcp_service.theme.tool.create_theme.db") as mock_db,
+        patch(
+            "superset.mcp_service.theme.tool.create_theme.Theme",
+            return_value=mock_theme,
+        ),
+    ):
+        mock_db.session.flush = MagicMock()
+
+        async with Client(mcp_server) as client:
+            request = CreateThemeRequest(
+                theme_name="Blue Theme",
+                json_data='{"token": {"colorPrimary": "#1677ff"}}',
+            )
+            result = await client.call_tool(
+                "create_theme", {"request": request.model_dump()}
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["id"] == 42
+    assert data["theme_name"] == "Blue Theme"
+    assert data["error"] is None
+
+
[email protected]
+async def test_create_theme_with_dict_json_data(mcp_server: object) -> None:
+    """Tool accepts json_data as a dict (native object) from LLM clients."""
+    mock_theme = _make_mock_theme()
+
+    with (
+        patch("superset.mcp_service.theme.tool.create_theme.db") as mock_db,
+        patch(
+            "superset.mcp_service.theme.tool.create_theme.Theme",
+            return_value=mock_theme,
+        ),
+    ):
+        mock_db.session.flush = MagicMock()
+
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "create_theme",
+                {
+                    "request": {
+                        "theme_name": "Blue Theme",
+                        "json_data": {"token": {"colorPrimary": "#1677ff"}},
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["id"] == 42
+    assert data["error"] is None
+
+
[email protected]
+async def test_create_theme_validation_error_empty_name(mcp_server: object) -> 
None:
+    """Empty theme name is caught by ThemePostSchema and returned as error."""
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "create_theme",
+            {
+                "request": {
+                    "theme_name": "   ",
+                    "json_data": '{"token": {}}',
+                }
+            },
+        )
+        data = json.loads(result.content[0].text)
+
+    assert data["id"] is None
+    assert data["error"] is not None
+    assert "empty" in str(data["error"]).lower()
+
+
[email protected]
+async def test_create_theme_validation_error_invalid_json(mcp_server: object) 
-> None:
+    """Malformed json_data string is caught by ThemePostSchema."""
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "create_theme",
+            {
+                "request": {
+                    "theme_name": "Test",
+                    "json_data": "not-valid-json{{{",
+                }
+            },
+        )
+        data = json.loads(result.content[0].text)
+
+    assert data["id"] is None
+    assert data["error"] is not None
+
+
+# ---------------------------------------------------------------------------
+# UpdateThemeRequest schema tests
+# ---------------------------------------------------------------------------
+
+
+def test_update_theme_request_dict_json_data() -> None:
+    """json_data accepts a native dict and serializes it."""
+    req = UpdateThemeRequest(
+        id=1,
+        json_data={"token": {"colorPrimary": "#ff0000"}},
+    )
+    assert isinstance(req.json_data, str)
+    parsed = json.loads(req.json_data)
+    assert parsed["token"]["colorPrimary"] == "#ff0000"
+
+
+def test_update_theme_request_no_json_data() -> None:
+    """json_data defaults to None (partial update)."""
+    req = UpdateThemeRequest(id=1, theme_name="New Name")
+    assert req.json_data is None
+    assert req.theme_name == "New Name"
+
+
+def test_update_theme_request_missing_id_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        UpdateThemeRequest(theme_name="Test")
+
+
+# ---------------------------------------------------------------------------
+# update_theme tool tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_existing_theme(
+    id: int = 10,
+    theme_name: str = "Old Theme",
+    json_data: str = '{"token": {"colorPrimary": "#aaaaaa"}}',
+    is_system: bool = False,
+) -> MagicMock:
+    theme = MagicMock()
+    theme.id = id
+    theme.theme_name = theme_name
+    theme.json_data = json_data
+    theme.is_system = is_system
+    return theme
+
+
[email protected]
+async def test_update_theme_success(mcp_server: object) -> None:
+    """Happy path: theme updated and new values returned."""
+    existing = _make_mock_existing_theme()
+    updated = _make_mock_existing_theme(
+        theme_name="New Name", json_data='{"token": {"colorPrimary": 
"#1677ff"}}'
+    )
+
+    with (
+        patch("superset.mcp_service.theme.tool.update_theme.ThemeDAO") as 
mock_dao,
+        patch(
+            "superset.mcp_service.theme.tool.update_theme.UpdateThemeCommand"
+        ) as mock_cmd_class,
+    ):

Review Comment:
   Already fixed. Commit `3298248dfa` moved `ThemeDAO` and `UpdateThemeCommand` 
from inside the async function body to module-level imports in 
`update_theme.py`. The current code has:
   
   ```python
   from superset.commands.theme.update import UpdateThemeCommand
   from superset.daos.theme import ThemeDAO
   ```
   
   at the top of the file, so 
`superset.mcp_service.theme.tool.update_theme.ThemeDAO` and 
`superset.mcp_service.theme.tool.update_theme.UpdateThemeCommand` are valid 
module-level attributes and the patch targets work correctly.



##########
superset/mcp_service/theme/schemas.py:
##########
@@ -0,0 +1,102 @@
+# 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.
+
+"""
+Pydantic schemas for theme-related MCP tool requests and responses.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+from superset.mcp_service.utils.schema_utils import parse_json_or_passthrough
+
+
+class CreateThemeRequest(BaseModel):
+    model_config = ConfigDict(populate_by_name=True)
+
+    theme_name: str = Field(
+        ...,
+        description="Name of the theme to create.",
+    )
+    json_data: str | dict[str, Any] = Field(
+        ...,
+        description=(
+            "Theme configuration as a JSON string or a dict object. "
+            'Example: {"token": {"colorPrimary": "#1677ff"}}'
+        ),
+    )
+
+    @field_validator("json_data", mode="before")
+    @classmethod
+    def normalize_json_data(cls, v: Any) -> str:
+        """Accept a dict or JSON string; always store as a JSON string."""
+        parsed = parse_json_or_passthrough(v, "json_data")
+        if isinstance(parsed, dict):
+            from superset.utils import json as superset_json
+
+            return superset_json.dumps(parsed)
+        return str(parsed)

Review Comment:
   The shared logic has already been extracted into the module-level 
`_json_data_to_str` helper. Both validators call that same function, so there 
is no duplicated logic — only the validator method name is repeated, which is 
required because Pydantic validators are per-class. The return types also 
differ: `CreateThemeRequest.normalize_json_data` returns `str` (always 
required), while `UpdateThemeRequest.normalize_json_data` returns `str | None` 
(field is optional). Keeping them as two small methods rather than a shared 
mixin avoids unnecessary complexity for two classes.



##########
tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:
##########
@@ -0,0 +1,364 @@
+# 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.
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.theme.schemas import CreateThemeRequest, 
UpdateThemeRequest
+from superset.utils import json
+
+
[email protected]
+def mcp_server():
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth():
+    from unittest.mock import Mock, patch as _patch
+
+    with _patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
+# ---------------------------------------------------------------------------
+# Schema tests
+# ---------------------------------------------------------------------------
+
+
+def test_create_theme_request_string_json_data() -> None:
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data='{"token": {"colorPrimary": "#1677ff"}}',
+    )
+    assert req.theme_name == "Blue Theme"
+    assert '"colorPrimary"' in req.json_data
+
+
+def test_create_theme_request_dict_json_data() -> None:
+    """json_data accepts a native dict and serializes it to a JSON string."""
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data={"token": {"colorPrimary": "#1677ff"}},
+    )
+    assert isinstance(req.json_data, str)
+    parsed = json.loads(req.json_data)
+    assert parsed["token"]["colorPrimary"] == "#1677ff"
+
+
+def test_create_theme_request_missing_name_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(json_data='{"token": {}}')
+
+
+def test_create_theme_request_missing_json_data_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(theme_name="My Theme")
+
+
+# ---------------------------------------------------------------------------
+# Tool logic tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_theme(id: int = 42, theme_name: str = "Blue Theme") -> 
MagicMock:
+    theme = MagicMock()
+    theme.id = id
+    theme.theme_name = theme_name
+    theme.json_data = '{"token": {"colorPrimary": "#1677ff"}}'
+    return theme
+
+
[email protected]
+async def test_create_theme_success(mcp_server: object) -> None:
+    """Happy path: theme created and ID returned."""
+    mock_theme = _make_mock_theme()
+
+    with (
+        patch("superset.mcp_service.theme.tool.create_theme.db") as mock_db,

Review Comment:
   Already fixed. Commit `3298248dfa` moved `db` and `Theme` to module-level 
imports in `create_theme.py`, so the patch target 
`superset.mcp_service.theme.tool.create_theme.db` is a valid module-level 
attribute. No `AttributeError` is raised.



-- 
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