blob: 493779ff704c8f612572bfb132d8e0a43a49936b [file]
# 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.
import logging
import uuid
from datetime import datetime
from unittest.mock import MagicMock, patch, PropertyMock
import pytest
from flask import current_app
from parameterized import parameterized
from sqlalchemy.orm.session import Session
from superset.connectors.sqla.models import SqlaTable
from superset.models.core import Database
from superset.models.slice import id_or_uuid_filter, set_related_perm, Slice
class TestSlice:
"""Test cases for Slice model functionality."""
@parameterized.expand(
[
("numeric_id", "123"),
("uuid_string", "550e8400-e29b-41d4-a716-446655440000"),
]
)
def test_slice_get_calls_filter_correctly(self, test_name, id_or_uuid):
"""Test Slice.get() calls filter() correctly for ID and UUID."""
with patch("superset.models.slice.db") as mock_db:
# Setup mock chain
mock_query = MagicMock()
mock_filtered_query = MagicMock()
mock_db.session.query.return_value = mock_query
mock_query.filter.return_value = mock_filtered_query
mock_filtered_query.one_or_none.return_value = None
# Call the method
result = Slice.get(id_or_uuid)
# Verify correct methods called
mock_db.session.query.assert_called_once_with(Slice)
mock_query.filter.assert_called_once() # Not filter_by!
mock_filtered_query.one_or_none.assert_called_once()
assert result is None
@parameterized.expand(
[
("numeric_id", "123"),
("large_id", "999999"),
("uuid_string", str(uuid.uuid4())),
]
)
def test_slice_get_no_type_error(self, test_name, input_value):
"""Verify Slice.get() doesn't raise TypeError for various inputs."""
try:
result = Slice.get(input_value)
# Success - no TypeError, result can be None or a Slice
assert result is None or hasattr(result, "id")
except TypeError as e:
if "filter_by() takes 1 positional argument" in str(e):
pytest.fail(
f"filter_by() bug exists: Slice.get('{input_value}') failed with {e}" # noqa: E501
)
else:
raise
@parameterized.expand(
[
("numeric_id", "123"),
("uuid_format", "550e8400-e29b-41d4-a716-446655440000"),
("invalid_string", "not-a-number"),
("integer_id", 123),
# str.isdigit() is True for "²" (superscript 2) but int()
# rejects it; must not raise and must fall through to the uuid
# branch instead of the int(id_or_uuid) branch.
("non_decimal_digit", "²"),
]
)
def test_id_or_uuid_filter(self, test_name, input_value):
"""Test id_or_uuid_filter returns correct BinaryExpression."""
result = id_or_uuid_filter(input_value)
assert result is not None
def test_datasource_url_returns_none_when_datasource_lacks_explore_url(self):
"""datasource_url() must not raise when the datasource has no explore_url.
Charts whose datasource resolves to a Query (or any other type without
explore_url) used to raise AttributeError, which caused the entire chart
list API response to fail instead of just skipping that one chart.
"""
slc = Slice()
slc.id = 1
# Simulate a datasource object that does NOT have explore_url (e.g. Query)
mock_datasource = MagicMock(spec=[]) # spec=[] means no attributes at all
slc.table = mock_datasource
result = slc.datasource_url()
assert result is None
def test_datasource_url_returns_explore_url_when_present(self):
"""datasource_url() returns the datasource explore_url when it exists."""
slc = Slice()
slc.id = 1
mock_table = MagicMock()
mock_table.explore_url = "/explore/?datasource_type=table&datasource_id=1"
slc.table = mock_table
result = slc.datasource_url()
assert result == "/explore/?datasource_type=table&datasource_id=1"
def test_datasource_url_returns_none_when_no_datasource(self):
"""datasource_url() returns None when there is no datasource."""
slc = Slice()
slc.id = 1
slc.table = None
result = slc.datasource_url()
assert result is None
@staticmethod
def _semantic_view_slice() -> Slice:
"""Build a chart on a semantic view, with a colliding table also attached.
The table stands in for a regular dataset that happens to share the
numeric id; it must never leak into the semantic-view chart's display.
"""
slc = Slice()
slc.id = 1
slc.datasource_type = "semantic_view"
slc.datasource_id = 2
view = MagicMock()
view.name = "orders"
view.url = "/semantic_view/abc/"
view.explore_url = "/explore/?datasource_type=semantic_view&datasource_id=2"
view.link = "<a>orders</a>"
slc.semantic_view = view
table = MagicMock()
table.name = "public.colliding_table"
table.explore_url = "/explore/?datasource_type=table&datasource_id=2"
slc.table = table
return slc
def test_datasource_url_uses_semantic_view_explore_url(self) -> None:
"""A semantic-view chart links to the view's Explore page, not a table's."""
slc = self._semantic_view_slice()
assert (
slc.datasource_url()
== "/explore/?datasource_type=semantic_view&datasource_id=2"
)
def test_datasource_name_text_uses_semantic_view_name(self) -> None:
"""A semantic-view chart is named after the view (no schema prefix)."""
slc = self._semantic_view_slice()
assert slc.datasource_name_text() == "orders"
def test_display_datasource_never_falls_back_across_types(self) -> None:
"""A semantic-view chart with no view resolves to None, not to a table."""
slc = self._semantic_view_slice()
slc.semantic_view = None
assert slc._display_datasource() is None
assert slc.datasource_url() is None
assert slc.datasource_name_text() is None
def test_table_chart_display_is_unchanged_by_semantic_view_relationship(
self,
) -> None:
"""A table chart ignores ``semantic_view`` even if it is populated."""
slc = self._semantic_view_slice()
slc.datasource_type = "table"
assert slc.datasource_url() == "/explore/?datasource_type=table&datasource_id=2"
assert slc.datasource_name_text() == "public.colliding_table"
def test_datasource_edit_url_and_link_use_semantic_view(self) -> None:
"""Edit URL and legacy link come from the view for a semantic-view chart."""
slc = self._semantic_view_slice()
assert slc.datasource_edit_url == "/semantic_view/abc/"
assert slc.datasource_link() == "<a>orders</a>"
def test_datasource_link_is_none_when_unresolved(self) -> None:
"""A chart whose datasource cannot be resolved has no link, no error."""
slc = self._semantic_view_slice()
slc.semantic_view = None
assert slc.datasource_link() is None
assert slc.datasource_edit_url is None
def test_icons_names_the_semantic_view(self) -> None:
"""icons uses the semantic view's name and edit URL for its tooltip."""
slc = self._semantic_view_slice()
html = slc.icons
assert 'title="orders"' in html
assert 'href="/semantic_view/abc/"' in html
@parameterized.expand(
[
("json_string", '"foo"'),
("json_array", "[1, 2]"),
("json_integer", "42"),
("json_null", "null"),
]
)
def test_form_data_falls_back_for_non_dict_params(self, test_name, params_value):
"""form_data must not raise when params is valid JSON but not a dict."""
slc = Slice()
slc.id = 7
slc.viz_type = "table"
slc.datasource_id = 3
slc.datasource_type = "table"
slc.params = params_value
result = slc.form_data
assert isinstance(result, dict)
assert result["slice_id"] == 7
assert result["viz_type"] == "table"
assert result["datasource"] == "3__table"
def test_icons_escapes_datasource_html(self):
"""icons must HTML-escape the datasource name and edit URL."""
slc = Slice()
with (
patch.object(
Slice,
"datasource_edit_url",
new_callable=PropertyMock,
return_value='/x"onmouseover=alert(1)',
),
patch.object(
Slice,
"datasource_name_text",
return_value="<img src=x onerror=alert(1)>",
),
):
html = slc.icons
# The injected tag and attribute-breakout quote are escaped.
assert "<img" not in html
assert '"onmouseover' not in html
def test_thumbnail_url_is_router_relative_at_root(app_context: None) -> None:
"""thumbnail_url uses url_for, so at root it keeps the legacy shape."""
slc = Slice()
slc.id = 42
with patch.object(
Slice, "digest", new_callable=PropertyMock, return_value="abc123"
):
with current_app.test_request_context("/"):
url = slc.thumbnail_url
assert url == "/api/v1/chart/42/thumbnail/abc123/"
def test_thumbnail_url_carries_app_root_prefix(app_context: None) -> None:
"""Under a subdirectory deployment the serialized thumbnail URL must carry
the application root, because the frontend treats thumbnail_url as an
already-prefixed raw fetch target (it is excluded from
normalizeBackendUrls and never passed through ensureAppRoot)."""
slc = Slice()
slc.id = 42
with patch.object(
Slice, "digest", new_callable=PropertyMock, return_value="abc123"
):
with current_app.test_request_context(
"/", base_url="http://example.com/superset/"
):
url = slc.thumbnail_url
assert url == "/superset/api/v1/chart/42/thumbnail/abc123/"
def test_thumbnail_url_is_none_without_digest(app_context: None) -> None:
slc = Slice()
slc.id = 42
with patch.object(Slice, "digest", new_callable=PropertyMock, return_value=None):
with current_app.test_request_context("/"):
assert slc.thumbnail_url is None
def test_thumbnail_url_works_outside_request_context(app_context: None) -> None:
"""The property must stay callable from out-of-request callers (CLI,
celery tasks): with no request there is no SCRIPT_NAME to honor, so it
falls back to the router-relative shape instead of raising."""
slc = Slice()
slc.id = 42
with patch.object(
Slice, "digest", new_callable=PropertyMock, return_value="abc123"
):
url = slc.thumbnail_url
assert url == "/api/v1/chart/42/thumbnail/abc123/"
def test_set_related_perm_unknown_datasource_type_fails_closed_and_warns(
caplog: pytest.LogCaptureFixture,
) -> None:
"""sc-119782: an unknown ``datasource_type`` must not KeyError inside the
before_insert/before_update listener and abort the flush. It fails closed —
a chart that started with a valid perm (e.g. once a ``table``) and is
updated to an unknown type has its denormalized perm columns cleared, so it
loses access rather than resolving under the stale perm — and logs a
warning."""
target: Slice = Slice(
slice_name="unknown-type chart",
datasource_id=3,
# ``druid`` is used precisely because it is no longer a registered
# DatasourceDAO source, so the lookup resolves to None.
datasource_type="druid",
)
# Simulate an existing chart whose perms were denormalized from a real
# datasource before its type was mutated to an unknown value.
target.perm = "[db].[table](id:1)"
target.catalog_perm = "[db].[catalog]"
target.schema_perm = "[db].[schema]"
with caplog.at_level(logging.WARNING, logger="superset.models.slice"):
# Pre-fix this raised KeyError on ``DatasourceDAO.sources[...]``.
set_related_perm(MagicMock(), MagicMock(), target)
# Fail closed: the stale perms are cleared, not carried forward.
assert target.perm is None
assert target.catalog_perm is None
assert target.schema_perm is None
assert "unknown datasource_type" in caplog.text
assert "druid" in caplog.text
def test_set_related_perm_unknown_type_without_datasource_id_fails_closed() -> None:
"""The datasource-type lookup runs before the ``datasource_id`` guard, so an
unknown-type slice with no ``datasource_id`` still fails closed — its perm
columns are cleared — rather than raising KeyError."""
target: Slice = Slice(slice_name="orphan chart", datasource_type="druid")
# Pre-set the perms so the assertion proves the clearing branch ran, not
# that they were merely never set.
target.perm = "[db].[table](id:1)"
target.catalog_perm = "[db].[catalog]"
target.schema_perm = "[db].[schema]"
set_related_perm(MagicMock(), MagicMock(), target)
assert target.perm is None
assert target.catalog_perm is None
assert target.schema_perm is None
def test_set_related_perm_known_type_denormalizes_perms_from_datasource() -> None:
"""A known ``datasource_type`` still copies the datasource's perm columns
onto the chart — the common path must keep working after the ``.get()``
guard."""
target: Slice = Slice(
slice_name="table chart",
datasource_id=5,
datasource_type="table",
)
ds: MagicMock = MagicMock()
ds.perm = "[db].[table](id:5)"
ds.catalog_perm = "[db].[catalog]"
ds.schema_perm = "[db].[schema]"
mock_db: MagicMock
with patch("superset.models.slice.db") as mock_db:
query: MagicMock = mock_db.session.query.return_value
query.filter_by.return_value.first.return_value = ds
set_related_perm(MagicMock(), MagicMock(), target)
assert target.perm == "[db].[table](id:5)"
assert target.catalog_perm == "[db].[catalog]"
assert target.schema_perm == "[db].[schema]"
def _slice_with_stale_perms(datasource_id: int | None) -> Slice:
"""A known-type chart still carrying perms denormalized from its dataset."""
target: Slice = Slice(
slice_name="table chart",
datasource_id=datasource_id,
datasource_type="table",
)
target.perm = "[db].[old_table](id:9)"
target.catalog_perm = "[db].[catalog]"
target.schema_perm = "[db].[schema]"
return target
def test_set_related_perm_missing_dataset_fails_closed(
session: Session, app_context: None
) -> None:
"""sc-119912: a known-type chart whose dataset row no longer exists has its
perm columns cleared, rather than keeping access through the stale perm."""
SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member
target: Slice = _slice_with_stale_perms(datasource_id=9)
set_related_perm(MagicMock(), MagicMock(), target)
assert target.perm is None
assert target.catalog_perm is None
assert target.schema_perm is None
def test_set_related_perm_without_datasource_id_fails_closed() -> None:
"""sc-119912: a known-type chart with no ``datasource_id`` cannot resolve a
datasource, so its stale perm columns are cleared."""
target: Slice = _slice_with_stale_perms(datasource_id=None)
set_related_perm(MagicMock(), MagicMock(), target)
assert target.perm is None
assert target.catalog_perm is None
assert target.schema_perm is None
def test_set_related_perm_resolves_soft_deleted_dataset(
session: Session, app_context: None
) -> None:
"""A soft-deleted dataset is restorable, not missing: its charts keep the
dataset's perms instead of being failed closed by the visibility filter."""
SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member
database: Database = Database(database_name="db", sqlalchemy_uri="sqlite://")
dataset: SqlaTable = SqlaTable(table_name="trashed", database=database)
session.add(dataset)
session.flush()
dataset.deleted_at = datetime(2026, 1, 1)
session.flush()
target: Slice = _slice_with_stale_perms(datasource_id=dataset.id)
set_related_perm(MagicMock(), MagicMock(), target)
assert dataset.perm
assert target.perm == dataset.perm
assert target.catalog_perm == dataset.catalog_perm
assert target.schema_perm == dataset.schema_perm
def test_get_query_context_returns_none_without_stored_context() -> None:
"""No query_context stored: return None without touching the factory."""
slc = Slice(slice_name="no context", query_context=None)
assert slc.get_query_context() is None
def test_get_query_context_returns_none_on_malformed_json(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Malformed JSON is logged and returns None rather than raising."""
slc = Slice(slice_name="malformed", query_context="{not valid json")
with caplog.at_level(logging.ERROR, logger="superset.models.slice"):
assert slc.get_query_context() is None
assert "Malformed json" in caplog.text
@pytest.mark.parametrize(
"query_context",
[
'{"queries": [{"metrics": ["count"]}]}', # missing datasource
'{"datasource": {"id": 1, "type": "table"}}', # missing queries
],
)
def test_get_query_context_returns_none_when_metadata_incomplete(
query_context: str, caplog: pytest.LogCaptureFixture
) -> None:
"""apache/superset#35774: a stored query_context missing 'datasource' or
'queries' must not reach QueryContextFactory.create() -- it requires both
as keyword-only arguments and would raise a raw TypeError. The chart
should fail closed (None) with a clear log message instead, so a legacy
row saved before the ChartPostSchema/ChartPutSchema validation existed
degrades gracefully rather than crashing every read."""
slc = Slice(slice_name="incomplete", query_context=query_context)
slc.id = 7
slc.query_context_factory = MagicMock()
with caplog.at_level(logging.ERROR, logger="superset.models.slice"):
result = slc.get_query_context()
assert result is None
slc.query_context_factory.create.assert_not_called()
assert "missing required" in caplog.text
def test_get_query_context_calls_factory_with_complete_metadata() -> None:
"""A complete query_context is passed through to the factory, with
current_slice bound in."""
slc = Slice(
slice_name="complete",
query_context=(
'{"datasource": {"id": 1, "type": "table"}, '
'"queries": [{"metrics": ["count"]}]}'
),
)
mock_factory = MagicMock()
slc.query_context_factory = mock_factory
result = slc.get_query_context()
assert result is mock_factory.create.return_value
mock_factory.create.assert_called_once_with(
datasource={"id": 1, "type": "table"},
queries=[{"metrics": ["count"]}],
current_slice=slc,
)
def test_get_query_context_calls_factory_with_empty_queries() -> None:
"""An empty 'queries' list is a complete, valid query_context -- it must
still reach the factory rather than being treated as missing."""
slc = Slice(
slice_name="empty-queries",
query_context='{"datasource": {"id": 1, "type": "table"}, "queries": []}',
)
mock_factory = MagicMock()
slc.query_context_factory = mock_factory
result = slc.get_query_context()
assert result is mock_factory.create.return_value
mock_factory.create.assert_called_once_with(
datasource={"id": 1, "type": "table"},
queries=[],
current_slice=slc,
)