Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/developer_docs/semantic-query-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Its `SemanticQueryErrorCode` accepts `UNSUPPORTED_QUERY`, `UNSUPPORTED_OFFSET`,

Use `UNSUPPORTED_GROUP_OTHERS_METRIC` when a provider cannot combine a selected
metric into the remaining-series bucket, such as an average or distinct count
computed from grouped results. Its guidance identifies Group remaining as "Others"
computed from grouped results. Its guidance names the `Group remaining as "Others"` control
and suggests turning it off or choosing a sum, count, minimum, or maximum metric.
It does not change which aggregations the provider supports. Providers compatible
with older SDKs should fall back to `UNSUPPORTED_QUERY` when this enum member is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
* under the License.
*/
import { act, render } from '@testing-library/react';
import { ChartDataResponseResult } from '@superset-ui/core';
import {
AxisType,
ChartDataResponseResult,
TimeGranularity,
} from '@superset-ui/core';
import { GenericDataType } from '@apache-superset/core/common';
import { supersetTheme, ThemeProvider } from '@apache-superset/core/theme';
import EchartsTimeseries from '../../src/Timeseries/EchartsTimeseries';
Expand Down Expand Up @@ -56,6 +60,15 @@ afterEach(() => {
});

test.each([
[
'semantic_view',
'ORDERS.ORDER_DATE',
'Order date',
OrientationType.Vertical,
false,
true,
],
['table', 'order_date', 'Order date', OrientationType.Vertical, true, true],
['table', 'segment', 'Market segment', OrientationType.Vertical, false],
[
'semantic_view',
Expand Down Expand Up @@ -83,15 +96,25 @@ test.each([
],
] as const)(
'%s axis %s displayed as %s (%s, mixed=%s) emits column identity',
async (datasourceType, column, label, orientation, mixed) => {
async (
datasourceType,
column,
label,
orientation,
mixed,
temporal: boolean = false,
) => {
jest.useFakeTimers();
const value = 'AUTOMOBILE';
const value = temporal ? Date.UTC(2026, 0, 1) : 'AUTOMOBILE';
const query: ChartDataResponseResult & {
label_map: Record<string, string[]>;
} = {
data: [{ [column]: value, count: 3 }],
colnames: [column, 'count'],
coltypes: [GenericDataType.String, GenericDataType.Numeric],
coltypes: [
temporal ? GenericDataType.Temporal : GenericDataType.String,
GenericDataType.Numeric,
],
label_map: { count: ['count'] },
annotation_data: null,
cache_key: null,
Expand Down Expand Up @@ -120,6 +143,7 @@ test.each([
metrics: ['count'],
groupby: [],
orientation,
...(temporal && { timeGrainSqla: TimeGranularity.MONTH }),
};
const setDataMask = jest.fn();
const onContextMenu = jest.fn();
Expand All @@ -139,6 +163,7 @@ test.each([
}),
);
expect(transformed.xAxis.label).toBe(label);
if (temporal) expect(transformed.xAxis.type).toBe(AxisType.Time);
render(
<ThemeProvider theme={supersetTheme}>
<EchartsMixedTimeseries {...transformed} {...commonProps} />
Expand All @@ -158,6 +183,7 @@ test.each([
}),
);
expect(transformed.xAxis.label).toBe(label);
if (temporal) expect(transformed.xAxis.type).toBe(AxisType.Time);
render(
<ThemeProvider theme={supersetTheme}>
<EchartsTimeseries {...transformed} {...commonProps} />
Expand All @@ -170,7 +196,7 @@ test.each([
seriesName: 'count',
seriesIndex: 0,
dataIndex: 0,
name: value,
name: String(value),
data:
orientation === OrientationType.Horizontal ? [3, value] : [value, 3],
event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
Expand All @@ -192,9 +218,20 @@ test.each([
? undefined
: expect.objectContaining({
extraFormData: {
filters: [{ col: column, op: 'IN', val: [value] }],
filters: [
temporal
? {
col: column,
op: 'TEMPORAL_RANGE',
val: expect.any(String),
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
}
: { col: column, op: 'IN', val: [value] },
],
...(temporal && { time_range: expect.any(String) }),
},
filterState: expect.objectContaining({ selectedValues: [value] }),
filterState: expect.objectContaining({
selectedValues: temporal ? [expect.any(String)] : [value],
}),
}),
context: expect.objectContaining({
drillToDetail: [expect.objectContaining({ col: column, val: value })],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,18 @@ test.each([
);

test.each([false, true])(
'names the unavailable dataset from a validation dict, display controls=%s',
'renders the endpoint validation dict, display controls=%s',
async failControls => {
// Dataset validation returns normalized_messages() via response_422.
// Customizations uses response_400(error.messages); filters uses response_422.
const detail = failControls
? 'Field may not be null.'
: 'The native filters reference datasets that are not available: 42';
const failure = {
status: 422,
status: failControls ? 400 : 422,
body: {
message: {
native_filter_configuration: [
'The native filters reference datasets that are not available: 42',
],
},
message: failControls
? { modified: [detail] }
: { native_filter_configuration: [detail] },
},
};
fetchMock.route(
Expand All @@ -162,7 +163,7 @@ test.each([false, true])(
expect(store.getState()).toMatchObject({
messageToasts: [
{
text: `Your ${failControls ? 'display control' : 'filter'} changes were not saved: The native filters reference datasets that are not available: 42`,
text: `Your ${failControls ? 'display control' : 'filter'} changes were not saved: ${detail}`,
},
],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import getFormDataWithExtraFilters from 'src/dashboard/util/charts/getFormDataWi
const mockRequestChartData = jest.fn();
const mockGetClientErrorObject = jest.fn();
const mockSuperChartProps = jest.fn();
let mockRenderSelectPlugin = false;
jest.mock('src/components/Chart/chartAction', () => ({
requestChartDataResolved: (...args: unknown[]) =>
mockRequestChartData(...args),
Expand All @@ -52,6 +53,22 @@ jest.mock('@superset-ui/core', () => {
}),
SuperChart: (props: Record<string, unknown>) => {
mockSuperChartProps(props);
if (mockRenderSelectPlugin) {
const SelectPlugin = jest.requireActual<
typeof import('src/filters/components/Select/SelectFilterPlugin')
>('src/filters/components/Select/SelectFilterPlugin').default;
const transform = jest.requireActual<
typeof import('src/filters/components/Select/transformProps')
>('src/filters/components/Select/transformProps').default;
return (
<SelectPlugin
{...transform(new original.ChartProps(props))}
showOverflow={Boolean(props.showOverflow)}
isRefreshing={Boolean(props.isRefreshing)}
appSection={original.AppSection.Dashboard}
/>
);
}
return (
<div data-test="mock-super-chart" data-chart-type={props.chartType}>
SuperChart
Expand Down Expand Up @@ -137,6 +154,7 @@ function renderFilterValue(
}

beforeEach(() => {
mockRenderSelectPlugin = false;
jest.clearAllMocks();
// Exercise the real parsing so each rejection shape is handled as in
// production.
Expand Down Expand Up @@ -735,7 +753,29 @@ test.each([false, true])(
filterState: { value: ['US'] },
extraFormData: { filters: [{ col: 'country', op: 'IN', val: ['US'] }] },
};
const change = await emitFromPlugin(filter, mask);
let change: jest.Mock;
if (defaultToFirstItem) {
mockRenderSelectPlugin = true;
mockRequestChartData.mockResolvedValue([
{
data: [{ country: 'US' }, { country: 'CA' }],
colnames: ['country'],
coltypes: [1],
},
]);
change = jest.fn();
renderFilterValue({ filter, onFilterSelectionChange: change });
await waitFor(() =>
expect(change).toHaveBeenCalledWith(
filter,
expect.objectContaining({
filterState: expect.objectContaining({ value: ['US'] }),
}),
),
);
} else {
change = await emitFromPlugin(filter, mask);
}
const emitted: DataMask = change.mock.lastCall[1];
const result = getFormDataWithExtraFilters({
chart: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -765,17 +765,12 @@ test('should verify DatasourceControl callback fires on save', async () => {
// The existing callback tests provide sufficient coverage for metric creation workflows
// Future enhancement could add MetricsControl integration when test infrastructure supports it

test.each(
['semantic_view', 'table', 'query'].flatMap(type =>
[true, false].map(saved => ({ type, saved })),
),
)(
'datasource SQL Lab action respects datasource $type (saved=$saved)',
async ({ type, saved }) => {
test.each(['semantic_view', 'table', 'query'])(
'datasource SQL Lab action respects datasource %s',
async type => {
const props = createProps({
value: `25__${type}`,
datasource: { ...mockDatasource, type },
form_data: saved ? { slice_id: 318 } : {},
});
render(<DatasourceControl {...props} />, { useRouter: true });
await userEvent.click(await screen.findByTestId('datasource-menu-trigger'));
Expand Down
27 changes: 20 additions & 7 deletions tests/unit_tests/commands/explore/test_get_explore_rls.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
from typing import Any
from unittest.mock import MagicMock, patch, PropertyMock

import pytest
from pytest_mock import MockerFixture

from superset.commands.explore.get import GetExploreCommand
from superset.commands.explore.parameters import CommandParameters
from superset.connectors.sqla.models import SqlaTable
from superset.models.sql_lab import Query
from superset.semantic_layers.models import SemanticView

_FULL_FILTER: dict[str, Any] = {
Expand Down Expand Up @@ -130,10 +132,17 @@ def test_rls_empty_list_on_dao_exception(
assert datasource_data["rls_filters"] == []


def test_explore_rls_lookup_uses_sql_dataset_identity(mocker: MockerFixture) -> None:
"""A semantic view cannot inherit SQL RLS metadata from a matching numeric id."""
@pytest.mark.parametrize("non_sql_type", ["semantic_view", "query"])
def test_explore_rls_lookup_uses_sql_dataset_identity(
mocker: MockerFixture, non_sql_type: str
) -> None:
"""Non-table datasources cannot inherit SQL RLS metadata by numeric id."""
view: SemanticView = SemanticView(id=42, name="orders_view")
dataset: SqlaTable = SqlaTable(id=42, table_name="orders")
query: Query = Query(id=42)
mocker.patch.object(
Query, "data", new_callable=PropertyMock, return_value={"name": "query"}
)
mocker.patch.object(
SemanticView,
"data",
Expand Down Expand Up @@ -163,18 +172,22 @@ def test_explore_rls_lookup_uses_sql_dataset_identity(mocker: MockerFixture) ->
).can_access.return_value = True
datasource_lookup: MagicMock = mocker.patch(
"superset.commands.explore.get.DatasourceDAO.get_datasource",
side_effect=lambda kind, id: view if kind == "semantic_view" else dataset,
side_effect=lambda kind, id: {
"semantic_view": view,
"table": dataset,
"query": query,
}[kind],
)
rls_lookup: MagicMock = mocker.patch(
"superset.commands.explore.get.DatasetDAO.get_rls_filters_for_dataset",
return_value=[_FULL_FILTER],
)

view_result: dict[str, Any] | None = GetExploreCommand(
CommandParameters(None, None, 42, "semantic_view", None)
non_sql_result: dict[str, Any] | None = GetExploreCommand(
CommandParameters(None, None, 42, non_sql_type, None)
).run()
assert view_result is not None
assert view_result["dataset"].get("rls_filters", []) == []
assert non_sql_result is not None
assert non_sql_result["dataset"].get("rls_filters", []) == []
rls_lookup.assert_not_called()

dataset_result: dict[str, Any] | None = GetExploreCommand(
Expand Down
23 changes: 22 additions & 1 deletion tests/unit_tests/semantic_layers/mapper_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5874,7 +5874,7 @@ def test_dormant_grain_preserves_advertised_variants(
def test_categorical_legacy_grain_refuses_time_bounds(
mocker: MockerFixture, columns: list[str | AdhocColumn], bounds: str
) -> None:
"""Never send date bounds to the categorical axis or retarget its grain."""
"""Refuse bounded categorical axes with a grain; grainless bounds are separate."""
datasource: MagicMock = _dormant_grain_datasource(mocker, pa.string())
query: ValidatedQueryObject = ValidatedQueryObject(
datasource=datasource,
Expand All @@ -5899,6 +5899,27 @@ def test_categorical_legacy_grain_refuses_time_bounds(
assert not mapped.filters


def test_query_grain_on_text_variants_requires_temporal_axis(
mocker: MockerFixture,
) -> None:
"""Advertised text variants do not infer an axis for a query-level grain."""
datasource: MagicMock = _dormant_grain_datasource(mocker, pa.string())
datasource.implementation._dimensions.add(
Dimension("segment.month", "segment", pa.string(), grain=Grains.MONTH)
)
query: ValidatedQueryObject = ValidatedQueryObject(
datasource=datasource,
columns=["segment"],
metrics=["revenue"],
extras={"time_grain_sqla": "P1M"},
)
with pytest.raises(
QueryObjectValidationError,
match="A time column must be specified when a time grain is provided",
):
validate_query_object(query)


def test_categorical_legacy_attached_grain_refuses_time_bounds(
mocker: MockerFixture,
) -> None:
Expand Down
Loading