Skip to content

Commit 264b16f

Browse files
mikebridgeMike Bridge
andauthored
test(semantic-layer): pin review follow-ups for dashboard and Explore fixes (#46364)
Co-authored-by: Mike Bridge <michael.bridge@ext.preset.io>
1 parent c224903 commit 264b16f

7 files changed

Lines changed: 141 additions & 34 deletions

File tree

‎docs/developer_docs/semantic-query-errors.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ Its `SemanticQueryErrorCode` accepts `UNSUPPORTED_QUERY`, `UNSUPPORTED_OFFSET`,
3131

3232
Use `UNSUPPORTED_GROUP_OTHERS_METRIC` when a provider cannot combine a selected
3333
metric into the remaining-series bucket, such as an average or distinct count
34-
computed from grouped results. Its guidance identifies Group remaining as "Others"
34+
computed from grouped results. Its guidance names the `Group remaining as "Others"` control
3535
and suggests turning it off or choosing a sum, count, minimum, or maximum metric.
3636
It does not change which aggregations the provider supports. Providers compatible
3737
with older SDKs should fall back to `UNSUPPORTED_QUERY` when this enum member is

‎superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/axisColumn.test.tsx‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@
1717
* under the License.
1818
*/
1919
import { act, render } from '@testing-library/react';
20-
import { ChartDataResponseResult } from '@superset-ui/core';
20+
import {
21+
AxisType,
22+
ChartDataResponseResult,
23+
TimeGranularity,
24+
} from '@superset-ui/core';
2125
import { GenericDataType } from '@apache-superset/core/common';
2226
import { supersetTheme, ThemeProvider } from '@apache-superset/core/theme';
2327
import EchartsTimeseries from '../../src/Timeseries/EchartsTimeseries';
@@ -56,6 +60,15 @@ afterEach(() => {
5660
});
5761

5862
test.each([
63+
[
64+
'semantic_view',
65+
'ORDERS.ORDER_DATE',
66+
'Order date',
67+
OrientationType.Vertical,
68+
false,
69+
true,
70+
],
71+
['table', 'order_date', 'Order date', OrientationType.Vertical, true, true],
5972
['table', 'segment', 'Market segment', OrientationType.Vertical, false],
6073
[
6174
'semantic_view',
@@ -83,15 +96,25 @@ test.each([
8396
],
8497
] as const)(
8598
'%s axis %s displayed as %s (%s, mixed=%s) emits column identity',
86-
async (datasourceType, column, label, orientation, mixed) => {
99+
async (
100+
datasourceType,
101+
column,
102+
label,
103+
orientation,
104+
mixed,
105+
temporal: boolean = false,
106+
) => {
87107
jest.useFakeTimers();
88-
const value = 'AUTOMOBILE';
108+
const value = temporal ? Date.UTC(2026, 0, 1) : 'AUTOMOBILE';
89109
const query: ChartDataResponseResult & {
90110
label_map: Record<string, string[]>;
91111
} = {
92112
data: [{ [column]: value, count: 3 }],
93113
colnames: [column, 'count'],
94-
coltypes: [GenericDataType.String, GenericDataType.Numeric],
114+
coltypes: [
115+
temporal ? GenericDataType.Temporal : GenericDataType.String,
116+
GenericDataType.Numeric,
117+
],
95118
label_map: { count: ['count'] },
96119
annotation_data: null,
97120
cache_key: null,
@@ -120,6 +143,7 @@ test.each([
120143
metrics: ['count'],
121144
groupby: [],
122145
orientation,
146+
...(temporal && { timeGrainSqla: TimeGranularity.MONTH }),
123147
};
124148
const setDataMask = jest.fn();
125149
const onContextMenu = jest.fn();
@@ -139,6 +163,7 @@ test.each([
139163
}),
140164
);
141165
expect(transformed.xAxis.label).toBe(label);
166+
if (temporal) expect(transformed.xAxis.type).toBe(AxisType.Time);
142167
render(
143168
<ThemeProvider theme={supersetTheme}>
144169
<EchartsMixedTimeseries {...transformed} {...commonProps} />
@@ -158,6 +183,7 @@ test.each([
158183
}),
159184
);
160185
expect(transformed.xAxis.label).toBe(label);
186+
if (temporal) expect(transformed.xAxis.type).toBe(AxisType.Time);
161187
render(
162188
<ThemeProvider theme={supersetTheme}>
163189
<EchartsTimeseries {...transformed} {...commonProps} />
@@ -170,7 +196,7 @@ test.each([
170196
seriesName: 'count',
171197
seriesIndex: 0,
172198
dataIndex: 0,
173-
name: value,
199+
name: String(value),
174200
data:
175201
orientation === OrientationType.Horizontal ? [3, value] : [value, 3],
176202
event: { stop: jest.fn(), event: { clientX: 10, clientY: 20 } },
@@ -192,9 +218,20 @@ test.each([
192218
? undefined
193219
: expect.objectContaining({
194220
extraFormData: {
195-
filters: [{ col: column, op: 'IN', val: [value] }],
221+
filters: [
222+
temporal
223+
? {
224+
col: column,
225+
op: 'TEMPORAL_RANGE',
226+
val: expect.any(String),
227+
}
228+
: { col: column, op: 'IN', val: [value] },
229+
],
230+
...(temporal && { time_range: expect.any(String) }),
196231
},
197-
filterState: expect.objectContaining({ selectedValues: [value] }),
232+
filterState: expect.objectContaining({
233+
selectedValues: temporal ? [expect.any(String)] : [value],
234+
}),
198235
}),
199236
context: expect.objectContaining({
200237
drillToDetail: [expect.objectContaining({ col: column, val: value })],

‎superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterConfigurationLink/useFilterConfigModal.test.tsx‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -137,17 +137,18 @@ test.each([
137137
);
138138

139139
test.each([false, true])(
140-
'names the unavailable dataset from a validation dict, display controls=%s',
140+
'renders the endpoint validation dict, display controls=%s',
141141
async failControls => {
142-
// Dataset validation returns normalized_messages() via response_422.
142+
// Both endpoints return 400 for schema errors and 422 for dataset validation.
143+
const detail = failControls
144+
? 'Field may not be null.'
145+
: 'The native filters reference datasets that are not available: 42';
143146
const failure = {
144-
status: 422,
147+
status: failControls ? 400 : 422,
145148
body: {
146-
message: {
147-
native_filter_configuration: [
148-
'The native filters reference datasets that are not available: 42',
149-
],
150-
},
149+
message: failControls
150+
? { modified: [detail] }
151+
: { native_filter_configuration: [detail] },
151152
},
152153
};
153154
fetchMock.route(
@@ -162,7 +163,7 @@ test.each([false, true])(
162163
expect(store.getState()).toMatchObject({
163164
messageToasts: [
164165
{
165-
text: `Your ${failControls ? 'display control' : 'filter'} changes were not saved: The native filters reference datasets that are not available: 42`,
166+
text: `Your ${failControls ? 'display control' : 'filter'} changes were not saved: ${detail}`,
166167
},
167168
],
168169
});

‎superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterValue.test.tsx‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import getFormDataWithExtraFilters from 'src/dashboard/util/charts/getFormDataWi
3838
const mockRequestChartData = jest.fn();
3939
const mockGetClientErrorObject = jest.fn();
4040
const mockSuperChartProps = jest.fn();
41+
let mockRenderSelectPlugin = false;
4142
jest.mock('src/components/Chart/chartAction', () => ({
4243
requestChartDataResolved: (...args: unknown[]) =>
4344
mockRequestChartData(...args),
@@ -52,6 +53,22 @@ jest.mock('@superset-ui/core', () => {
5253
}),
5354
SuperChart: (props: Record<string, unknown>) => {
5455
mockSuperChartProps(props);
56+
if (mockRenderSelectPlugin) {
57+
const SelectPlugin = jest.requireActual<
58+
typeof import('src/filters/components/Select/SelectFilterPlugin')
59+
>('src/filters/components/Select/SelectFilterPlugin').default;
60+
const transform = jest.requireActual<
61+
typeof import('src/filters/components/Select/transformProps')
62+
>('src/filters/components/Select/transformProps').default;
63+
return (
64+
<SelectPlugin
65+
{...transform(new original.ChartProps(props))}
66+
showOverflow={Boolean(props.showOverflow)}
67+
isRefreshing={Boolean(props.isRefreshing)}
68+
appSection={original.AppSection.Dashboard}
69+
/>
70+
);
71+
}
5572
return (
5673
<div data-test="mock-super-chart" data-chart-type={props.chartType}>
5774
SuperChart
@@ -137,6 +154,7 @@ function renderFilterValue(
137154
}
138155

139156
beforeEach(() => {
157+
mockRenderSelectPlugin = false;
140158
jest.clearAllMocks();
141159
// Exercise the real parsing so each rejection shape is handled as in
142160
// production.
@@ -735,7 +753,29 @@ test.each([false, true])(
735753
filterState: { value: ['US'] },
736754
extraFormData: { filters: [{ col: 'country', op: 'IN', val: ['US'] }] },
737755
};
738-
const change = await emitFromPlugin(filter, mask);
756+
let change: jest.Mock;
757+
if (defaultToFirstItem) {
758+
mockRenderSelectPlugin = true;
759+
mockRequestChartData.mockResolvedValue([
760+
{
761+
data: [{ country: 'US' }, { country: 'CA' }],
762+
colnames: ['country'],
763+
coltypes: [1],
764+
},
765+
]);
766+
change = jest.fn();
767+
renderFilterValue({ filter, onFilterSelectionChange: change });
768+
await waitFor(() =>
769+
expect(change).toHaveBeenCalledWith(
770+
filter,
771+
expect.objectContaining({
772+
filterState: expect.objectContaining({ value: ['US'] }),
773+
}),
774+
),
775+
);
776+
} else {
777+
change = await emitFromPlugin(filter, mask);
778+
}
739779
const emitted: DataMask = change.mock.lastCall[1];
740780
const result = getFormDataWithExtraFilters({
741781
chart: {

‎superset-frontend/src/explore/components/controls/DatasourceControl/DatasourceControl.test.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -765,17 +765,12 @@ test('should verify DatasourceControl callback fires on save', async () => {
765765
// The existing callback tests provide sufficient coverage for metric creation workflows
766766
// Future enhancement could add MetricsControl integration when test infrastructure supports it
767767

768-
test.each(
769-
['semantic_view', 'table', 'query'].flatMap(type =>
770-
[true, false].map(saved => ({ type, saved })),
771-
),
772-
)(
773-
'datasource SQL Lab action respects datasource $type (saved=$saved)',
774-
async ({ type, saved }) => {
768+
test.each(['semantic_view', 'table', 'query'])(
769+
'datasource SQL Lab action respects datasource %s',
770+
async type => {
775771
const props = createProps({
776772
value: `25__${type}`,
777773
datasource: { ...mockDatasource, type },
778-
form_data: saved ? { slice_id: 318 } : {},
779774
});
780775
render(<DatasourceControl {...props} />, { useRouter: true });
781776
await userEvent.click(await screen.findByTestId('datasource-menu-trigger'));

‎tests/unit_tests/commands/explore/test_get_explore_rls.py‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@
2727
from typing import Any
2828
from unittest.mock import MagicMock, patch, PropertyMock
2929

30+
import pytest
3031
from pytest_mock import MockerFixture
3132

3233
from superset.commands.explore.get import GetExploreCommand
3334
from superset.commands.explore.parameters import CommandParameters
3435
from superset.connectors.sqla.models import SqlaTable
36+
from superset.models.sql_lab import Query
3537
from superset.semantic_layers.models import SemanticView
3638

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

132134

133-
def test_explore_rls_lookup_uses_sql_dataset_identity(mocker: MockerFixture) -> None:
134-
"""A semantic view cannot inherit SQL RLS metadata from a matching numeric id."""
135+
@pytest.mark.parametrize("non_sql_type", ["semantic_view", "query"])
136+
def test_explore_rls_lookup_uses_sql_dataset_identity(
137+
mocker: MockerFixture, non_sql_type: str
138+
) -> None:
139+
"""Non-table datasources cannot inherit SQL RLS metadata by numeric id."""
135140
view: SemanticView = SemanticView(id=42, name="orders_view")
136141
dataset: SqlaTable = SqlaTable(id=42, table_name="orders")
142+
query: Query = Query(id=42)
143+
mocker.patch.object(
144+
Query, "data", new_callable=PropertyMock, return_value={"name": "query"}
145+
)
137146
mocker.patch.object(
138147
SemanticView,
139148
"data",
@@ -163,18 +172,22 @@ def test_explore_rls_lookup_uses_sql_dataset_identity(mocker: MockerFixture) ->
163172
).can_access.return_value = True
164173
datasource_lookup: MagicMock = mocker.patch(
165174
"superset.commands.explore.get.DatasourceDAO.get_datasource",
166-
side_effect=lambda kind, id: view if kind == "semantic_view" else dataset,
175+
side_effect=lambda kind, id: {
176+
"semantic_view": view,
177+
"table": dataset,
178+
"query": query,
179+
}[kind],
167180
)
168181
rls_lookup: MagicMock = mocker.patch(
169182
"superset.commands.explore.get.DatasetDAO.get_rls_filters_for_dataset",
170183
return_value=[_FULL_FILTER],
171184
)
172185

173-
view_result: dict[str, Any] | None = GetExploreCommand(
174-
CommandParameters(None, None, 42, "semantic_view", None)
186+
non_sql_result: dict[str, Any] | None = GetExploreCommand(
187+
CommandParameters(None, None, 42, non_sql_type, None)
175188
).run()
176-
assert view_result is not None
177-
assert view_result["dataset"].get("rls_filters", []) == []
189+
assert non_sql_result is not None
190+
assert non_sql_result["dataset"].get("rls_filters", []) == []
178191
rls_lookup.assert_not_called()
179192

180193
dataset_result: dict[str, Any] | None = GetExploreCommand(

‎tests/unit_tests/semantic_layers/mapper_test.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5874,7 +5874,7 @@ def test_dormant_grain_preserves_advertised_variants(
58745874
def test_categorical_legacy_grain_refuses_time_bounds(
58755875
mocker: MockerFixture, columns: list[str | AdhocColumn], bounds: str
58765876
) -> None:
5877-
"""Never send date bounds to the categorical axis or retarget its grain."""
5877+
"""Refuse bounded categorical axes with a grain; grainless bounds are separate."""
58785878
datasource: MagicMock = _dormant_grain_datasource(mocker, pa.string())
58795879
query: ValidatedQueryObject = ValidatedQueryObject(
58805880
datasource=datasource,
@@ -5899,6 +5899,27 @@ def test_categorical_legacy_grain_refuses_time_bounds(
58995899
assert not mapped.filters
59005900

59015901

5902+
def test_query_grain_on_text_variants_requires_temporal_axis(
5903+
mocker: MockerFixture,
5904+
) -> None:
5905+
"""Advertised text variants do not infer an axis for a query-level grain."""
5906+
datasource: MagicMock = _dormant_grain_datasource(mocker, pa.string())
5907+
datasource.implementation._dimensions.add(
5908+
Dimension("segment.month", "segment", pa.string(), grain=Grains.MONTH)
5909+
)
5910+
query: ValidatedQueryObject = ValidatedQueryObject(
5911+
datasource=datasource,
5912+
columns=["segment"],
5913+
metrics=["revenue"],
5914+
extras={"time_grain_sqla": "P1M"},
5915+
)
5916+
with pytest.raises(
5917+
QueryObjectValidationError,
5918+
match="A time column must be specified when a time grain is provided",
5919+
):
5920+
validate_query_object(query)
5921+
5922+
59025923
def test_categorical_legacy_attached_grain_refuses_time_bounds(
59035924
mocker: MockerFixture,
59045925
) -> None:

0 commit comments

Comments
 (0)