codeant-ai-for-open-source[bot] commented on code in PR #40960:
URL: https://github.com/apache/superset/pull/40960#discussion_r3477249655


##########
tests/unit_tests/mcp_service/dashboard/tool/test_manage_native_filters.py:
##########
@@ -0,0 +1,588 @@
+# 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 the manage_native_filters MCP tool.
+
+Follows the pattern from test_add_chart_to_existing_dashboard.py:
+- Tests run through the async MCP Client (not direct function calls)
+- Patches applied at source locations (superset.daos.dashboard.*, etc.)
+- auth is mocked via the autouse mock_auth fixture
+
+Covers:
+- Adding a filter_select filter (full config shape, scope translation)
+- Adding a filter_time filter (with default time range)
+- Updating a filter (merge produces a FULL config, not a delta)
+- Removing a filter
+- Reordering filters (including incomplete-reorder validation)
+- Invalid dataset / column errors
+- Dashboard not found
+- Permission denied (DashboardForbiddenError)
+"""
+
+import logging
+from typing import Any
+from unittest.mock import Mock, patch
+
+import pytest
+from fastmcp import Client
+
+from superset.commands.dashboard.exceptions import DashboardForbiddenError
+from superset.mcp_service.app import mcp
+from superset.utils import json
+
+logging.basicConfig(level=logging.DEBUG)
+logger = logging.getLogger(__name__)
+
+DAO_FIND_BY_ID = "superset.daos.dashboard.DashboardDAO.find_by_id"
+DATASET_FIND_BY_ID = "superset.daos.dataset.DatasetDAO.find_by_id"
+COMMAND_PATH = 
"superset.commands.dashboard.update.UpdateDashboardNativeFiltersCommand"
+
+
[email protected]
+def mcp_server() -> object:
+    """Return the FastMCP app instance for use in MCP client tests."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth():
+    """Mock authentication for all tests."""
+    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
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+EXISTING_SELECT_FILTER = {
+    "id": "NATIVE_FILTER-existing1",
+    "type": "NATIVE_FILTER",
+    "filterType": "filter_select",
+    "name": "Region",
+    "description": "",
+    "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+    "targets": [{"datasetId": 5, "column": {"name": "region"}}],
+    "controlValues": {
+        "multiSelect": True,
+        "defaultToFirstItem": False,
+        "enableEmptyFilter": False,
+        "searchAllOptions": False,
+    },
+    "defaultDataMask": {"filterState": {"value": None}, "extraFormData": {}},
+    "cascadeParentIds": [],
+}
+
+EXISTING_TIME_FILTER = {
+    "id": "NATIVE_FILTER-existing2",
+    "type": "NATIVE_FILTER",
+    "filterType": "filter_time",
+    "name": "Time Range",
+    "description": "",
+    "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+    "targets": [{}],
+    "controlValues": {},
+    "defaultDataMask": {"filterState": {"value": None}, "extraFormData": {}},
+    "cascadeParentIds": [],
+}
+
+
+def _mock_dashboard(
+    id: int = 1,
+    filters: list[dict[str, Any]] | None = None,
+    chart_ids: list[int] | None = None,
+) -> Mock:
+    dashboard = Mock()
+    dashboard.id = id
+    dashboard.dashboard_title = "Test Dashboard"
+    dashboard.json_metadata = json.dumps({"native_filter_configuration": 
filters or []})
+    slices = []
+    for chart_id in chart_ids or [10, 11]:
+        slc = Mock()
+        slc.id = chart_id
+        slices.append(slc)
+    dashboard.slices = slices
+    return dashboard
+
+
+def _mock_dataset(columns: list[str] | None = None) -> Mock:
+    dataset = Mock()
+    dataset.id = 5
+    cols = []
+    for name in columns or ["region", "country", "ds"]:
+        col = Mock()
+        col.column_name = name
+        cols.append(col)
+    dataset.columns = cols
+    return dataset
+
+
+def _mock_command(captured: dict[str, Any]):
+    """Build a mock UpdateDashboardNativeFiltersCommand class.
+
+    Captures constructor args and returns the modified configuration
+    the way the real DAO would (existing filters with substitutions,
+    new filters appended, deletions removed).
+    """
+
+    def command_factory(dashboard_id, payload):
+        captured["dashboard_id"] = dashboard_id
+        captured["payload"] = payload
+
+        command = Mock()
+
+        def run():
+            current = captured.get("current_config", [])
+            deleted = payload.get("deleted", [])
+            modified = payload.get("modified", [])
+            result = []
+            for conf in current:
+                if conf["id"] in deleted:
+                    continue
+                replacement = next((m for m in modified if m["id"] == 
conf["id"]), None)
+                result.append(replacement if replacement else conf)
+            for m in modified:
+                if m["id"] not in [c["id"] for c in result]:
+                    result.append(m)
+            if reordered := list(payload.get("reordered", [])):
+                for m in modified:
+                    if m["id"] not in reordered:
+                        reordered.append(m["id"])
+                by_id = {c["id"]: c for c in result}
+                result = [by_id[fid] for fid in reordered if fid in by_id]
+            captured["result"] = result
+            return result
+
+        command.run = run
+        return command
+
+    return command_factory
+
+
+async def _call(mcp_server, request: dict[str, Any]) -> dict[str, Any]:
+    async with Client(mcp_server) as client:
+        result = await client.call_tool("manage_native_filters", {"request": 
request})
+        return json.loads(result.content[0].text)
+
+
+# ---------------------------------------------------------------------------
+# Add
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_add_filter_select(mcp_server):

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require per-test docstrings in test files when the test name is 
already self-describing and the module-level docstring covers the suite context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI 
Settings](https://app.codeant.ai/org/settings/learnings)*



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