This is an automated email from the ASF dual-hosted git repository.

aminghadersohi pushed a commit to branch fix-datasource-samples-response-404
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 80785183dbf28be14d3a2f469aa615f37858955d
Author: Amin Ghadersohi <[email protected]>
AuthorDate: Tue Nov 17 14:05:35 2026 +0000

    fix(datasource): return 404 instead of 500 from /datasource/samples when 
the datasource is not found
    
    Datasource is a plain BaseView, so the BaseApi-only response_404() helper
    does not exist on it. The guest branch of /datasource/samples (non-dataset
    datasource type, or missing dataset/dashboard) and the non-guest dataset
    pre-fetch called it, raised AttributeError, and handle_api_exception turned
    that into a 500. Return json_error_response(..., status=404) like the
    neighbouring 403/400 responses.
    
    The tests use a view stand-in specced on Datasource so a call to an
    attribute the view does not have fails instead of being auto-created.
---
 superset/views/datasource/views.py              | 10 +--
 tests/unit_tests/views/datasource/views_test.py | 91 +++++++++++++++++++++++--
 2 files changed, 91 insertions(+), 10 deletions(-)

diff --git a/superset/views/datasource/views.py 
b/superset/views/datasource/views.py
index eb5205f82df..7b658d9586d 100644
--- a/superset/views/datasource/views.py
+++ b/superset/views/datasource/views.py
@@ -76,7 +76,7 @@ _DATASET_TYPES = frozenset({DatasourceType.TABLE.value, 
DatasourceType.DATASET.v
 
 
 def _load_dataset_for_samples(
-    view: BaseSupersetView, params: dict[str, Any]
+    params: dict[str, Any],
 ) -> tuple[DatasourceModel | None, FlaskResponse | None]:
     """Pre-fetch and access-check the dataset for an authenticated request.
 
@@ -96,7 +96,7 @@ def _load_dataset_for_samples(
             database_id_or_uuid=params["datasource_id"],
         )
     except (DatasourceNotFound, DatasourceTypeNotSupportedError):
-        return None, view.response_404()
+        return None, json_error_response(_("Not found"), status=404)
     try:
         security_manager.raise_for_access(datasource=dataset)
     except SupersetSecurityException:
@@ -656,21 +656,21 @@ class Datasource(BaseSupersetView):
             # spaces, so the lookup below would validate whichever unrelated
             # SqlaTable happens to share the integer id.
             if params["datasource_type"] not in _DATASET_TYPES:
-                return self.response_404()
+                return json_error_response(_("Not found"), status=404)
             dashboard_id = params["dashboard_id"]
             dataset = DatasetDAO.find_by_id(
                 params["datasource_id"], skip_base_filter=True
             )
             dashboard = DashboardDAO.find_by_id(dashboard_id, 
skip_base_filter=True)
             if not (dashboard and dataset):
-                return self.response_404()
+                return json_error_response(_("Not found"), status=404)
             if not security_manager.can_drill_dataset_via_dashboard_access(
                 dataset,
                 dashboard,
             ):
                 return json_error_response(_("Forbidden"), status=403)
         else:
-            dataset, error_response = _load_dataset_for_samples(self, params)
+            dataset, error_response = _load_dataset_for_samples(params)
             if error_response is not None:
                 return error_response
 
diff --git a/tests/unit_tests/views/datasource/views_test.py 
b/tests/unit_tests/views/datasource/views_test.py
index 9083b1f4a21..19c7c420e55 100644
--- a/tests/unit_tests/views/datasource/views_test.py
+++ b/tests/unit_tests/views/datasource/views_test.py
@@ -74,6 +74,20 @@ def _view_self() -> MagicMock:
     return self
 
 
+def _spec_view_self() -> MagicMock:
+    """Stand-in for a Datasource view instance restricted to its real 
attributes.
+
+    ``Datasource`` is a plain ``BaseView``, so FAB's ``BaseApi``-only helpers
+    (``response_404`` and friends) are absent; a bare ``MagicMock`` would mask
+    a call to one of them.
+    """
+    from superset.views.datasource.views import Datasource
+
+    self = MagicMock(spec=Datasource)
+    self.json_response = MagicMock(return_value="ok")
+    return self
+
+
 def _save_orm_dataset(**overrides: Any) -> MagicMock:
     """Stand-in for the dataset ``save`` loads, defaulting to a physical one.
 
@@ -1653,8 +1667,8 @@ def 
test_samples_guest_with_dashboard_gets_404_for_non_dataset_type(
     unrelated table shares the integer id.
     """
     mock_security_manager.is_guest_user.return_value = True
+    mock_json_error_response.return_value = "not-found-response"
 
-    view = _view_self()
     app = Flask(__name__)
     with app.test_request_context(
         "/datasource/samples?datasource_type=semantic_view&datasource_id=1"
@@ -1662,12 +1676,79 @@ def 
test_samples_guest_with_dashboard_gets_404_for_non_dataset_type(
         method="POST",
         json={},
     ):
-        result = _get_view_func("samples")(view)
+        result = _get_view_func("samples")(_spec_view_self())
 
-    assert result == view.response_404.return_value
-    view.response_404.assert_called_once()
+    assert result == "not-found-response"
+    mock_json_error_response.assert_called_once_with("Not found", status=404)
     mock_dataset_dao.find_by_id.assert_not_called()
-    mock_json_error_response.assert_not_called()
+    mock_get_samples.assert_not_called()
+
+
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.DashboardDAO")
+@patch("superset.views.datasource.views.DatasetDAO")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.security_manager", 
new_callable=MagicMock)
[email protected]("missing", ["dataset", "dashboard"])
+def test_samples_guest_gets_404_when_dataset_or_dashboard_is_missing(
+    mock_security_manager: MagicMock,
+    mock_json_error_response: MagicMock,
+    mock_dataset_dao: MagicMock,
+    mock_dashboard_dao: MagicMock,
+    mock_get_samples: MagicMock,
+    missing: str,
+) -> None:
+    """A guest naming a nonexistent dataset or dashboard gets 404, not a 
500."""
+    mock_security_manager.is_guest_user.return_value = True
+    mock_json_error_response.return_value = "not-found-response"
+    if missing == "dataset":
+        mock_dataset_dao.find_by_id.return_value = None
+    else:
+        mock_dashboard_dao.find_by_id.return_value = None
+
+    app = Flask(__name__)
+    with app.test_request_context(
+        
"/datasource/samples?datasource_type=table&datasource_id=1&dashboard_id=5",
+        method="POST",
+        json={},
+    ):
+        result = _get_view_func("samples")(_spec_view_self())
+
+    assert result == "not-found-response"
+    mock_json_error_response.assert_called_once_with("Not found", status=404)
+    
mock_security_manager.can_drill_dataset_via_dashboard_access.assert_not_called()
+    mock_get_samples.assert_not_called()
+
+
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.DatasourceDAO.get_datasource")
+@patch("superset.views.datasource.views.security_manager", 
new_callable=MagicMock)
+def test_samples_returns_404_when_dataset_is_not_found(
+    mock_security_manager: MagicMock,
+    mock_get_datasource: MagicMock,
+    mock_json_error_response: MagicMock,
+    mock_get_samples: MagicMock,
+) -> None:
+    """An authenticated user naming a nonexistent dataset gets 404, not a 
500."""
+    from superset.daos.exceptions import DatasourceNotFound
+
+    mock_security_manager.is_guest_user.return_value = False
+    mock_get_datasource.side_effect = DatasourceNotFound()
+    mock_json_error_response.return_value = "not-found-response"
+
+    app = Flask(__name__)
+    with app.test_request_context(
+        "/datasource/samples?datasource_type=table&datasource_id=1",
+        method="POST",
+        json={},
+    ):
+        result = _get_view_func("samples")(_spec_view_self())
+
+    assert result == "not-found-response"
+    mock_json_error_response.assert_called_once_with("Not found", status=404)
     mock_get_samples.assert_not_called()
 
 

Reply via email to